diff --git a/sdk/search/azure-search-documents/CHANGELOG.md b/sdk/search/azure-search-documents/CHANGELOG.md index a73f0e1f2cbe..b17d3e5011a2 100644 --- a/sdk/search/azure-search-documents/CHANGELOG.md +++ b/sdk/search/azure-search-documents/CHANGELOG.md @@ -1,1233 +1,13 @@ # Release History -## 11.8.0-beta.6 (Unreleased) +## 1.0.0-beta.1 (Unreleased) -### Features Added - -### Breaking Changes - -### Bugs Fixed - -### Other Changes - -## 11.7.6 (2025-03-24) - -### Other Changes - -#### Dependency Updates - -- Upgraded `azure-json` from `1.4.0` to version `1.5.0`. -- Upgraded `azure-core-http-netty` from `1.15.10` to version `1.15.11`. -- Upgraded `azure-core-serializer-json-jackson` from `1.5.7` to version `1.5.8`. -- Upgraded `azure-core` from `1.55.2` to version `1.55.3`. - - -## 11.7.5 (2025-02-25) - -### Other Changes - -#### Dependency Updates - -- Upgraded `azure-core-http-netty` from `1.15.7` to version `1.15.10`. -- Upgraded `azure-core-serializer-json-jackson` from `1.5.4` to version `1.5.7`. -- Upgraded `azure-json` from `1.3.0` to version `1.4.0`. -- Upgraded `azure-core` from `1.54.1` to version `1.55.2`. - -## 11.8.0-beta.5 (2025-02-18) - -### Bugs Fixed - -- Fixed bug that made 2024-11-01-preview service version inaccessible. - -### Other Changes - -#### Dependency Updates - -- Upgraded `azure-core` from `1.54.1` to version `1.55.1`. -- Upgraded `azure-core-http-netty` from `1.15.7` to version `1.15.9`. -- Upgraded `azure-core-serializer-json-jackson` from `1.5.4` to version `1.5.6`. - -## 11.7.4 (2024-12-04) - -### Other Changes - -#### Dependency Updates - -- Upgraded `azure-core` from `1.53.0` to version `1.54.1`. -- Upgraded `azure-core-http-netty` from `1.15.5` to version `1.15.7`. -- Upgraded `azure-core-serializer-json-jackson` from `1.5.2` to version `1.5.4`. - - -## 11.8.0-beta.4 (2024-11-22) - -### Bugs Fixed - - - Fixed bug in the serialization of `SearchDocumentsResult` `debuginfo` property. - - Fixed missing properties bug in `SemanticSearchResults`. - - Added missing properties `debugInfo` and `semanticQueryRewritesResultType`. - -## 11.8.0-beta.3 (2024-11-20) - -### Bugs Fixed - -- Fixed a bug where `SearchOptions` was missing setters for `QueryDebugMode`, `QueryLanguage`, and `QuerySpellerType`. - -## 11.8.0-beta.2 (2024-11-18) - -### Features Added - -- `FacetResults` is now a recursive data structure to support hierarchical aggregation and facet filtering. -- `QueryAnswer` now supports a `maxCharLength` option to limit the character length of the answer. -- `QueryCaption` now supports a `maxCharLength` option to limit the character length of the caption. -- `VectorizableTextQuery` now supports a `queryRewrites` option to specify the number query rewrites the service will generate. -- `SemanticSearchOptions` now supports a `queryRewrites` option to specify the number query rewrites the service will generate. -- `VectorSearchCompression` now supports configuring the `rescoringOptoins`. -- `IndexingParametersConfiguration` now supports two additional options for `MarkdownParsingSubmode` and `MarkdownHeaderDepth`. -- Added a new skill: `DocumentIntelligenceLayoutSkill` that extracts content and layout information (as markdown), via Azure AI Services, from files within the enrichment pipeline. -- Added 2 subtypes of `CognitiveServiceAccounts`: `AzureCognitiveServiceAccount` and `AzureCognitiveServiceAccountKey`. - -### Other Changes - -#### Dependency Updates - -- Upgraded `azure-core` from `1.52.0` to version `1.54.1`. -- Upgraded `azure-core-http-netty` from `1.15.4` to version `1.15.7`. -- Upgraded `azure-core-serializer-json-jackson` from `1.5.1` to version `1.5.4`. - -## 11.7.3 (2024-10-27) - -### Other Changes - -#### Dependency Updates - -- Upgraded `azure-core-http-netty` from `1.15.4` to version `1.15.5`. -- Upgraded `azure-core-serializer-json-jackson` from `1.5.1` to version `1.5.2`. -- Upgraded `azure-core` from `1.52.0` to version `1.53.0`. - - -## 11.7.2 (2024-09-27) - -### Other Changes - -#### Dependency Updates - -- Upgraded `azure-json` from `1.2.0` to version `1.3.0`. -- Upgraded `azure-core-http-netty` from `1.15.3` to version `1.15.4`. -- Upgraded `azure-core-serializer-json-jackson` from `1.5.0` to version `1.5.1`. -- Upgraded `azure-core` from `1.51.0` to version `1.52.0`. - - -## 11.8.0-beta.1 (2024-09-23) - -### Features Added - -- `VectorSearchCompression` now supports `truncationDimension` which allows for specifying the number of dimensions to - truncate vectors to. -- `SplitSkill` now supports tokenization. -- `VectorQuery` now supports `filterOverride` which allow for vector queries to override the broader SearchRequest.filter to allow for vector queries to have more specific configurations -- `DocumentDebugInfo` is extended with vector scores for the result. - -### Other Changes - -- Migrate Search test from local auth to Microsoft Entra authentication. - -#### Dependency Updates - -- Upgraded `azure-core` from `1.51.0` to version `1.52.0`. -- Upgraded `azure-core-http-netty` from `1.15.3` to version `1.15.4`. -- Upgraded `azure-core-serializer-json-jackson` from `1.5.` to version `1.5.1`. -- Upgraded `azure-json` from `1.2.0` to version `1.3.0`. - - -## 11.7.1 (2024-08-24) - -### Other Changes - -#### Dependency Updates - -- Upgraded `azure-core-serializer-json-jackson` from `1.4.14` to version `1.5.0`. -- Upgraded `azure-core` from `1.50.0` to version `1.51.0`. -- Upgraded `azure-core-http-netty` from `1.15.2` to version `1.15.3`. -- Upgraded `azure-json` from `1.1.0` to version `1.2.0`. - -## 11.7.0 (2024-07-17) - -### Features Added - -- Added support for `2024-07-01` service version. -- `SemanticSearchOptions` now supports `semanticQuery`, which allows for specifying a semantic query that is only used - for semantic reranking. -- `VectorQuery` now supports `oversampling` and `weight`, which allows for specifying richer configurations on how - vector queries affect search results. -- Added support for `VectorizableTextQuery`, which allows for passing a text-based query that is vectorized service-side - by `VectorSearchVectorizer`s configured on the index so that vectorization doesn't need to happen before querying. -- Added support for "bring your own endpoint" with `VectorSearchVectorizer`, with implementations `AzureOpenAIVectorizer` - and `WebApiVectorizer`. This enables the service to use a user-provided configuration for vectorizing text, rather - than requiring all client-side calls to vectorize before querying, allowing for easier standardization of vectorization. -- Added support for compression with `VectorSearchCompression`, with implementations `BinaryQuantizationCompression` - and `ScalarQuantizationCompression`. This allows for reducing the size of vectors in the index, which can reduce - storage costs and improve querying performance. -- Added support for `VectorEncodingFormat`, which allows for specifying the encoding format of the vector data. -- Added support for `AzureOpenAIEmbeddingSkill`, which is a skill that uses the Azure OpenAI service to create text - embeddings during indexing. -- Added support for index projections with `SearchIndexerIndexProjection`, which allows for specifying how indexed - documents are projected in the index (or indexes). -- Added support for "narrow" types in `SearchFieldDataType`. This allows for specifying smaller types for vector fields - to reduce storage costs and improve querying performance. -- Added support for `SearchIndexerDataIdentity`, which allows for specifying the identity for the data source for the - indexer. -- `SearchField` and `SearchableField` now support `stored` and `vectorEncodingFormat` configurations. `stored` allows - for specifying behaviors on how the index will retain vector data (enabling the ability to reduce storage costs), and - `vectorEncodingFormat` allows for specifying the encoding format of the vector data. -- `OcrSkill` now supports `OcrLineEnding`, which allows for specifying the line ending character used by the OCR skill. -- `SplitSkill` now supports `maximumPagesToTake` and `pageOverlapLength`, which allows for specifying how the split - skill behaves when splitting documents into pages. -- `SearchServiceLimits` now supports `maxStoragePerIndexInBytes`, which shows the maximum storage allowed per index. - -### Breaking Changes - -- All service concepts that have been in preview but not included in the `2024-07-01` GA have been removed. This - includes concepts such as index aliases, normalizers, Azure Machine Learning skills, hybrid search, and more. - -### Other Changes - -- All polymorphic models now expose their discriminator value through a getter, where the getter is named after the - discriminator property such as `getOdataType()`. Super most polymorphic classes are no longer `abstract` to allow for - direct instantiation of the class. - -#### Dependency Updates - -- Upgraded `azure-core` from `1.49.1` to version `1.50.0`. -- Upgraded `azure-core-http-netty` from `1.15.1` to version `1.15.2`. -- Upgraded `azure-core-serializer-json-jackson` from `1.4.13` to version `1.4.14`. - -## 11.6.6 (2024-06-27) - -### Other Changes - -#### Dependency Updates - -- Upgraded `azure-core-serializer-json-jackson` from `1.4.12` to version `1.4.13`. -- Upgraded `azure-core` from `1.49.0` to version `1.49.1`. -- Upgraded `azure-core-http-netty` from `1.15.0` to version `1.15.1`. - -## 11.6.5 (2024-05-28) - -### Other Changes - -#### Dependency Updates - -- Upgraded `azure-core-serializer-json-jackson` from `1.4.11` to version `1.4.12`. -- Upgraded `azure-core` from `1.48.0` to version `1.49.0`. -- Upgraded `azure-core-http-netty` from `1.14.2` to version `1.15.0`. - -## 11.7.0-beta.3 (2024-05-07) - -### Features Added - -- Added support for `Byte[]` and `List` in `FieldBuilder` -- Added support for `HybridSearch` -- Index models added: `AIServicesVisionParameters`, `AIServicesVisionVectorizer`, `AIStudioModelCatalogName`, - `AzureMachineLearningParameters`, `AzureMachineLearningVectorizer`, `AzureOpenAIModelName`, `VectorEncodingFormat`, - `VisionVectorizeSkill` -- Search models added: `HybridCountAndFacetMode`, `HybridSearch`, `SearchScoreThreshold`, `VectorSimilarityThreshold`, - `VectorThreshold`, `VectorThresholdKind`, `VectorizableImageBinaryQuery`, `VectorizableImageUrlQuery` - -### Other Changes - -- Sample added for creating a vector fields index with reduced dimensions. - -#### Dependency Updates - -- Upgraded `azure-core` from `1.48.0` to version `1.49.0`. -- Upgraded `azure-core-http-netty` from `1.14.2` to version `1.15.0`. -- Upgraded `azure-core-serializer-json-jackson` from `1.4.11` to version `1.4.12`. - -## 11.6.4 (2024-04-23) - -### Other Changes - -#### Dependency Updates - -- Upgraded `azure-core` from `1.47.0` to version `1.48.0`. -- Upgraded `azure-core-http-netty` from `1.14.1` to version `1.14.2`. -- Upgraded `azure-core-serializer-json-jackson` from `1.4.10` to version `1.4.11`. - -## 11.6.3 (2024-03-20) - -### Other Changes - -#### Dependency Updates - -- Upgraded `azure-core-serializer-json-jackson` from `1.4.9` to version `1.4.10`. -- Upgraded `azure-core` from `1.46.0` to version `1.47.0`. -- Upgraded `azure-core-http-netty` from `1.14.0` to version `1.14.1`. - -## 11.7.0-beta.2 (2024-03-11) - -### Features Added - -- Added support for the java types `Byte` and `Short` to FieldBuilder. -- Added support for "isStored" annotation to FieldBuilder. -- Added `VectorSearchCompressionConfiguration` to `VectorSearch` - -### Breaking Changes - -- Replaced `SearchErrorException` with `ErrorResponseException` - -### Other Changes - -#### Dependency Updates - -- Upgraded `azure-core-serializer-json-jackson` to version `1.4.10`. -- Upgraded `azure-core-http-netty` to version `1.14.1`. -- Upgraded `azure-core` to version `1.47.0`. - -## 11.6.2 (2024-02-22) - -### Other Changes - -#### Dependency Updates - -- Upgraded `azure-core` from `1.45.1` to version `1.46.0`. -- Upgraded `azure-core-http-netty` from `1.13.11` to version `1.14.0`. - -## 11.7.0-beta.1 (2024-02-09) - -### Features Added - -- Exposing HttpPipeline within clients. - -### Other Changes - -- Rebranding Azure Cognitive Search to Azure AI Search within the SDK. -- Updated JavaDoc to assist with developer experience. -- Sample added to show how to maintain a consistent sessionId across multiple requests. - -## 11.6.1 (2023-12-06) - -### Other Changes - -#### Dependency Updates - -- Upgraded `azure-core-serializer-json-jackson` from `1.4.7` to version `1.4.8`. -- Upgraded `azure-core-http-netty` from `1.13.10` to version `1.13.11`. -- Upgraded `azure-core` from `1.45.0` to version `1.45.1`. - -## 11.6.0 (2023-11-13) - -### Features Added - -- Support for `VectorQuery` and configuring a `SearchIndex` for vector query and vector `SearchField`. -- Support for semantic search and configuring a `SearchIndex` semantic searching. -- Added `EntityLinkingSkill`, `PiiDetectionSkill`, a new version of `EntityRecognitionSkill` and support for setting - which version to use, and a new version of `SentimentSkill` and support for setting which version to use. - -### Breaking Changes - -- Deprecated `V1` version of `EntityRecognitionSkill` and `SentimentSkill` as these are deprecated on the service. -- Replaced Jackson Databind annotations with `azure-json` functionality for Search service models. - -### Other Changes - -#### Dependency Updates - -- Upgraded `azure-core-http-netty` from `1.13.9` to version `1.13.10`. -- Upgraded `azure-core-serializer-json-jackson` from `1.4.6` to version `1.4.7`. -- Upgraded `azure-core` from `1.44.1` to version `1.45.0`. - -## 11.5.12 (2023-10-20) - -### Other Changes - -#### Dependency Updates - -- Upgraded `azure-core-http-netty` from `1.13.7` to version `1.13.9`. -- Upgraded `azure-core-serializer-json-jackson` from `1.4.4` to version `1.4.6`. -- Upgraded `azure-core` from `1.43.0` to version `1.44.1`. - -## 11.6.0-beta.10 (2023-10-12) - -### Features Added - -- `SemanticQuery` has been added to `SearchOptions`, allowing the setting of a separate search query that will be solely - used for semantic reranking, semantic captions and semantic answers. - -### Breaking Changes - -- `SearchQueryVector` model has been replaced by `VectorQuery`. -- `SearchOptions` instance method `SearchOptions setVectors(List)` has been replaced by `SearchOptions setVectorQueries(List)`. -- `SearchOptions` instance method `SearchOptions setVectors(SearchQueryVector...)` has been replaced by `SearchOptions setVectorQueries(VectorQuery...)`. -- `SearchOptions` instance method `List getVectors()` has been replaced by `List getVectorQueries()`. -- `VectorSearch` instance property `List algorithmConfigurations` has been replaced by properties `List profiles`, - `List algorithms`, and `List vectorizers`. - -### Other Changes - -- Added additional models to support vector search. -- Updated vector search samples to use `VectorQuery`. - -#### Dependency Updates - -- Upgraded `azure-core-http-netty` from `1.13.7` to version `1.13.8`. -- Upgraded `azure-core-serializer-json-jackson` from `1.4.4` to version `1.4.5`. -- Upgraded `azure-core` from `1.43.0` to version `1.44.0`. - -## 11.5.11 (2023-09-22) - -### Other Changes - -#### Dependency Updates - -- Upgraded `azure-core-http-netty` from `1.13.6` to version `1.13.7`. -- Upgraded `azure-core-serializer-json-jackson` from `1.4.3` to version `1.4.4`. -- Upgraded `azure-core` from `1.42.0` to version `1.43.0`. - -## 11.6.0-beta.9 (2023-09-15) - -### Other Changes - -#### Dependency Updates - -- Upgraded `azure-core-http-netty` from `1.13.6` to version `1.13.7`. -- Upgraded `azure-core-serializer-json-jackson` from `1.4.3` to version `1.4.4`. -- Upgraded `azure-core` from `1.42.0` to version `1.43.0`. - -## 11.5.10 (2023-08-18) - -### Other Changes - -#### Dependency Updates - -- Upgraded `azure-core-serializer-json-jackson` from `1.4.2` to version `1.4.3`. -- Upgraded `azure-core-http-netty` from `1.13.5` to version `1.13.6`. -- Upgraded `azure-core` from `1.41.0` to version `1.42.0`. - -## 11.6.0-beta.8 (2023-08-11) - -### Features Added - -- Added FieldBuilder support for float data types. -- Added support for multi-vector searches. -- Adjusted method for setting `fields` in `SearchQueryVector` from `SearchQueryVector setFields(String)` to `SearchQueryVector setFields(String...)` for convenience. - -### Breaking Changes - -- `SearchOptions` method `SearchOptions setVector(SearchQueryVector)` has been replaced with `SearchOptions setVectors(SearchQueryVector...)` and `SearchOptions setVectors(List)` -- `SearchOptions` method `SearchQueryVector getVector()` has been replaced with `List getVectors()` - -### Other Changes - -- Added sample for multi-vector search. - -#### Dependency Updates - -- Upgraded `azure-core-http-netty` from `1.13.5` to version `1.13.6`. -- Upgraded `azure-core-serializer-json-jackson` from `1.4.2` to version `1.4.3`. -- Upgraded `azure-core` from `1.41.0` to version `1.42.0`. - -## 11.5.9 (2023-07-25) - -### Other Changes - -#### Dependency Updates - -- Upgraded `azure-core-http-netty` from `1.13.4` to version `1.13.5`. -- Upgraded `azure-core-serializer-json-jackson` from `1.4.1` to version `1.4.2`. -- Upgraded `azure-core` from `1.40.0` to version `1.41.0`. - - -## 11.6.0-beta.7 (2023-07-11) - -### Features Added - -- Added support for [Vector Search](https://learn.microsoft.com/azure/search/vector-search-overview) ([Examples](https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/VectorSearchExample.java)). - -### Breaking Changes - -- Deprecated `EntityRecognitionSkillVersion.V1` and `SentimentSkillVersion.V1`, and corresponding constructors in - `EntityRecognitionSkill` and `SentimentSkill`, use `EntityRecognitionSkillVersion.V3` and `SentimentSkillVersion.V3` - instead. See [Cognitive Search skill deprecated](https://learn.microsoft.com/azure/search/cognitive-search-skill-deprecated) - for more details. - -### Other Changes - -- Migrate test recordings to assets repo. - -## 11.5.8 (2023-06-09) - -### Other Changes - -- Properly set Index and Search Analyzer names in FieldBuilder - -#### Dependency Updates - -- Upgraded `azure-core` from `1.39.0` to version `1.40.0`. -- Upgraded `azure-core-serializer-json-jackson` from `1.4.0` to version `1.4.1`. -- Upgraded `azure-core-http-netty` from `1.13.3` to version `1.13.4`. - -## 11.5.7 (2023-05-23) - -### Other Changes - -#### Dependency Updates - -- Upgraded `azure-core-http-netty` from `1.13.2` to version `1.13.3`. -- Upgraded `azure-core` from `1.38.0` to version `1.39.0`. -- Upgraded `azure-core-serializer-json-jackson` from `1.3.1` to version `1.4.0`. - -## 11.6.0-beta.6 (2023-05-15) - -### Other Changes - -#### Dependency Updates - -- Upgraded `azure-core` from `1.38.0` to version `1.39.0`. -- Upgraded `azure-core-http-netty` from `1.13.2` to version `1.13.3`. -- Upgraded `azure-core-serializer-json-jackson` from `1.3.1` to version `1.4.0`. -- Upgraded `azure-json` from `1.0.0` to version `1.0.1`. - -## 11.5.6 (2023-04-21) - -### Other Changes - -#### Dependency Updates - -- Upgraded `azure-core` from `1.37.0` to version `1.38.0`. -- Upgraded `azure-core-http-netty` from `1.13.1` to version `1.13.2`. -- Upgraded `azure-core-serializer-json-jackson` from `1.3.0` to version `1.3.1`. - -## 11.5.5 (2023-03-16) - -### Other Changes - -#### Dependency Updates - -- Upgraded `azure-core-http-netty` from `1.13.0` to version `1.13.1`. -- Upgraded `azure-core-serializer-json-jackson` from `1.2.25` to version `1.3.0`. -- Upgraded `azure-core` from `1.36.0` to version `1.37.0`. - -## 11.6.0-beta.5 (2023-02-13) - -### Other Changes - -#### Dependency Updates - -- Upgraded `azure-core` from `1.35.0` to version `1.36.0`. -- Upgraded `azure-core-http-netty` from `1.12.8` to version `1.13.0`. -- Upgraded `azure-core-serializer-json-jackson` from `1.2.24` to version `1.2.25`. - -## 11.5.4 (2023-02-13) - -### Other Changes - -#### Dependency Updates - -- Upgraded `azure-core` from `1.35.0` to version `1.36.0`. -- Upgraded `azure-core-http-netty` from `1.12.8` to version `1.13.0`. -- Upgraded `azure-core-serializer-json-jackson` from `1.2.24` to version `1.2.25`. - -## 11.6.0-beta.4 (2023-01-13) - -### Other Changes - -#### Dependency Updates - -- Upgraded `azure-core` from `1.34.0` to version `1.35.0`. -- Upgraded `azure-core-http-netty` from `1.12.7` to version `1.12.8`. -- Upgraded `azure-core-serializer-json-jackson` from `1.2.23` to version `1.2.24`. - -## 11.5.3 (2023-01-12) - -### Other Changes - -#### Dependency Updates - -- Upgraded `azure-core` from `1.34.0` to version `1.35.0`. -- Upgraded `azure-core-http-netty` from `1.12.7` to version `1.12.8`. -- Upgraded `azure-core-serializer-json-jackson` from `1.2.23` to version `1.2.24`. - -## 11.6.0-beta.3 (2022-11-11) - -### Other Changes - -#### Dependency Updates - -- Upgraded `azure-core` from `1.33.0` to version `1.34.0`. -- Upgraded `azure-core-http-netty` from `1.12.6` to version `1.12.7`. -- Upgraded `azure-core-serializer-json-jackson` from `1.2.22` to version `1.2.23`. - -## 11.5.2 (2022-11-10) - -### Other Changes - -#### Dependency Updates - -- Upgraded `azure-core` from `1.33.0` to version `1.34.0`. -- Upgraded `azure-core-http-netty` from `1.12.6` to version `1.12.7`. -- Upgraded `azure-core-serializer-json-jackson` from `1.2.22` to version `1.2.23`. - -## 11.6.0-beta.2 (2022-10-12) - -### Bugs Fixed - -- [Bug fix for incorrect JSON property names](https://github.com/Azure/azure-sdk-for-java/pull/31388) -- -### Other Changes - -#### Dependency Updates - -- Upgraded `azure-core` from `1.32.0` to version `1.33.0`. -- Upgraded `azure-core-http-netty` from `1.12.5` to version `1.12.6`. -- Upgraded `azure-core-serializer-json-jackson` from `1.2.21` to version `1.2.22`. - -## 11.5.1 (2022-10-12) - -### Other Changes - -#### Dependency Updates - -- Upgraded `azure-core` from `1.32.0` to version `1.33.0`. -- Upgraded `azure-core-http-netty` from `1.12.5` to version `1.12.6`. -- Upgraded `azure-core-serializer-json-jackson` from `1.2.21` to version `1.2.22`. - -## 11.6.0-beta.1 (2022-09-06) - -### Features Added - -- All features from the `11.5.x` betas that weren't included in `11.5.0`. - -### Other Changes - -#### Dependency Updates - -- Upgraded `azure-core` from `1.31.0` to version `1.32.0`. -- Upgraded `azure-core-http-netty` from `1.12.4` to version `1.12.5`. -- Upgraded `azure-core-serializer-json-jackson` from `1.2.20` to version `1.2.21`. - -## 11.5.0 (2022-09-06) +- Azure Search client library for Java. This package contains Microsoft Azure Search client library. ### Features Added -- Added multi-cloud support via `SearchAudience` to allow users to select the Azure cloud where the resource is located. ([#30331](https://github.com/Azure/azure-sdk-for-java/pull/30331)) -- Added interfaces from `com.azure.core.client.traits` to `SearchIndexerClientBuilder`, `SearchIndexClientBuilder` - and `SearchClientBuilder`. - -### Other Changes - -- Doesn't include other features added in the `11.5.x` betas. To continue using those features upgrade to `11.6.0-beta.1`. - -#### Dependency Updates - -- Upgraded `azure-core` from `1.31.0` to version `1.32.0`. -- Upgraded `azure-core-http-netty` from `1.12.4` to version `1.12.5`. -- Upgraded `azure-core-serializer-json-jackson` from `1.2.20` to version `1.2.21`. - -## 11.4.13 (2022-08-19) - -### Other Changes - -#### Dependency Updates - -- Upgraded `azure-core` from `1.30.0` to version `1.31.0`. -- Upgraded `azure-core-http-netty` from `1.12.3` to version `1.12.4`. -- Upgraded `azure-core-serializer-json-jackson` from `1.2.19` to version `1.2.20`. - -## 11.5.0-beta.12 (2022-08-17) - -### Features Added - -- Added multi-cloud support via `SearchAudience` to allow users to select the Azure cloud where the resource is located. ([#30331](https://github.com/Azure/azure-sdk-for-java/pull/30331)) -- Added new languages to `ImageAnalysisSkillLanguage` and `OcrSkillLanguage`. ([#30363](https://github.com/Azure/azure-sdk-for-java/pull/30363)) - -### Other Changes - -- Added fluent setter overloads to subclasses that return the subclass type instead of the super class type - allowing for fluent calls to maintain type instead of requiring a type cast. - -#### Dependency Updates - -- Upgraded `azure-core` from `1.30.0` to version `1.31.0`. -- Upgraded `azure-core-http-netty` from `1.12.3` to version `1.12.4`. -- Upgraded `azure-core-serializer-json-jackson` from `1.2.19` to version `1.2.20`. - -## 11.5.0-beta.11 (2022-07-01) - -### Features Added - -- Added support for `LexicalNormalizer`s in `SimpleField` and `SearchableField` annotations. - -### Other Changes - -#### Dependency Updates - -- Upgraded `azure-core` from `1.29.1` to version `1.30.0`. -- Upgraded `azure-core-http-netty` from `1.12.2` to version `1.12.3`. -- Upgraded `azure-core-serializer-json-jackson` from `1.2.18` to version `1.2.19`. - -## 11.4.12 (2022-07-01) - -### Other Changes - -#### Dependency Updates - -- Upgraded `azure-core` from `1.29.1` to version `1.30.0`. -- Upgraded `azure-core-http-netty` from `1.12.2` to version `1.12.3`. -- Upgraded `azure-core-serializer-json-jackson` from `1.2.18` to version `1.2.19`. - -## 11.5.0-beta.10 (2022-06-07) - -### Bugs Fixed - -- Fixed a bug where a custom `ObjectSerializer`'s output wasn't being respected in regard to null field values. ([#29238](https://github.com/Azure/azure-sdk-for-java/pull/29238)) - -### Other Changes - -#### Dependency Updates - -- Upgraded `azure-core` from `1.28.0` to version `1.29.1`. -- Upgraded `azure-core-http-netty` from `1.12.0` to version `1.12.2`. -- Upgraded `azure-core-serializer-json-jackson` from `1.2.16` to version `1.2.18`. - -## 11.4.11 (2022-06-07) - -### Bugs Fixed - -- Fixed a bug where a custom `ObjectSerializer`'s output wasn't being respected in regard to null field values. ([#29238](https://github.com/Azure/azure-sdk-for-java/pull/29238)) - -### Other Changes - -#### Dependency Updates - -- Upgraded `azure-core` from `1.28.0` to version `1.29.1`. -- Upgraded `azure-core-http-netty` from `1.12.0` to version `1.12.2`. -- Upgraded `azure-core-serializer-json-jackson` from `1.2.16` to version `1.2.18`. - -## 11.4.10 (2022-05-12) - -### Other Changes - -#### Dependency Updates -- Upgraded `azure-core` from `1.27.0` to version `1.28.0`. -- Upgraded `azure-core-http-netty` from `1.11.9` to version `1.12.0`. -- Upgraded `azure-core-serializer-json-jackson` from `1.2.15` to version `1.2.16`. - -## 11.5.0-beta.9 (2022-05-10) - -### Other Changes - -#### Dependency Updates - -- Upgraded `azure-core` from `1.27.0` to version `1.28.0`. -- Upgraded `azure-core-http-netty` from `1.11.9` to version `1.12.0`. -- Upgraded `azure-core-serializer-json-jackson` from `1.2.15` to version `1.2.16`. - -## 11.5.0-beta.8 (2022-04-08) - -### Other Changes - -#### Dependency Updates - -- Upgraded `azure-core` from `1.26.0` to version `1.27.0`. -- Upgraded `azure-core-http-netty` from `1.11.8` to version `1.11.9`. -- Upgraded `azure-core-serializer-json-jackson` from `1.2.14` to version `1.2.15`. - -## 11.4.9 (2022-04-08) - -### Other Changes - -#### Dependency Updates -- Upgraded `azure-core` from `1.26.0` to version `1.27.0`. -- Upgraded `azure-core-http-netty` from `1.11.8` to version `1.11.9`. -- Upgraded `azure-core-serializer-json-jackson` from `1.2.14` to version `1.2.15`. - -## 11.5.0-beta.7 (2022-03-10) - -### Features Added - -- Added support to create, update and delete aliases via the `SearchIndexClient`. - -### Other Changes - -- Updated all `ClientLogger`s to be static constants instead of instance variables. - -#### Dependency Updates - -- Upgraded `azure-core` from `1.25.0` to version `1.26.0`. -- Upgraded `azure-core-http-netty` from `1.11.7` to version `1.11.8`. -- Upgraded `azure-core-serializer-json-jackson` from `1.2.13` to version `1.2.14`. - -## 11.4.8 (2022-03-10) - -### Other Changes - -- Updated all `ClientLogger`s to be static constants instead of instance variables. - -#### Dependency Updates - -- Upgraded `azure-core` from `1.25.0` to version `1.26.0`. -- Upgraded `azure-core-http-netty` from `1.11.7` to version `1.11.8`. -- Upgraded `azure-core-serializer-json-jackson` from `1.2.13` to version `1.2.14`. - -## 11.5.0-beta.6 (2022-02-08) - -### Features Added - -- Added `Unk` as an `OcrSkillLanguage` value. The values are used to set the default language code for the - [OCR cognitive skill](https://docs.microsoft.com/azure/search/cognitive-search-skill-ocr). -- Support for [`AzureMachineLearningSkill`](https://docs.microsoft.com/azure/search/cognitive-search-aml-skill). The - AML skill allows you to extend AI enrichment with a custom [Azure Machine Learning](https://docs.microsoft.com/azure/machine-learning/overview-what-is-azure-machine-learning) - (AML) model. Once an AML model is [trained and deployed](https://docs.microsoft.com/azure/machine-learning/concept-azure-machine-learning-architecture#workspace), - an AML skill integrates it into AI enrichment. -- Added interfaces from `com.azure.core.client.traits` to `SearchIndexerClientBuilder`, `SearchIndexClientBuilder` - and `SearchClientBuilder` - -### Other Changes - -#### Dependency Updates - -- Upgraded `azure-core` from `1.24.1` to version `1.25.0`. -- Upgraded `azure-core-http-netty` from `1.11.6` to version `1.11.7`. -- Upgraded `azure-core-serializer-json-jackson` from `1.2.12` to version `1.2.13`. - -## 11.4.7 (2022-02-08) - -### Other Changes - -#### Dependency Updates - -- Upgraded `azure-core` from `1.24.1` to version `1.25.0`. -- Upgraded `azure-core-http-netty` from `1.11.6` to version `1.11.7`. -- Upgraded `azure-core-serializer-json-jackson` from `1.2.12` to version `1.2.13`. - -## 11.4.6 (2022-01-24) - -### Other Changes - -#### Dependency Updates - -- Upgraded `azure-core` from `1.22.0` to version `1.24.1`. -- Upgraded `azure-core-http-netty` from `1.11.2` to version `1.11.6`. -- Upgraded `azure-core-serializer-json-jackson` from `1.2.9` to version `1.2.12`. - -## 11.5.0-beta.5 (2021-11-24) - -### Features Added - -- Added support for [Semantic Search](https://docs.microsoft.com/azure/search/semantic-search-overview). `SearchOptions` - now support specifying `SemanticSettings` to influence the search behavior. - -### Other Changes - -#### Dependency Updates - -- Upgraded `azure-core` from `1.21.0` to version `1.22.0`. -- Upgraded `azure-core-http-netty` from `1.11.1` to version `1.11.2`. -- Upgraded `azure-core-serializer-json-jackson` from `1.2.8` to version `1.2.9`. - -## 11.4.5 (2021-11-15) - -### Other Changes - -#### Dependency Updates - -- Upgraded `azure-core` from `1.21.0` to version `1.22.0`. -- Upgraded `azure-core-http-netty` from `1.11.1` to version `1.11.2`. -- Upgraded `azure-core-serializer-json-jackson` from `1.2.8` to version `1.2.9`. - -## 11.4.4 (2021-10-13) - -### Other Changes - -#### Dependency Updates - -- Upgraded `azure-core` and other dependencies for the library. -- -## 11.5.0-beta.4 (2021-10-12) - -### Features Added - -- Added APIs to [reset documents](https://docs.microsoft.com/azure/search/search-howto-run-reset-indexers#reset-docs-preview) - and [skills](https://docs.microsoft.com/azure/search/search-howto-run-reset-indexers#reset-skills-preview). - -### Breaking Changes - -- Renamed `QueryAnswer` to `QueryAnswerType`, `QueryCaption` to `QueryCaptionType`, and `QuerySpeller` to `QuerySpellerType`. -- Renamed `SearchOptions` `queryCaptionHighlight` to `queryCaptionHighlightEnabled`. - -### Other Changes - -#### Dependency Updates - -- Updated `azure-core` from `1.20.0` to `1.21.0`. -- Updated `azure-core-http-netty` from `1.11.0` to `1.11.1`. -- Updated `azure-core-serializer-json-jackson` from `1.2.7` to `1.2.8`. - -## 11.4.3 (2021-09-09) - -### Other Changes - -#### Dependency Updates - -- Upgraded `azure-core` and other dependencies for the library. - -## 11.5.0-beta.3 (2021-09-08) - -### Features Added - -- Added `CreateOrUpdateDataSourceConnectionOptions`, `CreateOrUpdateIndexerOptions`, and `CreateOrUpdateSkillsetOptions` - to support passing new parameters to REST API calls. -- Added support for `LexicalNormalizerName` in `AnalyzeTextOptions`. -- Added `queryCaptionHighlight` to `SearchOptions`. - ### Breaking Changes -- Renamed `Captions` to `QueryCaption`. -- Exceptions are now thrown in `EntityRecognitionSkill` and `SentimentSkill` when properties are being set in unsupported - skill versions. +### Bugs Fixed ### Other Changes - -#### Dependency Updates - -- Updated `azure-core` from `1.19.0` to `1.20.0`. -- Updated `azure-core-http-netty` from `1.10.2` to `1.11.0`. -- Updated `azure-core-serializer-json-jackson` from `1.2.6` to `1.2.7`. - -## 11.5.0-beta.2 (2021-08-11) - -### Features Added - -- Added support for indexer caching. - -### Dependency Updates - -- Updated `azure-core` from `1.18.0` to `1.19.0`. -- Updated `azure-core-http-netty` from `1.10.1` to `1.10.2`. -- Updated `azure-core-serializer-json-jackson` from `1.2.5` to `1.2.6`. - -## 11.4.2 (2021-08-11) - -### Dependency Updates - -- Updated `azure-core` from `1.18.0` to `1.19.0`. -- Updated `azure-core-http-netty` from `1.10.1` to `1.10.2`. -- Updated `azure-core-serializer-json-jackson` from `1.2.5` to `1.2.6`. - -## 11.4.1 (2021-08-06) - -### Dependency Updates - -- Updated `azure-core` from `1.17.0` to `1.18.0`. -- Updated `azure-core-http-netty` from `1.10.0` to `1.10.1`. -- Updated `azure-core-serializer-json-jackson` from `1.2.4` to `1.2.5`. - -## 11.5.0-beta.1 (2021-07-20) - -### Features Added - -- Added support for service version `2021-04-30-Preview`. Default version is now `2021-04-30-Preview`. -- Added Semantic Search capability to `SearchClient` and `SearchAsyncClient`. -- Added the ability to configure AAD authentication in client builders to enable AAD authentication in clients. -- Added support for Normalizers in `SearchField` and `SearchIndex` with `CustomNormalizer` and `LexicalNormalizer`. -- Added new versions of `EntityRecognitionSkill` and `SentimentSkill`. Added `PiiDetectionSkill`. -- Added support for indexer data identity. - -### Dependency Updates - -- Updated `azure-core` from `1.17.0` to `1.18.0`. -- Updated `azure-core-http-netty` from `1.10.0` to `1.10.1`. -- Updated `azure-core-serializer-json-jackson` from `1.2.4` to `1.2.5`. - -## 11.4.0 (2021-06-08) - -### Features Added - -- Added the ability to configure Knowledge Store in skillsets. -- Added factory method to `SynonymMap` to enable creation from a file. -- Added support for `Edm.GeographyPoint` in `FieldBuilder` when property has type `GeoPoint`. -- Added support for geography based filtering in `SearchFilter` when `GeoPosition`, `GeoPoint`, `GeoLineString`, or - `GeoPolygon` are used as formatting arguments. -- Added new skills `CustomEntityLookupSkill` and `DocumentExtractionSkill` and new skill versions for - `KeyPhraseExtractionSkill` and `LanguageDetectionSkill`. -- Added support for the ADLS Gen 2 Indexer data source type. -- Added skillset counts to `SearchServiceCounters`. -- Added additional log messages to `SearchIndexingBufferedSender` and `SearchIndexingBufferedAsyncSender`. - -### Breaking Changes - -- Removed support for service version `2020-06-30-Preview`. Default version is now `2020-06-30`. -- Removed Semantic Search capability to `SearchClient` and `SearchAsyncClient`. -- Removed support for Normalizers in `SearchField` and `SearchIndex` with `CustomNormalizer` and `LexicalNormalizer`. - -### Dependency Updates - -- Updated `azure-core` from `1.16.0` to `1.17.0`. -- Updated `azure-core-http-netty` from `1.9.2` to `1.10.0`. -- Updated `azure-core-serializer-json-jackson` from `1.2.3` to `1.2.4`. -- Updated Jackson from `2.12.2` to `2.12.3`. -- Updated Reactor from `3.4.5` to `3.4.6`. -- Updated Reactor Netty from `1.0.6` to `1.0.7`. - -## 11.3.2 (2021-05-11) - -### Dependency Updates - -- Updated `azure-core` from `1.15.0` to `1.16.0`. -- Updated `azure-core-http-netty` from `1.9.1` to `1.9.2`. -- Updated `azure-core-serializer-json-jackson` from `1.2.2` to `1.2.3`. - -## 11.4.0-beta.2 (2021-05-10) - -### Features Added - -- Added Semantic Search capability to `SearchClient` and `SearchAsyncClient`. -- Added the ability to configure Knowledge Store in skillsets. -- Added factory method to `SynonymMap` to enable creation from a file. - -### Dependency Updates - -- Updated `azure-core` from `1.15.0` to `1.16.0`. -- Updated `azure-core-http-netty` from `1.9.1` to `1.9.2`. -- Updated `azure-core-serializer-json-jackson` from `1.2.2` to `1.2.3`. - -## 11.3.1 (2021-04-08) - -### Dependency Updates - -- Updated `azure-core` from `1.14.0` to `1.15.0`. -- Updated `azure-core-http-netty` from `1.9.0` to `1.9.1`. -- Updated `azure-core-serializer-json-jackson` from `1.2.0` to `1.2.2`. -- Updated Jackson from `2.12.1` to `2.12.2`. - -## 11.4.0-beta.1 (2021-04-06) - -### New Features - -- Clients now default to using service version `2020-06-30-Preview`. -- Added support for `Edm.GeographyPoint` in `FieldBuilder` when property has type `GeoPoint`. -- Added support for geography based filtering in `SearchFilter` when `GeoPosition`, `GeoPoint`, `GeoLineString`, or - `GeoPolygon` are used as formatting arguments. -- Added support for Normalizers in `SearchField` and `SearchIndex` with `CustomNormalizer` and `LexicalNormalizer`. -- Added new skills `CustomEntityLookupSkill` and `DocumentExtractionSkill` and new skill versions for - `KeyPhraseExtractionSkill` and `LanguageDetectionSkill`. -- Added support for the ADLS Gen 2 Indexer data source type. -- Added skillset counts to `SearchServiceCounters`. -- Added additional log messages to `SearchIndexingBufferedSender` and `SearchIndexingBufferedAsyncSender`. - -### Dependency Updates - -- Updated `azure-core` from `1.14.0` to `1.15.0`. -- Updated Jackson from `2.12.1` to `2.12.2`. - -### Breaking Changes - -- Updated Jackson annotations to include `required = true` when service must receive or return the property. - -## 11.3.0 (2021-03-10) - -### Dependency Updates - -- Updated `azure-core` from `1.13.0` to `1.14.0`. -- Updated Jackson from `2.11.3` to `2.12.1`. -- Updated Reactor from `3.3.12.RELEASE` to `3.4.3`. -- Updated Reactor Netty from `0.9.15.RELEASE` to `1.0.4`. - -## 11.2.0 (2021-02-10) - -### New Features - -- Added a builder, `SearchIndexingBufferedSenderBuilder`, to configure and construct `SearchIndexingBufferedSender`. -- Added `SearchClientBuilder.bufferedSender(TypeReference)` to create a `SearchIndexingBufferedSenderBuilder` with - base configuration passed from `SearchClientBuilder`. -- Added `OnActionAddedOptions`, `OnActionErrorOptions`, `OnActionSentOptions`, and `OnActionSucceededOptions` - as request options for the on action callback methods in `SearchIndexingBufferedSender`. -- Added `ClientOptions` APIs to all builders to allow re-using common client configurations. -- All changes from the 11.2.0-beta.3, 11.2.0-beta.2, and 11.2.0-beta.1 releases listed below. - -### Breaking Changes - -- Removed `SearchIndexingBufferedSenderOptions` and `SearchClient.getSearchIndexingBufferedSender` and - `SearchAsyncClient.getSearchIndexingBufferedSender`. -- Changed buffered sender configuration options from `autoFlushWindow` to `autoFlushInterval`, - `maxRetries` to `maxRetriesPerAction`, `retryDelay` to `throttlingDelay`, `maxRetryDelay` to `maxThrottlingDelay` - and `onActionErrorBiConsumer` to `onActionErrorConsumer`. -- Renamed `BlobIndexerPDFTextRotationAlgorithm` to `BlobIndexerPdfTextRotationAlgorithm`. - -### Dependency updates - -- Updated `azure-core` to `1.13.0`. -- Updated `azure-core-http-netty` to `1.8.0`. - -## 11.1.3 (2021-01-15) - -### Dependency updates - -- Updated `azure-core` to `1.12.0`. -- Updated `azure-core-http-netty` to `1.7.1`. - -## 11.2.0-beta.3 (2020-11-10) - -### New Features - -- Added encryption key to `SearchIndexer`, `SearchIndexerDataSourceConnection`, and `SearchIndexerSkillset`. -- Added ability to configure initial batch size and retry back-offs to `SearchIndexingBufferedSenderOptions`. - -### Breaking Changes - -- Removed `SearchIndexingBufferedSender.getBatchSize()`. -- `SearchIndexingBufferedSenderOptions` now throws on invalid values instead of falling back to default. - -## 11.1.2 (2020-11-10) - -### Dependency updates - -- Updated `azure-core` version. - -## 11.2.0-beta.2 (2020-10-06) - -### New Features - -- Added `SearchFilter` to help aid creation of OData filter expressions. -- Added required parameter `documentKeyRetriever` to `SearchIndexingBufferedSender` to better correlate response documents to sent documents. -- Added `ClientOptions` to all builders to support setting `applicationId` in `User-Agent` string and headers that need to be applied to each request. -- Added support for `HttpPipelinePosition` in client builders to determine when an `HttpPipelinePolicy` will be invoked. - -### Breaking Changes - -- Renamed `SearchBatchClient` and `SearchBatchAsyncClient` to `SearchIndexingBufferedSender` and `SearchIndexingBufferedAsyncSender`. -- Removed `SearchBatchClientBuilder` for options bag `SearchIndexingBufferedSenderOptions`. -- Renamed `getSearchBatchClient` to `getSearchIndexingBufferedSender` in `SearchClient`. -- Made `SearchIdexingBufferedSender` generic typed. -- Removed `IndexingHooks` in favor of individual callbacks. -- Removed the ability to configure `batchSize` on buffered sender and changed the default to 500 instead of 1000. -- Changed `onActionRemoved` to `onActionSent`. - -## 11.1.1 (2020-10-02) - -### Dependency Updates - -- Updated `azure-core` version. - -## 11.2.0-beta.1 (2020-09-10) - -### New Features - -- Added `SearchBatchClient` and `SearchBatchAsyncClient` which handle automatically creating and sending document batches. -- Added `IndexingHook` interface to provide callback functionality when indexing documents with batching clients. -- Added `IndexingParametersConfiguration`, and related enums, to offer strongly type configuration for `IndexingParameters`. -- Added `ScoringStatistics` and `SessionId` to `SearchOptions`. - -### Breaking Changes - -- Updated Jackson annotations to include `required = true` when service must receive or return the property. - -### Bug Fixes - -- Changed `Fluent` annotations to `Immutable` when the class is immutable. - -## 11.1.0 (2020-09-09) - -### New Features - -- GA release of `buildSearchFields` on `SearchIndexClient` and `SearchIndexAsyncClient`. -- GA release of `JsonSerializer` functionality for `SearchClient` and `SearchAsyncClient`. -- GA release of default `HttpLogOptions` on client builders. - -### Breaking Changes - -- Renamed `SearchableFieldProperty` to `SearchableField` and `SimpleFieldProperty` to `SimpleField`. -- Renamed `FieldBuilderOptions.setConverter` to `FieldBuilderOptions.setJsonSerializer`. -- Replaced `ObjectSerializer` setters in builders with `JsonSerializer` to better represent the type requirement. - -### Bug Fixes - -- Deprecated getter `OcrSkill.setShouldDetectOrientation()` and replaced with correct Javabeans named `isShouldDetectOrientation()`. - -## 11.1.0-beta.1 (2020-08-12) - -- Added `buildSearchFields` API to `SearchIndexClient` and `SearchIndexAsyncClient` to aid in creating `SearchField`s from the passed `Class`. -- Added `SearchableFieldProperty`, `SimpleFieldProperty`, and `FieldBuilderIgnore` to annotate `Class`es passed into `buildSearchFields`. -- Added `getDefaultLogOptions` to `SearchClientBuilder`, `SearchIndexClientBuilder`, and `SearchIndexerClientBuilder`. Updated client construction to use default log options by default. -- Added the ability for clients to accept a `JsonSerializer` to specify a custom JSON serialization layer when dealing with Search documents. - -## 11.0.0 (2020-07-13) - -- Changed version to 11.0.0. -- Removed preview version `SearchClientOptions.ServiceVersion.V2019_05_06_Preview` and added version `SearchClientOptions.ServiceVersion.V2020_06_30`. - -### New Features - -- Added `IndexDocumentsOptions` used to configure document operations. - -### Breaking Changes - -- Moved search result metadata to `SearchPagedFlux` and `SearchPagedIterable` from `SearchPagedResponse`. -- Changed many model classes from fluent setter pattern to immutable constructor pattern. -- Removed `RequestOptions` from APIs, instead use pipeline context to pass per method contextual information. -- Removed strongly type GeoJSON classes. - -### Bug Fixes - -- Removed `implementation` classes from APIs. - -## 1.0.0-beta.4 (2020-06-09) - -- Split `SearchServiceClient` into two clients `SearchIndexClient`, `SearchIndexerClient`. -- Split `SearchServiceAsyncClient` into two clients `SearchIndexAsyncClient`, `SearchIndexerAsyncClient`. -- Added `SearchIndexClientBuilder` to build sync client `SearchIndexClient` and async client `SearchIndexAsyncClient`. -- Added `SearchIndexerClientBuilder` to build sync client `SearchIndexerClient` and async client `SearchIndexerAsyncClient`. -- Removed `SearchServiceClientBuilder`. -- Renamed `SearchIndexClient` to `SearchClient` and `SearchIndexAsyncClient` to `SearchAsyncClient`. -- Put all models used `SearchIndexClient` and `SearchIndexerClient` (same for async clients) under `com.azure.search.documents.indexes`. -- Removed `SearchIndexerDataSource` to `SearchIndexerDataSourceConnection`. -- Renamed methods on `SearchIndexerClient` and `SearchIndexerAsyncClient` idiomatically matching "DataSource" to "DataSourceConnection". -- Removed `DataSourceCredential` and `AzureActiveDirectoryApplicationCredentials` -and uplifted the properties to `SearchIndexerDataSourceConnection` and `SearchResourceEncryptionKey` respectively. -- Removed `select` parameter from list service resource APIs. -- Added list names APIs for each search service resource. (e.g. `listSearchIndexNames`, `listSearchIndexerNames`, `listDataSourceNames`, `listSkillsetNames`, `listSynonymMapNames`) -- Removed deprecated versions and removed the V2 suffix. SDK is currently having `EdgeNGramTokenFilter`, `KeywordTokenizer`, `LuceneStandardTokenizer`, -`NGramTokenFilter`, and `PathHierarchyTokenizer`. -- Renamed `Similarity` to `SimilarityAlgorithm`. -- Renamed `Suggester` to `SearchSuggester`. -- Renamed fields `synonymMaps` to `synonymMapNames`, `analyzer` to `analyzerName`, -`searchAnalyzer` to `searchAnalyzerName` and `indexAnalyzer` to `indexAnalyzerName` -in `SearchField`, `SearchableField`. -- Renamed `SimpleField` to `SimpleFieldBuilder`, `SearchableField` to `SearchableFieldBuilder` -and `ComplexField` to `ComplexFieldBuilder`. - -## 1.0.0-beta.3 (2020-05-05) - -- Replaced `isRetrievable` API with `isHidden`, parameter name changed from `retrievable` to `hidden`. -- Changed Azure Search service version from `2019-05-06` to `2019-05-06-Preview`. -- Changed `createOrUpdate` and `delete` APIs in `SearchServiceClient` to use boolean `onlyIfUnchanged` instead of `MatchConditions`. -- Updated reactor core to `3.3.5.RELEASE`. -- Added helper class `FieldBuilder` which converts a strongly-typed model class to `List`. -- Added annotations `FieldIgnore`, `SimpleFieldProperty`, and `SearchableFieldProperty` to define the `Field` on model properties. -- Added fluent class `SimpleField`, `SearchableField`, and `ComplexField` to build `Field`. - -## 1.0.0-beta.2 (2020-04-06) - -Version 1.0.0-beta.2 is the consecutive beta version of 11.0.0-beta.1. The version is made because we renamed -the search client library module name and namespace. - -- Renamed the azure-search module to azure-search-documents. -- Changed the namespace com.azure.search to com.azure.search.documents. -- Added support for continuation tokens to resume server-side paging. -- Replaced `SearchApiKeyCredential` with `AzureKeyCredential`. -- Moved `AzureKeyCredentialPolicy` to Azure Core. -- Fixed a bug where the Date header wouldn't be updated with a new value on request retry. -- Changed the field type of `CustomAnalyzer`. -- Made `RangeFacetResult` and `ValueFacetResult` object strongly typed. -- Added helper function for IndexBatchException. -- Added ScoringParameter class. -- Refactored some boolean field getter. -- Made `IndexDocumentsBatch` APIs plurality. - -## 11.0.0-beta.1 (2020-03-10) - -Version 11.0.0-beta.1 is a preview of our efforts in creating a client library that is developer-friendly, idiomatic -to the Java ecosystem, and as consistent across different languages and platforms as possible. The principles that guide -our efforts can be found in the [Azure SDK Design Guidelines for Java](https://azure.github.io/azure-sdk/java_introduction.html). - -- Initial release. Please see the README and wiki for information on the new design. diff --git a/sdk/search/azure-search-documents/README.md b/sdk/search/azure-search-documents/README.md index 3a6e6875df06..5e9145c78fa2 100644 --- a/sdk/search/azure-search-documents/README.md +++ b/sdk/search/azure-search-documents/README.md @@ -1,598 +1,78 @@ -# Azure AI Search client library for Java +# Azure Search client library for Java -This is the Java client library for [Azure AI Search](https://learn.microsoft.com/azure/search/) (formerly known as "Azure Cognitive Search"). Azure AI Search service is an AI-powered information retrieval platform that helps developers build rich search experiences and generative AI apps that combine large language models with enterprise data. +Azure Search client library for Java. -Azure AI Search is well suited for the following application scenarios: +This package contains Microsoft Azure Search client library. -* Consolidate varied content types into a single searchable index. - To populate an index, you can push JSON documents that contain your content, - or if your data is already in Azure, create an indexer to pull in data - automatically. -* Attach skillsets to an indexer to create searchable content from images - and unstructured documents. A skillset leverages APIs from Azure AI Services - for built-in OCR, entity recognition, key phrase extraction, language - detection, text translation, and sentiment analysis. You can also add - custom skills to integrate external processing of your content during - data ingestion. -* In a search client application, implement query logic and user experiences - similar to commercial web search engines and chat-style apps. +## Documentation -Use the Azure AI Search client library to: +Various documentation is available to help you get started -* Submit queries using vector, keyword, and hybrid query forms. -* Implement filtered queries for metadata, geospatial search, faceted navigation, - or to narrow results based on filter criteria. -* Create and manage search indexes. -* Upload and update documents in the search index. -* Create and manage indexers that pull data from Azure into an index. -* Create and manage skillsets that add AI enrichment to data ingestion. -* Create and manage analyzers for advanced text analysis or multi-lingual content. -* Optimize results through semantic ranking and scoring profiles to factor in business logic or freshness. - -[Source code][source_code] | [Package (Maven)][package] | [API reference documentation][api_documentation]| [Product documentation][search_docs] | [Samples][samples] +- [API reference documentation][docs] +- [Product documentation][product_documentation] ## Getting started -### Include the package - -#### Include the BOM file - -Please include the azure-sdk-bom to your project to take dependency on the General Availability (GA) version of the library. In the following snippet, replace the {bom_version_to_target} placeholder with the version number. -To learn more about the BOM, see the [AZURE SDK BOM README](https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/boms/azure-sdk-bom/README.md). - -```xml - - - - com.azure - azure-sdk-bom - {bom_version_to_target} - pom - import - - - -``` -and then include the direct dependency in the dependencies section without the version tag. - -```xml - - - com.azure - azure-search-documents - - -``` - -#### Include direct dependency +### Prerequisites -If you want to take dependency on a particular version of the library that is not present in the BOM, -add the direct dependency to your project as follows. +- [Java Development Kit (JDK)][jdk] with version 8 or above +- [Azure Subscription][azure_subscription] +### Adding the package to your product [//]: # ({x-version-update-start;com.azure:azure-search-documents;current}) ```xml com.azure azure-search-documents - 11.8.0-beta.6 + 1.0.0-beta.1 ``` [//]: # ({x-version-update-end}) -### Prerequisites - -* [Java Development Kit (JDK) with version 8 or above][jdk] - * Here are details about [Java 8 client compatibility with Azure Certificate Authority](https://learn.microsoft.com/azure/security/fundamentals/azure-ca-details?tabs=root-and-subordinate-cas-list#client-compatibility-for-public-pkis). -* [Azure subscription][azure_subscription] -* [Azure AI Search service][search] -* To create a new search service, you can use the [Azure portal][create_search_service_docs], -[Azure PowerShell][create_search_service_ps], or the [Azure CLI][create_search_service_cli]. -Here's an example using the Azure CLI to create a free instance for getting started: - -```bash -az search service create --name --resource-group --sku free --location westus -``` - -See [choosing a pricing tier](https://learn.microsoft.com/azure/search/search-sku-tier) for more information about available options. +### Authentication -### Authenticate the client - -To interact with the Search service, you'll need to create an instance of the appropriate client class: `SearchClient` -for searching indexed documents, `SearchIndexClient` for managing indexes, or `SearchIndexerClient` for crawling data -sources and loading search documents into an index. To instantiate a client object, you'll need an **endpoint** and **Azure roles** or an **API key**. You can refer to the documentation for more information on [supported authenticating approaches](https://learn.microsoft.com/azure/search/search-security-overview#authentication) -with the Search service. - -#### Get an API Key - -An API key can be an easier approach to start with because it doesn't require pre-existing role assignments. - -You can get the **endpoint** and an **API key** from the search service in the [Azure Portal](https://portal.azure.com/). -Please refer the [documentation](https://learn.microsoft.com/azure/search/search-security-api-keys) for instructions on -how to get an API key. - -Alternatively, you can use the following [Azure CLI](https://learn.microsoft.com/cli/azure/) command to retrieve the -API key from the search service: - -```bash -az search admin-key show --service-name --resource-group -``` - -**Note:** - -* The example Azure CLI snippet above retrieves an admin key. This allows for easier access when exploring APIs, -but it should be managed carefully. -* There are two types of keys used to access your search service: **admin** *(read-write)* and **query** *(read-only)* -keys. Restricting access and operations in client apps is essential to safeguarding the search assets on your service. -Always use a query key rather than an admin key for any query originating from a client app. - -The SDK provides three clients. - -* `SearchIndexClient` for CRUD operations on indexes and synonym maps. -* `SearchIndexerClient` for CRUD operations on indexers, data sources, and skillsets. -* `SearchClient` for all document operations. - -#### Create a SearchIndexClient - -To create a `SearchIndexClient/SearchIndexAsyncClient`, you will need the values of the Azure AI Search service -URL endpoint and admin key. - -```java readme-sample-createIndexClient -SearchIndexClient searchIndexClient = new SearchIndexClientBuilder() - .endpoint(ENDPOINT) - .credential(new AzureKeyCredential(API_KEY)) - .buildClient(); -``` - -or - -```java readme-sample-createIndexAsyncClient -SearchIndexAsyncClient searchIndexAsyncClient = new SearchIndexClientBuilder() - .endpoint(ENDPOINT) - .credential(new AzureKeyCredential(API_KEY)) - .buildAsyncClient(); -``` - -#### Create a SearchIndexerClient - -To create a `SearchIndexerClient/SearchIndexerAsyncClient`, you will need the values of the Azure AI Search service -URL endpoint and admin key. - -```java readme-sample-createIndexerClient -SearchIndexerClient searchIndexerClient = new SearchIndexerClientBuilder() - .endpoint(ENDPOINT) - .credential(new AzureKeyCredential(API_KEY)) - .buildClient(); -``` - -or - -```java readme-sample-createIndexerAsyncClient -SearchIndexerAsyncClient searchIndexerAsyncClient = new SearchIndexerClientBuilder() - .endpoint(ENDPOINT) - .credential(new AzureKeyCredential(API_KEY)) - .buildAsyncClient(); -``` - -#### Create a SearchClient - -Once you have the values of the Azure AI Search service URL endpoint and -admin key, you can create the `SearchClient/SearchAsyncClient` with an existing index name: - -```java readme-sample-createSearchClient -SearchClient searchClient = new SearchClientBuilder() - .endpoint(ENDPOINT) - .credential(new AzureKeyCredential(ADMIN_KEY)) - .indexName(INDEX_NAME) - .buildClient(); -``` - -or - -```java readme-sample-createAsyncSearchClient -SearchAsyncClient searchAsyncClient = new SearchClientBuilder() - .endpoint(ENDPOINT) - .credential(new AzureKeyCredential(ADMIN_KEY)) - .indexName(INDEX_NAME) - .buildAsyncClient(); -``` - -#### Create a client using Microsoft Entra ID authentication - -You can also create a `SearchClient`, `SearchIndexClient`, or `SearchIndexerClient` using Microsoft Entra ID authentication. Your user or service principal must be assigned the "Search Index Data Reader" role. -Using the [DefaultAzureCredential](https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/identity/azure-identity/README.md#defaultazurecredential) -you can authenticate a service using Managed Identity or a service principal, authenticate as a developer working on an -application, and more all without changing code. Please refer the [documentation](https://learn.microsoft.com/azure/search/search-security-rbac?tabs=config-svc-portal%2Croles-portal%2Ctest-portal%2Ccustom-role-portal%2Cdisable-keys-portal) -for instructions on how to connect to Azure AI Search using Azure role-based access control (Azure RBAC). - -Before you can use the `DefaultAzureCredential`, or any credential type from [Azure.Identity](https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/identity/azure-identity/README.md), -you'll first need to [install the Azure.Identity package](https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/identity/azure-identity/README.md#include-the-package). - -To use `DefaultAzureCredential` with a client ID and secret, you'll need to set the `AZURE_TENANT_ID`, -`AZURE_CLIENT_ID`, and `AZURE_CLIENT_SECRET` environment variables; alternatively, you can pass those values -to the `ClientSecretCredential` also in `azure-identity`. - -Make sure you use the right namespace for `DefaultAzureCredential` at the top of your source file: - -```java -import com.azure.identity.DefaultAzureCredential; -import com.azure.identity.DefaultAzureCredentialBuilder; -``` - -Then you can create an instance of `DefaultAzureCredential` and pass it to a new instance of your client: - -```java readme-sample-searchClientWithTokenCredential -String indexName = "nycjobs"; - -// Get the service endpoint from the environment -String endpoint = Configuration.getGlobalConfiguration().get("SEARCH_ENDPOINT"); -DefaultAzureCredential credential = new DefaultAzureCredentialBuilder().build(); - -// Create a client -SearchClient client = new SearchClientBuilder() - .endpoint(endpoint) - .indexName(indexName) - .credential(credential) - .buildClient(); -``` - -### Send your first search query - -To get running with Azure AI Search first create an index following this [guide][search-get-started-portal]. -With an index created you can use the following samples to begin using the SDK. +[Azure Identity][azure_identity] package provides the default implementation for authenticating the client. ## Key concepts -An Azure AI Search service contains one or more indexes that provide persistent storage of searchable data in -the form of JSON documents. _(If you're new to search, you can make a very rough analogy between indexes and database -tables.)_ The `azure-search-documents` client library exposes operations on these resources through two main client types. - -* `SearchClient` helps with: - * [Searching](https://learn.microsoft.com/azure/search/search-lucene-query-architecture) - your indexed documents using [vector queries](https://learn.microsoft.com/azure/search/vector-search-how-to-query), - [keyword queries](https://learn.microsoft.com/azure/search/search-query-create) - and [hybrid queries](https://learn.microsoft.com/azure/search/hybrid-search-how-to-query) - * [Vector query filters](https://learn.microsoft.com/azure/search/vector-search-filters) and [Text query filters](https://learn.microsoft.com/azure/search/search-filters) - * [Semantic ranking](https://learn.microsoft.com/azure/search/semantic-how-to-query-request) and [scoring profiles](https://learn.microsoft.com/azure/search/index-add-scoring-profiles) for boosting relevance - * [Autocompleting](https://learn.microsoft.com/rest/api/searchservice/autocomplete) - partially typed search terms based on documents in the index - * [Suggesting](https://learn.microsoft.com/rest/api/searchservice/suggestions) - the most likely matching text in documents as a user types - * [Adding, Updating or Deleting Documents](https://learn.microsoft.com/rest/api/searchservice/addupdate-or-delete-documents) - documents from an index - -* `SearchIndexClient` allows you to: - * [Create, delete, update, or configure a search index](https://learn.microsoft.com/rest/api/searchservice/index-operations) - * [Declare custom synonym maps to expand or rewrite queries](https://learn.microsoft.com/rest/api/searchservice/synonym-map-operations) - - -* `SearchIndexerClient` allows you to: - * [Start indexers to automatically crawl data sources](https://learn.microsoft.com/rest/api/searchservice/indexer-operations) - * [Define AI powered Skillsets to transform and enrich your data](https://learn.microsoft.com/rest/api/searchservice/skillset-operations) - -Azure AI Search provides two powerful features: - -### Semantic ranking - -Semantic ranking enhances the quality of search results for text-based queries. By enabling semantic ranking on your search service, you can improve the relevance of search results in two ways: -- It applies secondary ranking to the initial result set, promoting the most semantically relevant results to the top. -- It extracts and returns captions and answers in the response, which can be displayed on a search page to enhance the user's search experience. - -To learn more about semantic ranking, you can refer to the [documentation](https://learn.microsoft.com/azure/search/vector-search-overview). - -### Vector Search - -**Vector search** is an information retrieval technique that uses numeric representations of searchable documents and query strings. By searching for numeric representations of content that are most similar to the numeric query, vector search can find relevant matches, even if the exact terms of the query are not present in the index. Moreover, vector search can be applied to various types of content, including images and videos and translated text, not just same-language text. - -To learn how to index vector fields and perform vector search, you can refer to the [sample](https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/search/azure-search-documents/samples/sample_vector_search.py). This sample provides detailed guidance on indexing vector fields and demonstrates how to perform vector search. - -Additionally, for more comprehensive information about vector search, including its concepts and usage, you can refer to the [documentation](https://learn.microsoft.com/azure/search/vector-search-overview). The documentation provides in-depth explanations and guidance on leveraging the power of vector search in Azure AI Search. - ## Examples -The following examples all use a simple [Hotel data set](https://github.com/Azure-Samples/azure-search-sample-data) -that you can [import into your own index from the Azure portal.](https://learn.microsoft.com/azure/search/search-get-started-portal#step-1---start-the-import-data-wizard-and-create-a-data-source) -These are just a few of the basics - please [check out our Samples][samples_readme] for much more. - -* [Querying](#querying) - * [Use `SearchDocument` like a dictionary for search results](#use-searchdocument-like-a-dictionary-for-search-results) - * [Use Java model for search results](#use-java-model-class-for-search-results) - * [Search Options](#search-options) -* [Creating an index](#creating-an-index) -* [Adding documents to your index](#adding-documents-to-your-index) -* [Retrieving a specific document from your index](#retrieving-a-specific-document-from-your-index) -* [Async APIs](#async-apis) -* [Create a client that can authenticate in a national cloud](#authenticate-in-a-national-cloud) - -### Querying - -There are two ways to interact with the data returned from a search query. - -Let's explore them with a search for a "luxury" hotel. - -#### Use `SearchDocument` like a dictionary for search results - -`SearchDocument` is the default type returned from queries when you don't provide your own. Here we perform the search, -enumerate over the results, and extract data using `SearchDocument`'s dictionary indexer. - -```java readme-sample-searchWithDynamicType -for (SearchResult searchResult : SEARCH_CLIENT.search("luxury")) { - SearchDocument doc = searchResult.getDocument(SearchDocument.class); - String id = (String) doc.get("hotelId"); - String name = (String) doc.get("hotelName"); - System.out.printf("This is hotelId %s, and this is hotel name %s.%n", id, name); -} +```java com.azure.search.documents.readme ``` -#### Use Java model class for search results +### Service API versions -Define a `Hotel` class. +The client library targets the latest service API version by default. +The service client builder accepts an optional service API version parameter to specify which API version to communicate. -```java readme-sample-hotelclass -public static class Hotel { - @SimpleField(isKey = true, isFilterable = true, isSortable = true) - private String id; - @SearchableField(isFilterable = true, isSortable = true) - private String name; +#### Select a service API version - public String getId() { - return id; - } - - public Hotel setId(String id) { - this.id = id; - return this; - } - - public String getName() { - return name; - } - - public Hotel setName(String name) { - this.name = name; - return this; - } -} -``` +You have the flexibility to explicitly select a supported service API version when initializing a service client via the service client builder. +This ensures that the client can communicate with services using the specified API version. -Use it in place of `SearchDocument` when querying. +When selecting an API version, it is important to verify that there are no breaking changes compared to the latest API version. +If there are significant differences, API calls may fail due to incompatibility. -```java readme-sample-searchWithStronglyType -for (SearchResult searchResult : SEARCH_CLIENT.search("luxury")) { - Hotel doc = searchResult.getDocument(Hotel.class); - String id = doc.getId(); - String name = doc.getName(); - System.out.printf("This is hotelId %s, and this is hotel name %s.%n", id, name); -} -``` - -It is recommended, when you know the schema of the search index, to create a Java model class. - -#### Search Options - -The `SearchOptions` provide powerful control over the behavior of our queries. - -Let's search for the top 5 luxury hotels with a good rating. - -```java readme-sample-searchWithSearchOptions -SearchOptions options = new SearchOptions() - .setFilter("rating ge 4") - .setOrderBy("rating desc") - .setTop(5); -SearchPagedIterable searchResultsIterable = SEARCH_CLIENT.search("luxury", options, Context.NONE); -// ... -``` - -### Creating an index - -You can use the [`SearchIndexClient`](#create-a-searchindexclient) to create a search index. Indexes can also define -suggesters, lexical analyzers, and more. - -There are multiple ways of preparing search fields for a search index. For basic needs, we provide a static helper method -`buildSearchFields` in `SearchIndexClient` and `SearchIndexAsyncClient`, which can convert Java POJO class into -`List`. There are three annotations `SimpleFieldProperty`, `SearchFieldProperty` and `FieldBuilderIgnore` -to configure the field of model class. - -```java readme-sample-createIndexUseFieldBuilder -List searchFields = SearchIndexClient.buildSearchFields(Hotel.class, null); -SEARCH_INDEX_CLIENT.createIndex(new SearchIndex("index", searchFields)); -``` - -For advanced scenarios, we can build search fields using `SearchField` directly. - -```java readme-sample-createIndex -List searchFieldList = new ArrayList<>(); -searchFieldList.add(new SearchField("hotelId", SearchFieldDataType.STRING) - .setKey(true) - .setFilterable(true) - .setSortable(true)); - -searchFieldList.add(new SearchField("hotelName", SearchFieldDataType.STRING) - .setSearchable(true) - .setFilterable(true) - .setSortable(true)); -searchFieldList.add(new SearchField("description", SearchFieldDataType.STRING) - .setSearchable(true) - .setAnalyzerName(LexicalAnalyzerName.EU_LUCENE)); -searchFieldList.add(new SearchField("tags", SearchFieldDataType.collection(SearchFieldDataType.STRING)) - .setSearchable(true) - .setFilterable(true) - .setFacetable(true)); -searchFieldList.add(new SearchField("address", SearchFieldDataType.COMPLEX) - .setFields(new SearchField("streetAddress", SearchFieldDataType.STRING).setSearchable(true), - new SearchField("city", SearchFieldDataType.STRING) - .setSearchable(true) - .setFilterable(true) - .setFacetable(true) - .setSortable(true), - new SearchField("stateProvince", SearchFieldDataType.STRING) - .setSearchable(true) - .setFilterable(true) - .setFacetable(true) - .setSortable(true), - new SearchField("country", SearchFieldDataType.STRING) - .setSearchable(true) - .setFilterable(true) - .setFacetable(true) - .setSortable(true), - new SearchField("postalCode", SearchFieldDataType.STRING) - .setSearchable(true) - .setFilterable(true) - .setFacetable(true) - .setSortable(true) - )); - -// Prepare suggester. -SearchSuggester suggester = new SearchSuggester("sg", Collections.singletonList("hotelName")); -// Prepare SearchIndex with index name and search fields. -SearchIndex index = new SearchIndex("hotels").setFields(searchFieldList).setSuggesters(suggester); -// Create an index -SEARCH_INDEX_CLIENT.createIndex(index); -``` - -### Retrieving a specific document from your index - -In addition to querying for documents using keywords and optional filters, you can retrieve a specific document from -your index if you already know the key. You could get the key from a query, for example, and want to show more -information about it or navigate your customer to that document. - -```java readme-sample-retrieveDocuments -Hotel hotel = SEARCH_CLIENT.getDocument("1", Hotel.class); -System.out.printf("This is hotelId %s, and this is hotel name %s.%n", hotel.getId(), hotel.getName()); -``` - -### Adding documents to your index - -You can `Upload`, `Merge`, `MergeOrUpload`, and `Delete` multiple documents from an index in a single batched request. -There are [a few special rules for merging](https://learn.microsoft.com/rest/api/searchservice/addupdate-or-delete-documents#document-actions) -to be aware of. - -```java readme-sample-batchDocumentsOperations -IndexDocumentsBatch batch = new IndexDocumentsBatch<>(); -batch.addUploadActions(Collections.singletonList(new Hotel().setId("783").setName("Upload Inn"))); -batch.addMergeActions(Collections.singletonList(new Hotel().setId("12").setName("Renovated Ranch"))); -SEARCH_CLIENT.indexDocuments(batch); -``` - -The request will throw `IndexBatchException` by default if any of the individual actions fail, and you can use -`findFailedActionsToRetry` to retry on failed documents. There's also a `throwOnAnyError` option, and you can set it -to `false` to get a successful response with an `IndexDocumentsResult` for inspection. - -### Async APIs - -The examples so far have been using synchronous APIs, but we provide full support for async APIs as well. You'll need -to use [SearchAsyncClient](#create-a-searchclient). - -```java readme-sample-searchWithAsyncClient -SEARCH_ASYNC_CLIENT.search("luxury") - .subscribe(result -> { - Hotel hotel = result.getDocument(Hotel.class); - System.out.printf("This is hotelId %s, and this is hotel name %s.%n", hotel.getId(), hotel.getName()); - }); -``` - -### Authenticate in a National Cloud - -To authenticate in a [National Cloud](https://learn.microsoft.com/azure/active-directory/develop/authentication-national-cloud), you will need to make the following additions to your client configuration: - -- Set the `AuthorityHost` in the credential options or via the `AZURE_AUTHORITY_HOST` environment variable -- Set the `audience` in `SearchClientBuilder`, `SearchIndexClientBuilder`, or `SearchIndexerClientBuilder` - -```java readme-sample-nationalCloud -// Create a SearchClient that will authenticate through AAD in the China national cloud. -SearchClient searchClient = new SearchClientBuilder() - .endpoint(ENDPOINT) - .indexName(INDEX_NAME) - .credential(new DefaultAzureCredentialBuilder() - .authorityHost(AzureAuthorityHosts.AZURE_CHINA) - .build()) - .audience(SearchAudience.AZURE_CHINA) - .buildClient(); -``` +Always ensure that the chosen API version is fully supported and operational for your specific use case and that it aligns with the service's versioning policy. ## Troubleshooting -See our [troubleshooting guide](https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/search/azure-search-documents/TROUBLESHOOTING.md) -for details on how to diagnose various failure scenarios. - -### General - -When you interact with Azure AI Search using this Java client library, errors returned by the service correspond -to the same HTTP status codes returned for [REST API][rest_api] requests. For example, the service will return a `404` -error if you try to retrieve a document that doesn't exist in your index. - -### Handling Search Error Response - -Any Search API operation that fails will throw an [`HttpResponseException`][HttpResponseException] with helpful -[`Status codes`][status_codes]. Many of these errors are recoverable. - -```java readme-sample-handleErrorsWithSyncClient -try { - Iterable results = SEARCH_CLIENT.search("hotel"); -} catch (HttpResponseException ex) { - // The exception contains the HTTP status code and the detailed message - // returned from the search service - HttpResponse response = ex.getResponse(); - System.out.println("Status Code: " + response.getStatusCode()); - System.out.println("Message: " + ex.getMessage()); -} -``` - -You can also easily [enable console logging][logging] if you want to dig deeper into the requests you're making against -the service. - -### Enabling Logging - -Azure SDKs for Java provide a consistent logging story to help aid in troubleshooting application errors and expedite -their resolution. The logs produced will capture the flow of an application before reaching the terminal state to help -locate the root issue. View the [logging][logging] wiki for guidance about enabling logging. - -### Default HTTP Client - -By default, a Netty based HTTP client will be used. The [HTTP clients wiki](https://learn.microsoft.com/azure/developer/java/sdk/http-client-pipeline#http-clients) -provides more information on configuring or changing the HTTP client. - ## Next steps -* Samples are explained in detail [here][samples_readme]. -* Read more about the [Azure AI Search service](https://learn.microsoft.com/azure/search/search-what-is-azure-search) - ## Contributing -This project welcomes contributions and suggestions. Most contributions require you to agree to a -[Contributor License Agreement (CLA)][cla] declaring that you have the right to, and actually do, grant us the rights -to use your contribution. - -When you submit a pull request, a CLA-bot will automatically determine whether you need to provide a CLA and decorate -the PR appropriately (e.g., label, comment). Simply follow the instructions provided by the bot. You will only need to -do this once across all repos using our CLA. +For details on contributing to this repository, see the [contributing guide](https://github.com/Azure/azure-sdk-for-java/blob/main/CONTRIBUTING.md). -This project has adopted the [Microsoft Open Source Code of Conduct][coc]. For more information see the -[Code of Conduct FAQ][coc_faq] or contact [opencode@microsoft.com][coc_contact] with any additional questions or comments. +1. Fork it +1. Create your feature branch (`git checkout -b my-new-feature`) +1. Commit your changes (`git commit -am 'Add some feature'`) +1. Push to the branch (`git push origin my-new-feature`) +1. Create new Pull Request -[jdk]: https://learn.microsoft.com/java/azure/jdk/?view=azure-java-stable -[api_documentation]: https://azure.github.io/azure-sdk-for-java/search.html -[search]: https://azure.microsoft.com/services/search/ -[search_docs]: https://learn.microsoft.com/azure/search/ -[azure_subscription]: https://azure.microsoft.com/free/java -[maven]: https://maven.apache.org/ -[package]: https://central.sonatype.com/artifact/com.azure/azure-search-documents -[samples]: https://github.com/Azure/azure-sdk-for-java/tree/main/sdk/search/azure-search-documents/src/samples/ -[samples_readme]: https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/search/azure-search-documents/src/samples/README.md -[source_code]: https://github.com/Azure/azure-sdk-for-java/tree/main/sdk/search/azure-search-documents/src -[logging]: https://github.com/Azure/azure-sdk-for-java/wiki/Logging-in-Azure-SDK -[cla]: https://cla.microsoft.com -[coc]: https://opensource.microsoft.com/codeofconduct/ -[coc_faq]: https://opensource.microsoft.com/codeofconduct/faq/ -[coc_contact]: mailto:opencode@microsoft.com -[add_headers_from_context_policy]: https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/core/azure-core/src/main/java/com/azure/core/http/policy/AddHeadersFromContextPolicy.java -[rest_api]: https://learn.microsoft.com/rest/api/searchservice/http-status-codes -[create_search_service_docs]: https://learn.microsoft.com/azure/search/search-create-service-portal -[create_search_service_ps]: https://learn.microsoft.com/azure/search/search-manage-powershell#create-or-delete-a-service -[create_search_service_cli]: https://learn.microsoft.com/cli/azure/search/service?view=azure-cli-latest#az-search-service-create -[HttpResponseException]: https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/core/azure-core/src/main/java/com/azure/core/exception/HttpResponseException.java -[status_codes]: https://learn.microsoft.com/rest/api/searchservice/http-status-codes -[search-get-started-portal]: https://learn.microsoft.com/azure/search/search-get-started-portal - - +[product_documentation]: https://azure.microsoft.com/services/ +[docs]: https://azure.github.io/azure-sdk-for-java/ +[jdk]: https://learn.microsoft.com/azure/developer/java/fundamentals/ +[azure_subscription]: https://azure.microsoft.com/free/ +[azure_identity]: https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/identity/azure-identity diff --git a/sdk/search/azure-search-documents/TROUBLESHOOTING.md b/sdk/search/azure-search-documents/TROUBLESHOOTING.md deleted file mode 100644 index db0e7bc31dd4..000000000000 --- a/sdk/search/azure-search-documents/TROUBLESHOOTING.md +++ /dev/null @@ -1,66 +0,0 @@ -# Troubleshooting Azure AI Search SDK Issues - -The `azure-search-documents` package provides APIs for operations on the -[Azure AI Search](https://docs.microsoft.com/azure/search/search-what-is-azure-search) cloud service. - -## Table of Contents - -* [Identifying and Troubleshooting Issues by Response Code](#troubleshooting-issues-by-response-code) - * [HTTP 207 Errors](#207-multi-status) - * [HTTP 404 Errors](#404-not-found) - * [HTTP 429 Errors](#429-too-many-requests) -* [Unexpected search query results](#unexpected-search-query-results) - -## Troubleshooting Issues By Response Code - -See [this page](https://docs.microsoft.com/rest/api/searchservice/http-status-codes) for the common response status -codes sent by the Azure AI Search service. - -### 207 Multi-Status - -This response status indicates a partial success for an indexing operation. Some documents were successfully processed, -but at least one failed. Details of the failed documents are present in the individual `IndexingResult` objects within -the `IndexDocumentsResult`. If you want the [`indexDocumentsWithResponse`](https://docs.microsoft.com/java/api/com.azure.search.documents.searchclient.indexdocumentswithresponse?view=azure-java-stable) -method call to throw an exception on any failure, set [`IndexDocumentsOptions.throwOnAnyError`](https://docs.microsoft.com/java/api/com.azure.search.documents.models.indexdocumentsoptions.setthrowonanyerror?view=azure-java-stable#com-azure-search-documents-models-indexdocumentsoptions-setthrowonanyerror(boolean)) -to `true`. Each failure is then recorded in a separate `IndexingResult` and a single `IndexBatchException` is thrown by -the method. - -### 403 Forbidden - -Returned when you pass an invalid api-key. Search service uses two types of keys to control access: admin (read-write) -and query (read-only). The **admin key** grants full rights to all operations, including the ability to manage the service, -create and delete indexes, indexers, and data sources. The **query key** grants read-only access to indexes and documents. -Ensure that the key used for an API call provides sufficient privileges for the operation. See [here](https://docs.microsoft.com/azure/search/search-security-api-keys) -for details about managing API keys. - -If you are using the `azure-identity` package to authenticate requests to Azure AI Search, please see our [troubleshooting guide](https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/identity/azure-identity/TROUBLESHOOTING.md). - -### 404 Not Found - -Returned when a resource does not exist on the server. If you are managing or querying an index, check the syntax and -verify the index name is specified correctly. - -### 429 too many requests - -If this error occurs while you are trying to create an index, it means you already have the maximum number of indexes -allowed for your pricing tier. A count of the indexes stored in Azure AI Search is visible in the search service -dashboard on the [Azure portal](https://portal.azure.com/). To view the indexes by name, click the Index tile. -Alternatively, you can also get a list of the indexes by name using the [listIndexNames() method](https://docs.microsoft.com/java/api/com.azure.search.documents.indexes.searchindexclient.listindexnames?view=azure-java-stable). - -If this error occurs during document upload, it indicates that you've exceeded your quota on the number of documents per -index. You must either create a new index or upgrade for higher capacity limits. - -## Unexpected Search Query Results - -A common class of issues when using the Search SDK is that the result set of a search query is different from what is expected. -For such cases, you should start by running the search query in the portal to rule out any service-side issues with the -search query or any parameter(s). Review the [OData syntax](https://docs.microsoft.com/azure/search/query-odata-filter-orderby-syntax), -if any, used in the query. - -Once the result looks good in the portal, use that as the template to populate the objects and parameters in the search -request APIs. You should also verify that the correct set of documents have been indexed and are being searched on the -service side. One tip would be to start with a 'broad' query (one that returns a superset of desired results, possibly -by giving a large value for or entirely removing, some [query parameters](https://docs.microsoft.com/rest/api/searchservice/search-documents#query-parameters)) -and then progressively refining the query till it expresses the desired intent. - - diff --git a/sdk/search/azure-search-documents/assets.json b/sdk/search/azure-search-documents/assets.json index c17b86dda157..0e2f01c4d4d3 100644 --- a/sdk/search/azure-search-documents/assets.json +++ b/sdk/search/azure-search-documents/assets.json @@ -1,6 +1 @@ -{ - "AssetsRepo": "Azure/azure-sdk-assets", - "AssetsRepoPrefixPath": "java", - "TagPrefix": "java/search/azure-search-documents", - "Tag": "java/search/azure-search-documents_0bac7cbf4b" -} +{"AssetsRepo":"Azure/azure-sdk-assets","AssetsRepoPrefixPath":"java","TagPrefix":"java/search/azure-search-documents","Tag":""} \ No newline at end of file diff --git a/sdk/search/azure-search-documents/checkstyle-suppressions.xml b/sdk/search/azure-search-documents/checkstyle-suppressions.xml deleted file mode 100644 index c4c1ae64c7b3..000000000000 --- a/sdk/search/azure-search-documents/checkstyle-suppressions.xml +++ /dev/null @@ -1,68 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/sdk/search/azure-search-documents/pom.xml b/sdk/search/azure-search-documents/pom.xml index 9c3704a3a8f9..79a16eae58b9 100644 --- a/sdk/search/azure-search-documents/pom.xml +++ b/sdk/search/azure-search-documents/pom.xml @@ -1,96 +1,60 @@ - - + + 4.0.0 - com.azure azure-client-sdk-parent - 1.7.0 + 1.7.0 ../../parents/azure-client-sdk-parent - Microsoft Azure client library for Cognitive Search - This package contains the Microsoft Azure AI Search client library - com.azure azure-search-documents - 11.8.0-beta.6 + 1.0.0-beta.1 jar - - UTF-8 - UTF-8 - - - 0.55 - 0.46 - - - --add-exports com.azure.core/com.azure.core.implementation.http=ALL-UNNAMED - --add-exports com.azure.core/com.azure.core.implementation.util=ALL-UNNAMED - --add-exports com.azure.core/com.azure.core.implementation.jackson=ALL-UNNAMED - - --add-opens com.azure.core/com.azure.core.util=ALL-UNNAMED - --add-opens com.azure.search.documents/com.azure.search.documents=ALL-UNNAMED - --add-opens com.azure.search.documents/com.azure.search.documents.indexes=ALL-UNNAMED - --add-opens com.azure.search.documents/com.azure.search.documents.models=ALL-UNNAMED - --add-opens com.azure.search.documents/com.azure.search.documents.implementation=ALL-UNNAMED - --add-opens com.azure.search.documents/com.azure.search.documents.implementation.models=ALL-UNNAMED - --add-opens com.azure.search.documents/com.azure.search.documents.test.environment.models=com.fasterxml.jackson.databind - --add-opens com.azure.search.documents/com.azure.search.documents.test.environment.models=ALL-UNNAMED - - --add-opens com.azure.search.documents/com.azure.search.documents=com.fasterxml.jackson.databind - --add-opens com.azure.search.documents/com.azure.search.documents.implementation.models=com.fasterxml.jackson.databind - - --add-reads com.azure.search.documents=com.azure.core.serializer.json.jackson - --add-reads com.azure.core=ALL-UNNAMED - --add-reads com.azure.core.test=ALL-UNNAMED - --add-reads com.azure.core.http.netty=ALL-UNNAMED - + Microsoft Azure SDK for Search + This package contains Microsoft Azure Search client library. + https://github.com/Azure/azure-sdk-for-java - true + + + The MIT License (MIT) + http://opensource.org/licenses/MIT + repo + + - checkstyle-suppressions.xml - - false - spotbugs-exclude.xml + + https://github.com/Azure/azure-sdk-for-java + scm:git:git@github.com:Azure/azure-sdk-for-java.git + scm:git:git@github.com:Azure/azure-sdk-for-java.git + HEAD + + + + microsoft + Microsoft + + + + UTF-8 - com.azure azure-core 1.55.3 - - com.azure - azure-json - 1.5.0 - com.azure azure-core-http-netty 1.15.11 - - com.azure - azure-core-serializer-json-jackson - 1.5.8 - - - - - com.google.code.findbugs - jsr305 - 3.0.2 - provided - - - com.azure azure-core-test @@ -103,11 +67,5 @@ 1.15.4 test - - com.azure - azure-ai-openai - 1.0.0-beta.16 - test - diff --git a/sdk/search/azure-search-documents/spotbugs-exclude.xml b/sdk/search/azure-search-documents/spotbugs-exclude.xml deleted file mode 100644 index 4a1068e6717b..000000000000 --- a/sdk/search/azure-search-documents/spotbugs-exclude.xml +++ /dev/null @@ -1,288 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/AliasesAsyncClient.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/AliasesAsyncClient.java new file mode 100644 index 000000000000..f2d1d34d0a58 --- /dev/null +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/AliasesAsyncClient.java @@ -0,0 +1,419 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.search.documents; + +import com.azure.core.annotation.Generated; +import com.azure.core.annotation.ReturnType; +import com.azure.core.annotation.ServiceClient; +import com.azure.core.annotation.ServiceMethod; +import com.azure.core.exception.ClientAuthenticationException; +import com.azure.core.exception.HttpResponseException; +import com.azure.core.exception.ResourceModifiedException; +import com.azure.core.exception.ResourceNotFoundException; +import com.azure.core.http.HttpHeaderName; +import com.azure.core.http.MatchConditions; +import com.azure.core.http.rest.PagedFlux; +import com.azure.core.http.rest.PagedResponse; +import com.azure.core.http.rest.PagedResponseBase; +import com.azure.core.http.rest.RequestOptions; +import com.azure.core.http.rest.Response; +import com.azure.core.util.BinaryData; +import com.azure.core.util.FluxUtil; +import com.azure.search.documents.implementation.AliasesImpl; +import com.azure.search.documents.models.SearchAlias; +import java.util.stream.Collectors; +import reactor.core.publisher.Flux; +import reactor.core.publisher.Mono; + +/** + * Initializes a new instance of the asynchronous SearchClient type. + */ +@ServiceClient(builder = SearchClientBuilder.class, isAsync = true) +public final class AliasesAsyncClient { + @Generated + private final AliasesImpl serviceClient; + + /** + * Initializes an instance of AliasesAsyncClient class. + * + * @param serviceClient the service client implementation. + */ + @Generated + AliasesAsyncClient(AliasesImpl serviceClient) { + this.serviceClient = serviceClient; + } + + /** + * Creates a new search alias. + *

Request Body Schema

+ * + *
+     * {@code
+     * {
+     *     name: String (Required)
+     *     indexes (Required): [
+     *         String (Required)
+     *     ]
+     *     @odata.etag: String (Optional)
+     * }
+     * }
+     * 
+ * + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     name: String (Required)
+     *     indexes (Required): [
+     *         String (Required)
+     *     ]
+     *     @odata.etag: String (Optional)
+     * }
+     * }
+     * 
+ * + * @param alias The definition of the alias to create. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return represents an index alias, which describes a mapping from the alias name to an + * index along with {@link Response} on successful completion of {@link Mono}. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono> createWithResponse(BinaryData alias, RequestOptions requestOptions) { + return this.serviceClient.createWithResponseAsync(alias, requestOptions); + } + + /** + * Lists all aliases available for a search service. + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     name: String (Required)
+     *     indexes (Required): [
+     *         String (Required)
+     *     ]
+     *     @odata.etag: String (Optional)
+     * }
+     * }
+     * 
+ * + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return response from a List Aliases request as paginated response with {@link PagedFlux}. + */ + @Generated + @ServiceMethod(returns = ReturnType.COLLECTION) + public PagedFlux list(RequestOptions requestOptions) { + return this.serviceClient.listAsync(requestOptions); + } + + /** + * Creates a new search alias or updates an alias if it already exists. + *

Header Parameters

+ * + * + * + * + * + *
Header Parameters
NameTypeRequiredDescription
If-MatchStringNoDefines the If-Match condition. The operation will be + * performed only if the ETag on the server matches this value.
If-None-MatchStringNoDefines the If-None-Match condition. The operation will + * be performed only if the ETag on the server does not match this value.
+ * You can add these to a request with {@link RequestOptions#addHeader} + *

Request Body Schema

+ * + *
+     * {@code
+     * {
+     *     name: String (Required)
+     *     indexes (Required): [
+     *         String (Required)
+     *     ]
+     *     @odata.etag: String (Optional)
+     * }
+     * }
+     * 
+ * + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     name: String (Required)
+     *     indexes (Required): [
+     *         String (Required)
+     *     ]
+     *     @odata.etag: String (Optional)
+     * }
+     * }
+     * 
+ * + * @param aliasName The name of the alias. + * @param alias The definition of the alias to create or update. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return represents an index alias, which describes a mapping from the alias name to an + * index along with {@link Response} on successful completion of {@link Mono}. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono> createOrUpdateWithResponse(String aliasName, BinaryData alias, + RequestOptions requestOptions) { + return this.serviceClient.createOrUpdateWithResponseAsync(aliasName, alias, requestOptions); + } + + /** + * 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. + *

Header Parameters

+ * + * + * + * + * + *
Header Parameters
NameTypeRequiredDescription
If-MatchStringNoDefines the If-Match condition. The operation will be + * performed only if the ETag on the server matches this value.
If-None-MatchStringNoDefines the If-None-Match condition. The operation will + * be performed only if the ETag on the server does not match this value.
+ * You can add these to a request with {@link RequestOptions#addHeader} + * + * @param aliasName The name of the alias. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return the {@link Response} on successful completion of {@link Mono}. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono> deleteWithResponse(String aliasName, RequestOptions requestOptions) { + return this.serviceClient.deleteWithResponseAsync(aliasName, requestOptions); + } + + /** + * Retrieves an alias definition. + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     name: String (Required)
+     *     indexes (Required): [
+     *         String (Required)
+     *     ]
+     *     @odata.etag: String (Optional)
+     * }
+     * }
+     * 
+ * + * @param aliasName The name of the alias. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return represents an index alias, which describes a mapping from the alias name to an + * index along with {@link Response} on successful completion of {@link Mono}. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono> getWithResponse(String aliasName, RequestOptions requestOptions) { + return this.serviceClient.getWithResponseAsync(aliasName, requestOptions); + } + + /** + * Creates a new search alias. + * + * @param alias The definition of the alias to create. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return represents an index alias, which describes a mapping from the alias name to an + * index on successful completion of {@link Mono}. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono create(SearchAlias alias) { + // Generated convenience method for createWithResponse + RequestOptions requestOptions = new RequestOptions(); + return createWithResponse(BinaryData.fromObject(alias), requestOptions).flatMap(FluxUtil::toMono) + .map(protocolMethodData -> protocolMethodData.toObject(SearchAlias.class)); + } + + /** + * Lists all aliases available for a search service. + * + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return response from a List Aliases request as paginated response with {@link PagedFlux}. + */ + @Generated + @ServiceMethod(returns = ReturnType.COLLECTION) + public PagedFlux list() { + // Generated convenience method for list + RequestOptions requestOptions = new RequestOptions(); + PagedFlux pagedFluxResponse = list(requestOptions); + return PagedFlux.create(() -> (continuationTokenParam, pageSizeParam) -> { + Flux> flux = (continuationTokenParam == null) + ? pagedFluxResponse.byPage().take(1) + : pagedFluxResponse.byPage(continuationTokenParam).take(1); + return flux.map(pagedResponse -> new PagedResponseBase(pagedResponse.getRequest(), + pagedResponse.getStatusCode(), pagedResponse.getHeaders(), + pagedResponse.getValue() + .stream() + .map(protocolMethodData -> protocolMethodData.toObject(SearchAlias.class)) + .collect(Collectors.toList()), + pagedResponse.getContinuationToken(), null)); + }); + } + + /** + * Creates a new search alias or updates an alias if it already exists. + * + * @param aliasName The name of the alias. + * @param alias The definition of the alias to create or update. + * @param matchConditions Specifies HTTP options for conditional requests. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return represents an index alias, which describes a mapping from the alias name to an + * index on successful completion of {@link Mono}. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono createOrUpdate(String aliasName, SearchAlias alias, MatchConditions matchConditions) { + // Generated convenience method for createOrUpdateWithResponse + RequestOptions requestOptions = new RequestOptions(); + String ifMatch = matchConditions == null ? null : matchConditions.getIfMatch(); + String ifNoneMatch = matchConditions == null ? null : matchConditions.getIfNoneMatch(); + if (ifMatch != null) { + requestOptions.setHeader(HttpHeaderName.IF_MATCH, ifMatch); + } + if (ifNoneMatch != null) { + requestOptions.setHeader(HttpHeaderName.IF_NONE_MATCH, ifNoneMatch); + } + return createOrUpdateWithResponse(aliasName, BinaryData.fromObject(alias), requestOptions) + .flatMap(FluxUtil::toMono) + .map(protocolMethodData -> protocolMethodData.toObject(SearchAlias.class)); + } + + /** + * Creates a new search alias or updates an alias if it already exists. + * + * @param aliasName The name of the alias. + * @param alias The definition of the alias to create or update. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return represents an index alias, which describes a mapping from the alias name to an + * index on successful completion of {@link Mono}. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono createOrUpdate(String aliasName, SearchAlias alias) { + // Generated convenience method for createOrUpdateWithResponse + RequestOptions requestOptions = new RequestOptions(); + return createOrUpdateWithResponse(aliasName, BinaryData.fromObject(alias), requestOptions) + .flatMap(FluxUtil::toMono) + .map(protocolMethodData -> protocolMethodData.toObject(SearchAlias.class)); + } + + /** + * 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 aliasName The name of the alias. + * @param matchConditions Specifies HTTP options for conditional requests. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return A {@link Mono} that completes when a successful response is received. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono delete(String aliasName, MatchConditions matchConditions) { + // Generated convenience method for deleteWithResponse + RequestOptions requestOptions = new RequestOptions(); + String ifMatch = matchConditions == null ? null : matchConditions.getIfMatch(); + String ifNoneMatch = matchConditions == null ? null : matchConditions.getIfNoneMatch(); + if (ifMatch != null) { + requestOptions.setHeader(HttpHeaderName.IF_MATCH, ifMatch); + } + if (ifNoneMatch != null) { + requestOptions.setHeader(HttpHeaderName.IF_NONE_MATCH, ifNoneMatch); + } + return deleteWithResponse(aliasName, requestOptions).flatMap(FluxUtil::toMono); + } + + /** + * 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 aliasName The name of the alias. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return A {@link Mono} that completes when a successful response is received. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono delete(String aliasName) { + // Generated convenience method for deleteWithResponse + RequestOptions requestOptions = new RequestOptions(); + return deleteWithResponse(aliasName, requestOptions).flatMap(FluxUtil::toMono); + } + + /** + * Retrieves an alias definition. + * + * @param aliasName The name of the alias. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return represents an index alias, which describes a mapping from the alias name to an + * index on successful completion of {@link Mono}. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono get(String aliasName) { + // Generated convenience method for getWithResponse + RequestOptions requestOptions = new RequestOptions(); + return getWithResponse(aliasName, requestOptions).flatMap(FluxUtil::toMono) + .map(protocolMethodData -> protocolMethodData.toObject(SearchAlias.class)); + } +} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/AliasesClient.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/AliasesClient.java new file mode 100644 index 000000000000..81795feb1926 --- /dev/null +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/AliasesClient.java @@ -0,0 +1,395 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.search.documents; + +import com.azure.core.annotation.Generated; +import com.azure.core.annotation.ReturnType; +import com.azure.core.annotation.ServiceClient; +import com.azure.core.annotation.ServiceMethod; +import com.azure.core.exception.ClientAuthenticationException; +import com.azure.core.exception.HttpResponseException; +import com.azure.core.exception.ResourceModifiedException; +import com.azure.core.exception.ResourceNotFoundException; +import com.azure.core.http.HttpHeaderName; +import com.azure.core.http.MatchConditions; +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.http.rest.RequestOptions; +import com.azure.core.http.rest.Response; +import com.azure.core.util.BinaryData; +import com.azure.search.documents.implementation.AliasesImpl; +import com.azure.search.documents.models.SearchAlias; + +/** + * Initializes a new instance of the synchronous SearchClient type. + */ +@ServiceClient(builder = SearchClientBuilder.class) +public final class AliasesClient { + @Generated + private final AliasesImpl serviceClient; + + /** + * Initializes an instance of AliasesClient class. + * + * @param serviceClient the service client implementation. + */ + @Generated + AliasesClient(AliasesImpl serviceClient) { + this.serviceClient = serviceClient; + } + + /** + * Creates a new search alias. + *

Request Body Schema

+ * + *
+     * {@code
+     * {
+     *     name: String (Required)
+     *     indexes (Required): [
+     *         String (Required)
+     *     ]
+     *     @odata.etag: String (Optional)
+     * }
+     * }
+     * 
+ * + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     name: String (Required)
+     *     indexes (Required): [
+     *         String (Required)
+     *     ]
+     *     @odata.etag: String (Optional)
+     * }
+     * }
+     * 
+ * + * @param alias The definition of the alias to create. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return represents an index alias, which describes a mapping from the alias name to an + * index along with {@link Response}. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public Response createWithResponse(BinaryData alias, RequestOptions requestOptions) { + return this.serviceClient.createWithResponse(alias, requestOptions); + } + + /** + * Lists all aliases available for a search service. + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     name: String (Required)
+     *     indexes (Required): [
+     *         String (Required)
+     *     ]
+     *     @odata.etag: String (Optional)
+     * }
+     * }
+     * 
+ * + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return response from a List Aliases request as paginated response with {@link PagedIterable}. + */ + @Generated + @ServiceMethod(returns = ReturnType.COLLECTION) + public PagedIterable list(RequestOptions requestOptions) { + return this.serviceClient.list(requestOptions); + } + + /** + * Creates a new search alias or updates an alias if it already exists. + *

Header Parameters

+ * + * + * + * + * + *
Header Parameters
NameTypeRequiredDescription
If-MatchStringNoDefines the If-Match condition. The operation will be + * performed only if the ETag on the server matches this value.
If-None-MatchStringNoDefines the If-None-Match condition. The operation will + * be performed only if the ETag on the server does not match this value.
+ * You can add these to a request with {@link RequestOptions#addHeader} + *

Request Body Schema

+ * + *
+     * {@code
+     * {
+     *     name: String (Required)
+     *     indexes (Required): [
+     *         String (Required)
+     *     ]
+     *     @odata.etag: String (Optional)
+     * }
+     * }
+     * 
+ * + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     name: String (Required)
+     *     indexes (Required): [
+     *         String (Required)
+     *     ]
+     *     @odata.etag: String (Optional)
+     * }
+     * }
+     * 
+ * + * @param aliasName The name of the alias. + * @param alias The definition of the alias to create or update. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return represents an index alias, which describes a mapping from the alias name to an + * index along with {@link Response}. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public Response createOrUpdateWithResponse(String aliasName, BinaryData alias, + RequestOptions requestOptions) { + return this.serviceClient.createOrUpdateWithResponse(aliasName, alias, requestOptions); + } + + /** + * 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. + *

Header Parameters

+ * + * + * + * + * + *
Header Parameters
NameTypeRequiredDescription
If-MatchStringNoDefines the If-Match condition. The operation will be + * performed only if the ETag on the server matches this value.
If-None-MatchStringNoDefines the If-None-Match condition. The operation will + * be performed only if the ETag on the server does not match this value.
+ * You can add these to a request with {@link RequestOptions#addHeader} + * + * @param aliasName The name of the alias. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return the {@link Response}. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public Response deleteWithResponse(String aliasName, RequestOptions requestOptions) { + return this.serviceClient.deleteWithResponse(aliasName, requestOptions); + } + + /** + * Retrieves an alias definition. + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     name: String (Required)
+     *     indexes (Required): [
+     *         String (Required)
+     *     ]
+     *     @odata.etag: String (Optional)
+     * }
+     * }
+     * 
+ * + * @param aliasName The name of the alias. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return represents an index alias, which describes a mapping from the alias name to an + * index along with {@link Response}. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public Response getWithResponse(String aliasName, RequestOptions requestOptions) { + return this.serviceClient.getWithResponse(aliasName, requestOptions); + } + + /** + * Creates a new search alias. + * + * @param alias The definition of the alias to create. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return represents an index alias, which describes a mapping from the alias name to an + * index. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public SearchAlias create(SearchAlias alias) { + // Generated convenience method for createWithResponse + RequestOptions requestOptions = new RequestOptions(); + return createWithResponse(BinaryData.fromObject(alias), requestOptions).getValue().toObject(SearchAlias.class); + } + + /** + * Lists all aliases available for a search service. + * + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return response from a List Aliases request as paginated response with {@link PagedIterable}. + */ + @Generated + @ServiceMethod(returns = ReturnType.COLLECTION) + public PagedIterable list() { + // Generated convenience method for list + RequestOptions requestOptions = new RequestOptions(); + return serviceClient.list(requestOptions).mapPage(bodyItemValue -> bodyItemValue.toObject(SearchAlias.class)); + } + + /** + * Creates a new search alias or updates an alias if it already exists. + * + * @param aliasName The name of the alias. + * @param alias The definition of the alias to create or update. + * @param matchConditions Specifies HTTP options for conditional requests. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return represents an index alias, which describes a mapping from the alias name to an + * index. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public SearchAlias createOrUpdate(String aliasName, SearchAlias alias, MatchConditions matchConditions) { + // Generated convenience method for createOrUpdateWithResponse + RequestOptions requestOptions = new RequestOptions(); + String ifMatch = matchConditions == null ? null : matchConditions.getIfMatch(); + String ifNoneMatch = matchConditions == null ? null : matchConditions.getIfNoneMatch(); + if (ifMatch != null) { + requestOptions.setHeader(HttpHeaderName.IF_MATCH, ifMatch); + } + if (ifNoneMatch != null) { + requestOptions.setHeader(HttpHeaderName.IF_NONE_MATCH, ifNoneMatch); + } + return createOrUpdateWithResponse(aliasName, BinaryData.fromObject(alias), requestOptions).getValue() + .toObject(SearchAlias.class); + } + + /** + * Creates a new search alias or updates an alias if it already exists. + * + * @param aliasName The name of the alias. + * @param alias The definition of the alias to create or update. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return represents an index alias, which describes a mapping from the alias name to an + * index. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public SearchAlias createOrUpdate(String aliasName, SearchAlias alias) { + // Generated convenience method for createOrUpdateWithResponse + RequestOptions requestOptions = new RequestOptions(); + return createOrUpdateWithResponse(aliasName, BinaryData.fromObject(alias), requestOptions).getValue() + .toObject(SearchAlias.class); + } + + /** + * 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 aliasName The name of the alias. + * @param matchConditions Specifies HTTP options for conditional requests. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public void delete(String aliasName, MatchConditions matchConditions) { + // Generated convenience method for deleteWithResponse + RequestOptions requestOptions = new RequestOptions(); + String ifMatch = matchConditions == null ? null : matchConditions.getIfMatch(); + String ifNoneMatch = matchConditions == null ? null : matchConditions.getIfNoneMatch(); + if (ifMatch != null) { + requestOptions.setHeader(HttpHeaderName.IF_MATCH, ifMatch); + } + if (ifNoneMatch != null) { + requestOptions.setHeader(HttpHeaderName.IF_NONE_MATCH, ifNoneMatch); + } + deleteWithResponse(aliasName, requestOptions).getValue(); + } + + /** + * 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 aliasName The name of the alias. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public void delete(String aliasName) { + // Generated convenience method for deleteWithResponse + RequestOptions requestOptions = new RequestOptions(); + deleteWithResponse(aliasName, requestOptions).getValue(); + } + + /** + * Retrieves an alias definition. + * + * @param aliasName The name of the alias. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return represents an index alias, which describes a mapping from the alias name to an + * index. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public SearchAlias get(String aliasName) { + // Generated convenience method for getWithResponse + RequestOptions requestOptions = new RequestOptions(); + return getWithResponse(aliasName, requestOptions).getValue().toObject(SearchAlias.class); + } +} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/DataSourcesAsyncClient.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/DataSourcesAsyncClient.java new file mode 100644 index 000000000000..bea4b48070ca --- /dev/null +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/DataSourcesAsyncClient.java @@ -0,0 +1,601 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.search.documents; + +import com.azure.core.annotation.Generated; +import com.azure.core.annotation.ReturnType; +import com.azure.core.annotation.ServiceClient; +import com.azure.core.annotation.ServiceMethod; +import com.azure.core.exception.ClientAuthenticationException; +import com.azure.core.exception.HttpResponseException; +import com.azure.core.exception.ResourceModifiedException; +import com.azure.core.exception.ResourceNotFoundException; +import com.azure.core.http.HttpHeaderName; +import com.azure.core.http.MatchConditions; +import com.azure.core.http.rest.RequestOptions; +import com.azure.core.http.rest.Response; +import com.azure.core.util.BinaryData; +import com.azure.core.util.FluxUtil; +import com.azure.search.documents.implementation.DataSourcesImpl; +import com.azure.search.documents.models.ListDataSourcesResult; +import com.azure.search.documents.models.SearchIndexerDataSource; +import reactor.core.publisher.Mono; + +/** + * Initializes a new instance of the asynchronous SearchClient type. + */ +@ServiceClient(builder = SearchClientBuilder.class, isAsync = true) +public final class DataSourcesAsyncClient { + @Generated + private final DataSourcesImpl serviceClient; + + /** + * Initializes an instance of DataSourcesAsyncClient class. + * + * @param serviceClient the service client implementation. + */ + @Generated + DataSourcesAsyncClient(DataSourcesImpl serviceClient) { + this.serviceClient = serviceClient; + } + + /** + * Creates a new datasource or updates a datasource if it already exists. + *

Query Parameters

+ * + * + * + * + *
Query Parameters
NameTypeRequiredDescription
ignoreResetRequirementsBooleanNoIgnores cache reset requirements.
+ * You can add these to a request with {@link RequestOptions#addQueryParam} + *

Header Parameters

+ * + * + * + * + * + *
Header Parameters
NameTypeRequiredDescription
If-MatchStringNoDefines the If-Match condition. The operation will be + * performed only if the ETag on the server matches this value.
If-None-MatchStringNoDefines the If-None-Match condition. The operation will + * be performed only if the ETag on the server does not match this value.
+ * You can add these to a request with {@link RequestOptions#addHeader} + *

Request Body Schema

+ * + *
+     * {@code
+     * {
+     *     name: String (Required)
+     *     description: String (Optional)
+     *     type: String(azuresql/cosmosdb/azureblob/azuretable/mysql/adlsgen2/onelake) (Required)
+     *     credentials (Required): {
+     *         connectionString: String (Optional)
+     *     }
+     *     container (Required): {
+     *         name: String (Required)
+     *         query: String (Optional)
+     *     }
+     *     identity (Optional): {
+     *         @odata.type: String (Required)
+     *     }
+     *     dataChangeDetectionPolicy (Optional): {
+     *         @odata.type: String (Required)
+     *     }
+     *     dataDeletionDetectionPolicy (Optional): {
+     *         @odata.type: String (Required)
+     *     }
+     *     @odata.etag: String (Optional)
+     *     encryptionKey (Optional): {
+     *         keyVaultKeyName: String (Required)
+     *         keyVaultKeyVersion: String (Optional)
+     *         keyVaultUri: String (Required)
+     *         accessCredentials (Optional): {
+     *             applicationId: String (Required)
+     *             applicationSecret: String (Optional)
+     *         }
+     *         identity (Optional): (recursive schema, see identity above)
+     *     }
+     * }
+     * }
+     * 
+ * + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     name: String (Required)
+     *     description: String (Optional)
+     *     type: String(azuresql/cosmosdb/azureblob/azuretable/mysql/adlsgen2/onelake) (Required)
+     *     credentials (Required): {
+     *         connectionString: String (Optional)
+     *     }
+     *     container (Required): {
+     *         name: String (Required)
+     *         query: String (Optional)
+     *     }
+     *     identity (Optional): {
+     *         @odata.type: String (Required)
+     *     }
+     *     dataChangeDetectionPolicy (Optional): {
+     *         @odata.type: String (Required)
+     *     }
+     *     dataDeletionDetectionPolicy (Optional): {
+     *         @odata.type: String (Required)
+     *     }
+     *     @odata.etag: String (Optional)
+     *     encryptionKey (Optional): {
+     *         keyVaultKeyName: String (Required)
+     *         keyVaultKeyVersion: String (Optional)
+     *         keyVaultUri: String (Required)
+     *         accessCredentials (Optional): {
+     *             applicationId: String (Required)
+     *             applicationSecret: String (Optional)
+     *         }
+     *         identity (Optional): (recursive schema, see identity above)
+     *     }
+     * }
+     * }
+     * 
+ * + * @param dataSourceName The name of the datasource. + * @param dataSource The definition of the datasource to create or update. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return represents a datasource definition, which can be used to configure an indexer along with {@link Response} + * on successful completion of {@link Mono}. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono> createOrUpdateWithResponse(String dataSourceName, BinaryData dataSource, + RequestOptions requestOptions) { + return this.serviceClient.createOrUpdateWithResponseAsync(dataSourceName, dataSource, requestOptions); + } + + /** + * Deletes a datasource. + *

Header Parameters

+ * + * + * + * + * + *
Header Parameters
NameTypeRequiredDescription
If-MatchStringNoDefines the If-Match condition. The operation will be + * performed only if the ETag on the server matches this value.
If-None-MatchStringNoDefines the If-None-Match condition. The operation will + * be performed only if the ETag on the server does not match this value.
+ * You can add these to a request with {@link RequestOptions#addHeader} + * + * @param dataSourceName The name of the datasource. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return the {@link Response} on successful completion of {@link Mono}. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono> deleteWithResponse(String dataSourceName, RequestOptions requestOptions) { + return this.serviceClient.deleteWithResponseAsync(dataSourceName, requestOptions); + } + + /** + * Retrieves a datasource definition. + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     name: String (Required)
+     *     description: String (Optional)
+     *     type: String(azuresql/cosmosdb/azureblob/azuretable/mysql/adlsgen2/onelake) (Required)
+     *     credentials (Required): {
+     *         connectionString: String (Optional)
+     *     }
+     *     container (Required): {
+     *         name: String (Required)
+     *         query: String (Optional)
+     *     }
+     *     identity (Optional): {
+     *         @odata.type: String (Required)
+     *     }
+     *     dataChangeDetectionPolicy (Optional): {
+     *         @odata.type: String (Required)
+     *     }
+     *     dataDeletionDetectionPolicy (Optional): {
+     *         @odata.type: String (Required)
+     *     }
+     *     @odata.etag: String (Optional)
+     *     encryptionKey (Optional): {
+     *         keyVaultKeyName: String (Required)
+     *         keyVaultKeyVersion: String (Optional)
+     *         keyVaultUri: String (Required)
+     *         accessCredentials (Optional): {
+     *             applicationId: String (Required)
+     *             applicationSecret: String (Optional)
+     *         }
+     *         identity (Optional): (recursive schema, see identity above)
+     *     }
+     * }
+     * }
+     * 
+ * + * @param dataSourceName The name of the datasource. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return represents a datasource definition, which can be used to configure an indexer along with {@link Response} + * on successful completion of {@link Mono}. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono> getWithResponse(String dataSourceName, RequestOptions requestOptions) { + return this.serviceClient.getWithResponseAsync(dataSourceName, requestOptions); + } + + /** + * Lists all datasources available for a search service. + *

Query Parameters

+ * + * + * + * + *
Query Parameters
NameTypeRequiredDescription
$selectStringNoSelects 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.
+ * You can add these to a request with {@link RequestOptions#addQueryParam} + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     value (Required): [
+     *          (Required){
+     *             name: String (Required)
+     *             description: String (Optional)
+     *             type: String(azuresql/cosmosdb/azureblob/azuretable/mysql/adlsgen2/onelake) (Required)
+     *             credentials (Required): {
+     *                 connectionString: String (Optional)
+     *             }
+     *             container (Required): {
+     *                 name: String (Required)
+     *                 query: String (Optional)
+     *             }
+     *             identity (Optional): {
+     *                 @odata.type: String (Required)
+     *             }
+     *             dataChangeDetectionPolicy (Optional): {
+     *                 @odata.type: String (Required)
+     *             }
+     *             dataDeletionDetectionPolicy (Optional): {
+     *                 @odata.type: String (Required)
+     *             }
+     *             @odata.etag: String (Optional)
+     *             encryptionKey (Optional): {
+     *                 keyVaultKeyName: String (Required)
+     *                 keyVaultKeyVersion: String (Optional)
+     *                 keyVaultUri: String (Required)
+     *                 accessCredentials (Optional): {
+     *                     applicationId: String (Required)
+     *                     applicationSecret: String (Optional)
+     *                 }
+     *                 identity (Optional): (recursive schema, see identity above)
+     *             }
+     *         }
+     *     ]
+     * }
+     * }
+     * 
+ * + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return response from a List Datasources request along with {@link Response} on successful completion of + * {@link Mono}. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono> listWithResponse(RequestOptions requestOptions) { + return this.serviceClient.listWithResponseAsync(requestOptions); + } + + /** + * Creates a new datasource. + *

Request Body Schema

+ * + *
+     * {@code
+     * {
+     *     name: String (Required)
+     *     description: String (Optional)
+     *     type: String(azuresql/cosmosdb/azureblob/azuretable/mysql/adlsgen2/onelake) (Required)
+     *     credentials (Required): {
+     *         connectionString: String (Optional)
+     *     }
+     *     container (Required): {
+     *         name: String (Required)
+     *         query: String (Optional)
+     *     }
+     *     identity (Optional): {
+     *         @odata.type: String (Required)
+     *     }
+     *     dataChangeDetectionPolicy (Optional): {
+     *         @odata.type: String (Required)
+     *     }
+     *     dataDeletionDetectionPolicy (Optional): {
+     *         @odata.type: String (Required)
+     *     }
+     *     @odata.etag: String (Optional)
+     *     encryptionKey (Optional): {
+     *         keyVaultKeyName: String (Required)
+     *         keyVaultKeyVersion: String (Optional)
+     *         keyVaultUri: String (Required)
+     *         accessCredentials (Optional): {
+     *             applicationId: String (Required)
+     *             applicationSecret: String (Optional)
+     *         }
+     *         identity (Optional): (recursive schema, see identity above)
+     *     }
+     * }
+     * }
+     * 
+ * + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     name: String (Required)
+     *     description: String (Optional)
+     *     type: String(azuresql/cosmosdb/azureblob/azuretable/mysql/adlsgen2/onelake) (Required)
+     *     credentials (Required): {
+     *         connectionString: String (Optional)
+     *     }
+     *     container (Required): {
+     *         name: String (Required)
+     *         query: String (Optional)
+     *     }
+     *     identity (Optional): {
+     *         @odata.type: String (Required)
+     *     }
+     *     dataChangeDetectionPolicy (Optional): {
+     *         @odata.type: String (Required)
+     *     }
+     *     dataDeletionDetectionPolicy (Optional): {
+     *         @odata.type: String (Required)
+     *     }
+     *     @odata.etag: String (Optional)
+     *     encryptionKey (Optional): {
+     *         keyVaultKeyName: String (Required)
+     *         keyVaultKeyVersion: String (Optional)
+     *         keyVaultUri: String (Required)
+     *         accessCredentials (Optional): {
+     *             applicationId: String (Required)
+     *             applicationSecret: String (Optional)
+     *         }
+     *         identity (Optional): (recursive schema, see identity above)
+     *     }
+     * }
+     * }
+     * 
+ * + * @param dataSource The definition of the datasource to create. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return represents a datasource definition, which can be used to configure an indexer along with {@link Response} + * on successful completion of {@link Mono}. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono> createWithResponse(BinaryData dataSource, RequestOptions requestOptions) { + return this.serviceClient.createWithResponseAsync(dataSource, requestOptions); + } + + /** + * Creates a new datasource or updates a datasource if it already exists. + * + * @param dataSourceName The name of the datasource. + * @param dataSource The definition of the datasource to create or update. + * @param skipIndexerResetRequirementForCache Ignores cache reset requirements. + * @param matchConditions Specifies HTTP options for conditional requests. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return represents a datasource definition, which can be used to configure an indexer on successful completion of + * {@link Mono}. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono createOrUpdate(String dataSourceName, SearchIndexerDataSource dataSource, + Boolean skipIndexerResetRequirementForCache, MatchConditions matchConditions) { + // Generated convenience method for createOrUpdateWithResponse + RequestOptions requestOptions = new RequestOptions(); + String ifMatch = matchConditions == null ? null : matchConditions.getIfMatch(); + String ifNoneMatch = matchConditions == null ? null : matchConditions.getIfNoneMatch(); + if (skipIndexerResetRequirementForCache != null) { + requestOptions.addQueryParam("ignoreResetRequirements", String.valueOf(skipIndexerResetRequirementForCache), + false); + } + if (ifMatch != null) { + requestOptions.setHeader(HttpHeaderName.IF_MATCH, ifMatch); + } + if (ifNoneMatch != null) { + requestOptions.setHeader(HttpHeaderName.IF_NONE_MATCH, ifNoneMatch); + } + return createOrUpdateWithResponse(dataSourceName, BinaryData.fromObject(dataSource), requestOptions) + .flatMap(FluxUtil::toMono) + .map(protocolMethodData -> protocolMethodData.toObject(SearchIndexerDataSource.class)); + } + + /** + * Creates a new datasource or updates a datasource if it already exists. + * + * @param dataSourceName The name of the datasource. + * @param dataSource The definition of the datasource to create or update. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return represents a datasource definition, which can be used to configure an indexer on successful completion of + * {@link Mono}. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono createOrUpdate(String dataSourceName, SearchIndexerDataSource dataSource) { + // Generated convenience method for createOrUpdateWithResponse + RequestOptions requestOptions = new RequestOptions(); + return createOrUpdateWithResponse(dataSourceName, BinaryData.fromObject(dataSource), requestOptions) + .flatMap(FluxUtil::toMono) + .map(protocolMethodData -> protocolMethodData.toObject(SearchIndexerDataSource.class)); + } + + /** + * Deletes a datasource. + * + * @param dataSourceName The name of the datasource. + * @param matchConditions Specifies HTTP options for conditional requests. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return A {@link Mono} that completes when a successful response is received. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono delete(String dataSourceName, MatchConditions matchConditions) { + // Generated convenience method for deleteWithResponse + RequestOptions requestOptions = new RequestOptions(); + String ifMatch = matchConditions == null ? null : matchConditions.getIfMatch(); + String ifNoneMatch = matchConditions == null ? null : matchConditions.getIfNoneMatch(); + if (ifMatch != null) { + requestOptions.setHeader(HttpHeaderName.IF_MATCH, ifMatch); + } + if (ifNoneMatch != null) { + requestOptions.setHeader(HttpHeaderName.IF_NONE_MATCH, ifNoneMatch); + } + return deleteWithResponse(dataSourceName, requestOptions).flatMap(FluxUtil::toMono); + } + + /** + * Deletes a datasource. + * + * @param dataSourceName The name of the datasource. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return A {@link Mono} that completes when a successful response is received. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono delete(String dataSourceName) { + // Generated convenience method for deleteWithResponse + RequestOptions requestOptions = new RequestOptions(); + return deleteWithResponse(dataSourceName, requestOptions).flatMap(FluxUtil::toMono); + } + + /** + * Retrieves a datasource definition. + * + * @param dataSourceName The name of the datasource. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return represents a datasource definition, which can be used to configure an indexer on successful completion of + * {@link Mono}. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono get(String dataSourceName) { + // Generated convenience method for getWithResponse + RequestOptions requestOptions = new RequestOptions(); + return getWithResponse(dataSourceName, requestOptions).flatMap(FluxUtil::toMono) + .map(protocolMethodData -> protocolMethodData.toObject(SearchIndexerDataSource.class)); + } + + /** + * Lists all datasources available for a search service. + * + * @param 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. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return response from a List Datasources request on successful completion of {@link Mono}. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono list(String select) { + // Generated convenience method for listWithResponse + RequestOptions requestOptions = new RequestOptions(); + if (select != null) { + requestOptions.addQueryParam("$select", select, false); + } + return listWithResponse(requestOptions).flatMap(FluxUtil::toMono) + .map(protocolMethodData -> protocolMethodData.toObject(ListDataSourcesResult.class)); + } + + /** + * Lists all datasources available for a search service. + * + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return response from a List Datasources request on successful completion of {@link Mono}. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono list() { + // Generated convenience method for listWithResponse + RequestOptions requestOptions = new RequestOptions(); + return listWithResponse(requestOptions).flatMap(FluxUtil::toMono) + .map(protocolMethodData -> protocolMethodData.toObject(ListDataSourcesResult.class)); + } + + /** + * Creates a new datasource. + * + * @param dataSource The definition of the datasource to create. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return represents a datasource definition, which can be used to configure an indexer on successful completion of + * {@link Mono}. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono create(SearchIndexerDataSource dataSource) { + // Generated convenience method for createWithResponse + RequestOptions requestOptions = new RequestOptions(); + return createWithResponse(BinaryData.fromObject(dataSource), requestOptions).flatMap(FluxUtil::toMono) + .map(protocolMethodData -> protocolMethodData.toObject(SearchIndexerDataSource.class)); + } +} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/DataSourcesClient.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/DataSourcesClient.java new file mode 100644 index 000000000000..eabb294f4535 --- /dev/null +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/DataSourcesClient.java @@ -0,0 +1,587 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.search.documents; + +import com.azure.core.annotation.Generated; +import com.azure.core.annotation.ReturnType; +import com.azure.core.annotation.ServiceClient; +import com.azure.core.annotation.ServiceMethod; +import com.azure.core.exception.ClientAuthenticationException; +import com.azure.core.exception.HttpResponseException; +import com.azure.core.exception.ResourceModifiedException; +import com.azure.core.exception.ResourceNotFoundException; +import com.azure.core.http.HttpHeaderName; +import com.azure.core.http.MatchConditions; +import com.azure.core.http.rest.RequestOptions; +import com.azure.core.http.rest.Response; +import com.azure.core.util.BinaryData; +import com.azure.search.documents.implementation.DataSourcesImpl; +import com.azure.search.documents.models.ListDataSourcesResult; +import com.azure.search.documents.models.SearchIndexerDataSource; + +/** + * Initializes a new instance of the synchronous SearchClient type. + */ +@ServiceClient(builder = SearchClientBuilder.class) +public final class DataSourcesClient { + @Generated + private final DataSourcesImpl serviceClient; + + /** + * Initializes an instance of DataSourcesClient class. + * + * @param serviceClient the service client implementation. + */ + @Generated + DataSourcesClient(DataSourcesImpl serviceClient) { + this.serviceClient = serviceClient; + } + + /** + * Creates a new datasource or updates a datasource if it already exists. + *

Query Parameters

+ * + * + * + * + *
Query Parameters
NameTypeRequiredDescription
ignoreResetRequirementsBooleanNoIgnores cache reset requirements.
+ * You can add these to a request with {@link RequestOptions#addQueryParam} + *

Header Parameters

+ * + * + * + * + * + *
Header Parameters
NameTypeRequiredDescription
If-MatchStringNoDefines the If-Match condition. The operation will be + * performed only if the ETag on the server matches this value.
If-None-MatchStringNoDefines the If-None-Match condition. The operation will + * be performed only if the ETag on the server does not match this value.
+ * You can add these to a request with {@link RequestOptions#addHeader} + *

Request Body Schema

+ * + *
+     * {@code
+     * {
+     *     name: String (Required)
+     *     description: String (Optional)
+     *     type: String(azuresql/cosmosdb/azureblob/azuretable/mysql/adlsgen2/onelake) (Required)
+     *     credentials (Required): {
+     *         connectionString: String (Optional)
+     *     }
+     *     container (Required): {
+     *         name: String (Required)
+     *         query: String (Optional)
+     *     }
+     *     identity (Optional): {
+     *         @odata.type: String (Required)
+     *     }
+     *     dataChangeDetectionPolicy (Optional): {
+     *         @odata.type: String (Required)
+     *     }
+     *     dataDeletionDetectionPolicy (Optional): {
+     *         @odata.type: String (Required)
+     *     }
+     *     @odata.etag: String (Optional)
+     *     encryptionKey (Optional): {
+     *         keyVaultKeyName: String (Required)
+     *         keyVaultKeyVersion: String (Optional)
+     *         keyVaultUri: String (Required)
+     *         accessCredentials (Optional): {
+     *             applicationId: String (Required)
+     *             applicationSecret: String (Optional)
+     *         }
+     *         identity (Optional): (recursive schema, see identity above)
+     *     }
+     * }
+     * }
+     * 
+ * + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     name: String (Required)
+     *     description: String (Optional)
+     *     type: String(azuresql/cosmosdb/azureblob/azuretable/mysql/adlsgen2/onelake) (Required)
+     *     credentials (Required): {
+     *         connectionString: String (Optional)
+     *     }
+     *     container (Required): {
+     *         name: String (Required)
+     *         query: String (Optional)
+     *     }
+     *     identity (Optional): {
+     *         @odata.type: String (Required)
+     *     }
+     *     dataChangeDetectionPolicy (Optional): {
+     *         @odata.type: String (Required)
+     *     }
+     *     dataDeletionDetectionPolicy (Optional): {
+     *         @odata.type: String (Required)
+     *     }
+     *     @odata.etag: String (Optional)
+     *     encryptionKey (Optional): {
+     *         keyVaultKeyName: String (Required)
+     *         keyVaultKeyVersion: String (Optional)
+     *         keyVaultUri: String (Required)
+     *         accessCredentials (Optional): {
+     *             applicationId: String (Required)
+     *             applicationSecret: String (Optional)
+     *         }
+     *         identity (Optional): (recursive schema, see identity above)
+     *     }
+     * }
+     * }
+     * 
+ * + * @param dataSourceName The name of the datasource. + * @param dataSource The definition of the datasource to create or update. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return represents a datasource definition, which can be used to configure an indexer along with + * {@link Response}. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public Response createOrUpdateWithResponse(String dataSourceName, BinaryData dataSource, + RequestOptions requestOptions) { + return this.serviceClient.createOrUpdateWithResponse(dataSourceName, dataSource, requestOptions); + } + + /** + * Deletes a datasource. + *

Header Parameters

+ * + * + * + * + * + *
Header Parameters
NameTypeRequiredDescription
If-MatchStringNoDefines the If-Match condition. The operation will be + * performed only if the ETag on the server matches this value.
If-None-MatchStringNoDefines the If-None-Match condition. The operation will + * be performed only if the ETag on the server does not match this value.
+ * You can add these to a request with {@link RequestOptions#addHeader} + * + * @param dataSourceName The name of the datasource. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return the {@link Response}. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public Response deleteWithResponse(String dataSourceName, RequestOptions requestOptions) { + return this.serviceClient.deleteWithResponse(dataSourceName, requestOptions); + } + + /** + * Retrieves a datasource definition. + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     name: String (Required)
+     *     description: String (Optional)
+     *     type: String(azuresql/cosmosdb/azureblob/azuretable/mysql/adlsgen2/onelake) (Required)
+     *     credentials (Required): {
+     *         connectionString: String (Optional)
+     *     }
+     *     container (Required): {
+     *         name: String (Required)
+     *         query: String (Optional)
+     *     }
+     *     identity (Optional): {
+     *         @odata.type: String (Required)
+     *     }
+     *     dataChangeDetectionPolicy (Optional): {
+     *         @odata.type: String (Required)
+     *     }
+     *     dataDeletionDetectionPolicy (Optional): {
+     *         @odata.type: String (Required)
+     *     }
+     *     @odata.etag: String (Optional)
+     *     encryptionKey (Optional): {
+     *         keyVaultKeyName: String (Required)
+     *         keyVaultKeyVersion: String (Optional)
+     *         keyVaultUri: String (Required)
+     *         accessCredentials (Optional): {
+     *             applicationId: String (Required)
+     *             applicationSecret: String (Optional)
+     *         }
+     *         identity (Optional): (recursive schema, see identity above)
+     *     }
+     * }
+     * }
+     * 
+ * + * @param dataSourceName The name of the datasource. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return represents a datasource definition, which can be used to configure an indexer along with + * {@link Response}. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public Response getWithResponse(String dataSourceName, RequestOptions requestOptions) { + return this.serviceClient.getWithResponse(dataSourceName, requestOptions); + } + + /** + * Lists all datasources available for a search service. + *

Query Parameters

+ * + * + * + * + *
Query Parameters
NameTypeRequiredDescription
$selectStringNoSelects 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.
+ * You can add these to a request with {@link RequestOptions#addQueryParam} + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     value (Required): [
+     *          (Required){
+     *             name: String (Required)
+     *             description: String (Optional)
+     *             type: String(azuresql/cosmosdb/azureblob/azuretable/mysql/adlsgen2/onelake) (Required)
+     *             credentials (Required): {
+     *                 connectionString: String (Optional)
+     *             }
+     *             container (Required): {
+     *                 name: String (Required)
+     *                 query: String (Optional)
+     *             }
+     *             identity (Optional): {
+     *                 @odata.type: String (Required)
+     *             }
+     *             dataChangeDetectionPolicy (Optional): {
+     *                 @odata.type: String (Required)
+     *             }
+     *             dataDeletionDetectionPolicy (Optional): {
+     *                 @odata.type: String (Required)
+     *             }
+     *             @odata.etag: String (Optional)
+     *             encryptionKey (Optional): {
+     *                 keyVaultKeyName: String (Required)
+     *                 keyVaultKeyVersion: String (Optional)
+     *                 keyVaultUri: String (Required)
+     *                 accessCredentials (Optional): {
+     *                     applicationId: String (Required)
+     *                     applicationSecret: String (Optional)
+     *                 }
+     *                 identity (Optional): (recursive schema, see identity above)
+     *             }
+     *         }
+     *     ]
+     * }
+     * }
+     * 
+ * + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return response from a List Datasources request along with {@link Response}. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public Response listWithResponse(RequestOptions requestOptions) { + return this.serviceClient.listWithResponse(requestOptions); + } + + /** + * Creates a new datasource. + *

Request Body Schema

+ * + *
+     * {@code
+     * {
+     *     name: String (Required)
+     *     description: String (Optional)
+     *     type: String(azuresql/cosmosdb/azureblob/azuretable/mysql/adlsgen2/onelake) (Required)
+     *     credentials (Required): {
+     *         connectionString: String (Optional)
+     *     }
+     *     container (Required): {
+     *         name: String (Required)
+     *         query: String (Optional)
+     *     }
+     *     identity (Optional): {
+     *         @odata.type: String (Required)
+     *     }
+     *     dataChangeDetectionPolicy (Optional): {
+     *         @odata.type: String (Required)
+     *     }
+     *     dataDeletionDetectionPolicy (Optional): {
+     *         @odata.type: String (Required)
+     *     }
+     *     @odata.etag: String (Optional)
+     *     encryptionKey (Optional): {
+     *         keyVaultKeyName: String (Required)
+     *         keyVaultKeyVersion: String (Optional)
+     *         keyVaultUri: String (Required)
+     *         accessCredentials (Optional): {
+     *             applicationId: String (Required)
+     *             applicationSecret: String (Optional)
+     *         }
+     *         identity (Optional): (recursive schema, see identity above)
+     *     }
+     * }
+     * }
+     * 
+ * + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     name: String (Required)
+     *     description: String (Optional)
+     *     type: String(azuresql/cosmosdb/azureblob/azuretable/mysql/adlsgen2/onelake) (Required)
+     *     credentials (Required): {
+     *         connectionString: String (Optional)
+     *     }
+     *     container (Required): {
+     *         name: String (Required)
+     *         query: String (Optional)
+     *     }
+     *     identity (Optional): {
+     *         @odata.type: String (Required)
+     *     }
+     *     dataChangeDetectionPolicy (Optional): {
+     *         @odata.type: String (Required)
+     *     }
+     *     dataDeletionDetectionPolicy (Optional): {
+     *         @odata.type: String (Required)
+     *     }
+     *     @odata.etag: String (Optional)
+     *     encryptionKey (Optional): {
+     *         keyVaultKeyName: String (Required)
+     *         keyVaultKeyVersion: String (Optional)
+     *         keyVaultUri: String (Required)
+     *         accessCredentials (Optional): {
+     *             applicationId: String (Required)
+     *             applicationSecret: String (Optional)
+     *         }
+     *         identity (Optional): (recursive schema, see identity above)
+     *     }
+     * }
+     * }
+     * 
+ * + * @param dataSource The definition of the datasource to create. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return represents a datasource definition, which can be used to configure an indexer along with + * {@link Response}. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public Response createWithResponse(BinaryData dataSource, RequestOptions requestOptions) { + return this.serviceClient.createWithResponse(dataSource, requestOptions); + } + + /** + * Creates a new datasource or updates a datasource if it already exists. + * + * @param dataSourceName The name of the datasource. + * @param dataSource The definition of the datasource to create or update. + * @param skipIndexerResetRequirementForCache Ignores cache reset requirements. + * @param matchConditions Specifies HTTP options for conditional requests. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return represents a datasource definition, which can be used to configure an indexer. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public SearchIndexerDataSource createOrUpdate(String dataSourceName, SearchIndexerDataSource dataSource, + Boolean skipIndexerResetRequirementForCache, MatchConditions matchConditions) { + // Generated convenience method for createOrUpdateWithResponse + RequestOptions requestOptions = new RequestOptions(); + String ifMatch = matchConditions == null ? null : matchConditions.getIfMatch(); + String ifNoneMatch = matchConditions == null ? null : matchConditions.getIfNoneMatch(); + if (skipIndexerResetRequirementForCache != null) { + requestOptions.addQueryParam("ignoreResetRequirements", String.valueOf(skipIndexerResetRequirementForCache), + false); + } + if (ifMatch != null) { + requestOptions.setHeader(HttpHeaderName.IF_MATCH, ifMatch); + } + if (ifNoneMatch != null) { + requestOptions.setHeader(HttpHeaderName.IF_NONE_MATCH, ifNoneMatch); + } + return createOrUpdateWithResponse(dataSourceName, BinaryData.fromObject(dataSource), requestOptions).getValue() + .toObject(SearchIndexerDataSource.class); + } + + /** + * Creates a new datasource or updates a datasource if it already exists. + * + * @param dataSourceName The name of the datasource. + * @param dataSource The definition of the datasource to create or update. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return represents a datasource definition, which can be used to configure an indexer. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public SearchIndexerDataSource createOrUpdate(String dataSourceName, SearchIndexerDataSource dataSource) { + // Generated convenience method for createOrUpdateWithResponse + RequestOptions requestOptions = new RequestOptions(); + return createOrUpdateWithResponse(dataSourceName, BinaryData.fromObject(dataSource), requestOptions).getValue() + .toObject(SearchIndexerDataSource.class); + } + + /** + * Deletes a datasource. + * + * @param dataSourceName The name of the datasource. + * @param matchConditions Specifies HTTP options for conditional requests. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public void delete(String dataSourceName, MatchConditions matchConditions) { + // Generated convenience method for deleteWithResponse + RequestOptions requestOptions = new RequestOptions(); + String ifMatch = matchConditions == null ? null : matchConditions.getIfMatch(); + String ifNoneMatch = matchConditions == null ? null : matchConditions.getIfNoneMatch(); + if (ifMatch != null) { + requestOptions.setHeader(HttpHeaderName.IF_MATCH, ifMatch); + } + if (ifNoneMatch != null) { + requestOptions.setHeader(HttpHeaderName.IF_NONE_MATCH, ifNoneMatch); + } + deleteWithResponse(dataSourceName, requestOptions).getValue(); + } + + /** + * Deletes a datasource. + * + * @param dataSourceName The name of the datasource. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public void delete(String dataSourceName) { + // Generated convenience method for deleteWithResponse + RequestOptions requestOptions = new RequestOptions(); + deleteWithResponse(dataSourceName, requestOptions).getValue(); + } + + /** + * Retrieves a datasource definition. + * + * @param dataSourceName The name of the datasource. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return represents a datasource definition, which can be used to configure an indexer. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public SearchIndexerDataSource get(String dataSourceName) { + // Generated convenience method for getWithResponse + RequestOptions requestOptions = new RequestOptions(); + return getWithResponse(dataSourceName, requestOptions).getValue().toObject(SearchIndexerDataSource.class); + } + + /** + * Lists all datasources available for a search service. + * + * @param 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. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return response from a List Datasources request. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public ListDataSourcesResult list(String select) { + // Generated convenience method for listWithResponse + RequestOptions requestOptions = new RequestOptions(); + if (select != null) { + requestOptions.addQueryParam("$select", select, false); + } + return listWithResponse(requestOptions).getValue().toObject(ListDataSourcesResult.class); + } + + /** + * Lists all datasources available for a search service. + * + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return response from a List Datasources request. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public ListDataSourcesResult list() { + // Generated convenience method for listWithResponse + RequestOptions requestOptions = new RequestOptions(); + return listWithResponse(requestOptions).getValue().toObject(ListDataSourcesResult.class); + } + + /** + * Creates a new datasource. + * + * @param dataSource The definition of the datasource to create. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return represents a datasource definition, which can be used to configure an indexer. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public SearchIndexerDataSource create(SearchIndexerDataSource dataSource) { + // Generated convenience method for createWithResponse + RequestOptions requestOptions = new RequestOptions(); + return createWithResponse(BinaryData.fromObject(dataSource), requestOptions).getValue() + .toObject(SearchIndexerDataSource.class); + } +} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/DocumentsAsyncClient.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/DocumentsAsyncClient.java new file mode 100644 index 000000000000..3cf2d9ca2686 --- /dev/null +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/DocumentsAsyncClient.java @@ -0,0 +1,1682 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.search.documents; + +import com.azure.core.annotation.Generated; +import com.azure.core.annotation.ReturnType; +import com.azure.core.annotation.ServiceClient; +import com.azure.core.annotation.ServiceMethod; +import com.azure.core.exception.ClientAuthenticationException; +import com.azure.core.exception.HttpResponseException; +import com.azure.core.exception.ResourceModifiedException; +import com.azure.core.exception.ResourceNotFoundException; +import com.azure.core.http.rest.RequestOptions; +import com.azure.core.http.rest.Response; +import com.azure.core.util.BinaryData; +import com.azure.core.util.FluxUtil; +import com.azure.search.documents.implementation.DocumentsImpl; +import com.azure.search.documents.models.AutocompleteMode; +import com.azure.search.documents.models.AutocompleteRequest; +import com.azure.search.documents.models.AutocompleteResult; +import com.azure.search.documents.models.IndexBatch; +import com.azure.search.documents.models.IndexDocumentsResult; +import com.azure.search.documents.models.LookupDocument; +import com.azure.search.documents.models.QueryAnswerType; +import com.azure.search.documents.models.QueryCaptionType; +import com.azure.search.documents.models.QueryDebugMode; +import com.azure.search.documents.models.QueryLanguage; +import com.azure.search.documents.models.QueryRewritesType; +import com.azure.search.documents.models.QuerySpellerType; +import com.azure.search.documents.models.QueryType; +import com.azure.search.documents.models.ScoringStatistics; +import com.azure.search.documents.models.SearchDocumentsResult; +import com.azure.search.documents.models.SearchMode; +import com.azure.search.documents.models.SearchRequest; +import com.azure.search.documents.models.SemanticErrorMode; +import com.azure.search.documents.models.SuggestDocumentsResult; +import com.azure.search.documents.models.SuggestRequest; +import java.util.List; +import java.util.Objects; +import java.util.stream.Collectors; +import reactor.core.publisher.Mono; + +/** + * Initializes a new instance of the asynchronous SearchClient type. + */ +@ServiceClient(builder = SearchClientBuilder.class, isAsync = true) +public final class DocumentsAsyncClient { + @Generated + private final DocumentsImpl serviceClient; + + /** + * Initializes an instance of DocumentsAsyncClient class. + * + * @param serviceClient the service client implementation. + */ + @Generated + DocumentsAsyncClient(DocumentsImpl serviceClient) { + this.serviceClient = serviceClient; + } + + /** + * Queries the number of documents in the index. + *

Response Body Schema

+ * + *
+     * {@code
+     * int
+     * }
+     * 
+ * + * @param indexName The name of the index. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return a 32-bit integer along with {@link Response} on successful completion of {@link Mono}. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono> countWithResponse(String indexName, RequestOptions requestOptions) { + return this.serviceClient.countWithResponseAsync(indexName, requestOptions); + } + + /** + * Searches for documents in the index. + *

Query Parameters

+ * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + *
Query Parameters
NameTypeRequiredDescription
searchStringNoA full-text search query expression; Use "*" or omit this + * parameter to match + * all documents.
$countBooleanNoA 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.
facetList<String>NoThe 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. Call {@link RequestOptions#addQueryParam} to add string to array.
$filterStringNoThe OData $filter expression to apply to the search + * query.
highlightList<String>NoThe list of field names to use for hit + * highlights. Only searchable fields can + * be used for hit highlighting. In the form of "," separated string.
highlightPostTagStringNoA string tag that is appended to hit highlights. Must + * be set with + * highlightPreTag. Default is &lt;/em&gt;.
highlightPreTagStringNoA string tag that is prepended to hit highlights. Must + * be set with + * highlightPostTag. Default is &lt;em&gt;.
minimumCoverageDoubleNoA 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.
$orderbyList<String>NoThe 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. In the form of "," separated string.
queryTypeStringNoA value that specifies the syntax of the search query. The + * default is 'simple'. + * Use 'full' if your query uses the Lucene query syntax. Allowed values: "simple", "full", "semantic".
scoringParameterList<String>NoThe 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). Call + * {@link RequestOptions#addQueryParam} to add string to array.
scoringProfileStringNoThe name of a scoring profile to evaluate match scores + * for matching documents + * in order to sort the results.
searchFieldsList<String>NoThe 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. In the form of "," separated string.
searchModeStringNoA value that specifies whether any or all of the search + * terms must be matched + * in order to count the document as a match. Allowed values: "any", "all".
scoringStatisticsStringNoA value that specifies whether we want to calculate + * scoring statistics (such as + * document frequency) globally for more consistent scoring, or locally, for lower + * latency. Allowed values: "local", "global".
sessionIdStringNoA 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.
$selectList<String>NoThe list of fields to retrieve. If unspecified, all + * fields marked as + * retrievable in the schema are included. In the form of "," separated string.
$skipIntegerNoThe 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.
$topIntegerNoThe 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.
semanticConfigurationStringNoThe name of the semantic configuration that lists + * which fields should be used + * for semantic ranking, captions, highlights, and answers
semanticErrorHandlingStringNoAllows the user to choose whether a semantic call + * should fail completely, or to + * return partial results (default). Allowed values: "partial", "fail".
semanticMaxWaitInMillisecondsIntegerNoAllows the user to set an upper bound on + * the amount of time it takes for + * semantic enrichment to finish processing before the request fails.
answersStringNoThis 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-<number of answers>` 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-<confidence 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-<number of maximum character length>', + * such as 'extractive|maxcharlength-600'. Allowed values: "none", "extractive".
captionsStringNoThis 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-<true/false>` 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-<number of maximum + * character length>', such as 'extractive|maxcharlength-600'. Allowed values: "none", "extractive".
semanticQueryStringNoAllows 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.
queryRewritesStringNoWhen 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-<number of rewrites>` option, such as + * `generative|count-3`. Defaults to `None`. This parameter is only valid if the + * query type is `semantic`. Allowed values: "none", "generative".
debugStringNoEnables a debugging tool that can be used to further explore your + * search + * results. Allowed values: "disabled", "semantic", "vector", "queryRewrites", "all".
queryLanguageStringNoThe language of the query. Allowed values: "none", + * "en-us", "en-gb", "en-in", "en-ca", "en-au", "fr-fr", "fr-ca", "de-de", "es-es", "es-mx", "zh-cn", "zh-tw", + * "pt-br", "pt-pt", "it-it", "ja-jp", "ko-kr", "ru-ru", "cs-cz", "nl-be", "nl-nl", "hu-hu", "pl-pl", "sv-se", + * "tr-tr", "hi-in", "ar-sa", "ar-eg", "ar-ma", "ar-kw", "ar-jo", "da-dk", "no-no", "bg-bg", "hr-hr", "hr-ba", + * "ms-my", "ms-bn", "sl-sl", "ta-in", "vi-vn", "el-gr", "ro-ro", "is-is", "id-id", "th-th", "lt-lt", "uk-ua", + * "lv-lv", "et-ee", "ca-es", "fi-fi", "sr-ba", "sr-me", "sr-rs", "sk-sk", "nb-no", "hy-am", "bn-in", "eu-es", + * "gl-es", "gu-in", "he-il", "ga-ie", "kn-in", "ml-in", "mr-in", "fa-ae", "pa-in", "te-in", "ur-pk".
spellerStringNoImprove search recall by spell-correcting individual search + * query terms. Allowed values: "none", "lexicon".
semanticFieldsList<String>NoThe list of field names used for semantic + * ranking. In the form of "," separated string.
+ * You can add these to a request with {@link RequestOptions#addQueryParam} + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     @odata.count: Long (Optional)
+     *     @search.coverage: Double (Optional)
+     *     @search.facets (Optional): {
+     *         String (Required): [
+     *              (Required){
+     *                 count: Long (Optional)
+     *                 @search.facets (Optional): {
+     *                     String (Required): [
+     *                         (recursive schema, see above)
+     *                     ]
+     *                 }
+     *                 sum: Long (Optional)
+     *                  (Optional): {
+     *                     String: BinaryData (Required)
+     *                 }
+     *             }
+     *         ]
+     *     }
+     *     @search.answers (Optional): [
+     *          (Optional){
+     *             score: Double (Optional)
+     *             key: String (Optional)
+     *             text: String (Optional)
+     *             highlights: String (Optional)
+     *              (Optional): {
+     *                 String: BinaryData (Required)
+     *             }
+     *         }
+     *     ]
+     *     @search.debug (Optional): {
+     *         queryRewrites (Optional): {
+     *             text (Optional): {
+     *                 inputQuery: String (Optional)
+     *                 rewrites (Optional): [
+     *                     String (Optional)
+     *                 ]
+     *             }
+     *             vectors (Optional): [
+     *                 (recursive schema, see above)
+     *             ]
+     *         }
+     *     }
+     *     @search.nextPageParameters (Optional): {
+     *         count: Boolean (Optional)
+     *         facets (Optional): [
+     *             String (Optional)
+     *         ]
+     *         filter: String (Optional)
+     *         highlight: String (Optional)
+     *         highlightPostTag: String (Optional)
+     *         highlightPreTag: String (Optional)
+     *         minimumCoverage: Double (Optional)
+     *         orderby: String (Optional)
+     *         queryType: String(simple/full/semantic) (Optional)
+     *         scoringStatistics: String(local/global) (Optional)
+     *         sessionId: String (Optional)
+     *         scoringParameters (Optional): [
+     *             String (Optional)
+     *         ]
+     *         scoringProfile: String (Optional)
+     *         debug: String(disabled/semantic/vector/queryRewrites/all) (Optional)
+     *         search: String (Optional)
+     *         searchFields: String (Optional)
+     *         searchMode: String(any/all) (Optional)
+     *         queryLanguage: String(none/en-us/en-gb/en-in/en-ca/en-au/fr-fr/fr-ca/de-de/es-es/es-mx/zh-cn/zh-tw/pt-br/pt-pt/it-it/ja-jp/ko-kr/ru-ru/cs-cz/nl-be/nl-nl/hu-hu/pl-pl/sv-se/tr-tr/hi-in/ar-sa/ar-eg/ar-ma/ar-kw/ar-jo/da-dk/no-no/bg-bg/hr-hr/hr-ba/ms-my/ms-bn/sl-sl/ta-in/vi-vn/el-gr/ro-ro/is-is/id-id/th-th/lt-lt/uk-ua/lv-lv/et-ee/ca-es/fi-fi/sr-ba/sr-me/sr-rs/sk-sk/nb-no/hy-am/bn-in/eu-es/gl-es/gu-in/he-il/ga-ie/kn-in/ml-in/mr-in/fa-ae/pa-in/te-in/ur-pk) (Optional)
+     *         speller: String(none/lexicon) (Optional)
+     *         select: String (Optional)
+     *         skip: Integer (Optional)
+     *         top: Integer (Optional)
+     *         semanticConfiguration: String (Optional)
+     *         semanticErrorHandling: String(partial/fail) (Optional)
+     *         semanticMaxWaitInMilliseconds: Integer (Optional)
+     *         semanticQuery: String (Optional)
+     *         answers: String(none/extractive) (Optional)
+     *         captions: String(none/extractive) (Optional)
+     *         queryRewrites: String(none/generative) (Optional)
+     *         semanticFields: String (Optional)
+     *         vectorQueries (Optional): [
+     *              (Optional){
+     *                 kind: String(vector/text/imageUrl/imageBinary) (Required)
+     *                 k: Integer (Optional)
+     *                 fields: String (Optional)
+     *                 exhaustive: Boolean (Optional)
+     *                 oversampling: Double (Optional)
+     *                 weight: Double (Optional)
+     *                 threshold (Optional): {
+     *                     kind: String(vectorSimilarity/searchScore) (Required)
+     *                 }
+     *                 filterOverride: String (Optional)
+     *             }
+     *         ]
+     *         vectorFilterMode: String(postFilter/preFilter) (Optional)
+     *         hybridSearch (Optional): {
+     *             maxTextRecallSize: Integer (Optional)
+     *             countAndFacetMode: String(countRetrievableResults/countAllResults) (Optional)
+     *         }
+     *     }
+     *     value (Required): [
+     *          (Required){
+     *             @search.score: double (Required)
+     *             @search.rerankerScore: Double (Optional)
+     *             @search.highlights (Optional): {
+     *                 String (Required): [
+     *                     String (Required)
+     *                 ]
+     *             }
+     *             @search.captions (Optional): [
+     *                  (Optional){
+     *                     text: String (Optional)
+     *                     highlights: String (Optional)
+     *                      (Optional): {
+     *                         String: BinaryData (Required)
+     *                     }
+     *                 }
+     *             ]
+     *             @search.documentDebugInfo (Optional): [
+     *                  (Optional){
+     *                     semantic (Optional): {
+     *                         titleField (Optional): {
+     *                             name: String (Optional)
+     *                             state: String(used/unused/partial) (Optional)
+     *                         }
+     *                         contentFields (Optional): [
+     *                             (recursive schema, see above)
+     *                         ]
+     *                         keywordFields (Optional): [
+     *                             (recursive schema, see above)
+     *                         ]
+     *                         rerankerInput (Optional): {
+     *                             title: String (Optional)
+     *                             content: String (Optional)
+     *                             keywords: String (Optional)
+     *                         }
+     *                     }
+     *                     vectors (Optional): {
+     *                         subscores (Optional): {
+     *                             text (Optional): {
+     *                                 searchScore: Double (Optional)
+     *                             }
+     *                             vectors (Optional): [
+     *                                  (Optional){
+     *                                     String (Required): {
+     *                                         searchScore: Double (Optional)
+     *                                         vectorSimilarity: Double (Optional)
+     *                                     }
+     *                                 }
+     *                             ]
+     *                             documentBoost: Double (Optional)
+     *                         }
+     *                     }
+     *                 }
+     *             ]
+     *              (Optional): {
+     *                 String: BinaryData (Required)
+     *             }
+     *         }
+     *     ]
+     *     @odata.nextLink: String (Optional)
+     *     @search.semanticPartialResponseReason: String(maxWaitExceeded/capacityOverloaded/transient) (Optional)
+     *     @search.semanticPartialResponseType: String(baseResults/rerankedResults) (Optional)
+     *     @search.semanticQueryRewritesResultType: String(originalQueryOnly) (Optional)
+     * }
+     * }
+     * 
+ * + * @param indexName The name of the index. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return response containing search results from an index along with {@link Response} on successful completion of + * {@link Mono}. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono> searchGetWithResponse(String indexName, RequestOptions requestOptions) { + return this.serviceClient.searchGetWithResponseAsync(indexName, requestOptions); + } + + /** + * Searches for documents in the index. + *

Request Body Schema

+ * + *
+     * {@code
+     * {
+     *     count: Boolean (Optional)
+     *     facets (Optional): [
+     *         String (Optional)
+     *     ]
+     *     filter: String (Optional)
+     *     highlight: String (Optional)
+     *     highlightPostTag: String (Optional)
+     *     highlightPreTag: String (Optional)
+     *     minimumCoverage: Double (Optional)
+     *     orderby: String (Optional)
+     *     queryType: String(simple/full/semantic) (Optional)
+     *     scoringStatistics: String(local/global) (Optional)
+     *     sessionId: String (Optional)
+     *     scoringParameters (Optional): [
+     *         String (Optional)
+     *     ]
+     *     scoringProfile: String (Optional)
+     *     debug: String(disabled/semantic/vector/queryRewrites/all) (Optional)
+     *     search: String (Optional)
+     *     searchFields: String (Optional)
+     *     searchMode: String(any/all) (Optional)
+     *     queryLanguage: String(none/en-us/en-gb/en-in/en-ca/en-au/fr-fr/fr-ca/de-de/es-es/es-mx/zh-cn/zh-tw/pt-br/pt-pt/it-it/ja-jp/ko-kr/ru-ru/cs-cz/nl-be/nl-nl/hu-hu/pl-pl/sv-se/tr-tr/hi-in/ar-sa/ar-eg/ar-ma/ar-kw/ar-jo/da-dk/no-no/bg-bg/hr-hr/hr-ba/ms-my/ms-bn/sl-sl/ta-in/vi-vn/el-gr/ro-ro/is-is/id-id/th-th/lt-lt/uk-ua/lv-lv/et-ee/ca-es/fi-fi/sr-ba/sr-me/sr-rs/sk-sk/nb-no/hy-am/bn-in/eu-es/gl-es/gu-in/he-il/ga-ie/kn-in/ml-in/mr-in/fa-ae/pa-in/te-in/ur-pk) (Optional)
+     *     speller: String(none/lexicon) (Optional)
+     *     select: String (Optional)
+     *     skip: Integer (Optional)
+     *     top: Integer (Optional)
+     *     semanticConfiguration: String (Optional)
+     *     semanticErrorHandling: String(partial/fail) (Optional)
+     *     semanticMaxWaitInMilliseconds: Integer (Optional)
+     *     semanticQuery: String (Optional)
+     *     answers: String(none/extractive) (Optional)
+     *     captions: String(none/extractive) (Optional)
+     *     queryRewrites: String(none/generative) (Optional)
+     *     semanticFields: String (Optional)
+     *     vectorQueries (Optional): [
+     *          (Optional){
+     *             kind: String(vector/text/imageUrl/imageBinary) (Required)
+     *             k: Integer (Optional)
+     *             fields: String (Optional)
+     *             exhaustive: Boolean (Optional)
+     *             oversampling: Double (Optional)
+     *             weight: Double (Optional)
+     *             threshold (Optional): {
+     *                 kind: String(vectorSimilarity/searchScore) (Required)
+     *             }
+     *             filterOverride: String (Optional)
+     *         }
+     *     ]
+     *     vectorFilterMode: String(postFilter/preFilter) (Optional)
+     *     hybridSearch (Optional): {
+     *         maxTextRecallSize: Integer (Optional)
+     *         countAndFacetMode: String(countRetrievableResults/countAllResults) (Optional)
+     *     }
+     * }
+     * }
+     * 
+ * + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     @odata.count: Long (Optional)
+     *     @search.coverage: Double (Optional)
+     *     @search.facets (Optional): {
+     *         String (Required): [
+     *              (Required){
+     *                 count: Long (Optional)
+     *                 @search.facets (Optional): {
+     *                     String (Required): [
+     *                         (recursive schema, see above)
+     *                     ]
+     *                 }
+     *                 sum: Long (Optional)
+     *                  (Optional): {
+     *                     String: BinaryData (Required)
+     *                 }
+     *             }
+     *         ]
+     *     }
+     *     @search.answers (Optional): [
+     *          (Optional){
+     *             score: Double (Optional)
+     *             key: String (Optional)
+     *             text: String (Optional)
+     *             highlights: String (Optional)
+     *              (Optional): {
+     *                 String: BinaryData (Required)
+     *             }
+     *         }
+     *     ]
+     *     @search.debug (Optional): {
+     *         queryRewrites (Optional): {
+     *             text (Optional): {
+     *                 inputQuery: String (Optional)
+     *                 rewrites (Optional): [
+     *                     String (Optional)
+     *                 ]
+     *             }
+     *             vectors (Optional): [
+     *                 (recursive schema, see above)
+     *             ]
+     *         }
+     *     }
+     *     @search.nextPageParameters (Optional): {
+     *         count: Boolean (Optional)
+     *         facets (Optional): [
+     *             String (Optional)
+     *         ]
+     *         filter: String (Optional)
+     *         highlight: String (Optional)
+     *         highlightPostTag: String (Optional)
+     *         highlightPreTag: String (Optional)
+     *         minimumCoverage: Double (Optional)
+     *         orderby: String (Optional)
+     *         queryType: String(simple/full/semantic) (Optional)
+     *         scoringStatistics: String(local/global) (Optional)
+     *         sessionId: String (Optional)
+     *         scoringParameters (Optional): [
+     *             String (Optional)
+     *         ]
+     *         scoringProfile: String (Optional)
+     *         debug: String(disabled/semantic/vector/queryRewrites/all) (Optional)
+     *         search: String (Optional)
+     *         searchFields: String (Optional)
+     *         searchMode: String(any/all) (Optional)
+     *         queryLanguage: String(none/en-us/en-gb/en-in/en-ca/en-au/fr-fr/fr-ca/de-de/es-es/es-mx/zh-cn/zh-tw/pt-br/pt-pt/it-it/ja-jp/ko-kr/ru-ru/cs-cz/nl-be/nl-nl/hu-hu/pl-pl/sv-se/tr-tr/hi-in/ar-sa/ar-eg/ar-ma/ar-kw/ar-jo/da-dk/no-no/bg-bg/hr-hr/hr-ba/ms-my/ms-bn/sl-sl/ta-in/vi-vn/el-gr/ro-ro/is-is/id-id/th-th/lt-lt/uk-ua/lv-lv/et-ee/ca-es/fi-fi/sr-ba/sr-me/sr-rs/sk-sk/nb-no/hy-am/bn-in/eu-es/gl-es/gu-in/he-il/ga-ie/kn-in/ml-in/mr-in/fa-ae/pa-in/te-in/ur-pk) (Optional)
+     *         speller: String(none/lexicon) (Optional)
+     *         select: String (Optional)
+     *         skip: Integer (Optional)
+     *         top: Integer (Optional)
+     *         semanticConfiguration: String (Optional)
+     *         semanticErrorHandling: String(partial/fail) (Optional)
+     *         semanticMaxWaitInMilliseconds: Integer (Optional)
+     *         semanticQuery: String (Optional)
+     *         answers: String(none/extractive) (Optional)
+     *         captions: String(none/extractive) (Optional)
+     *         queryRewrites: String(none/generative) (Optional)
+     *         semanticFields: String (Optional)
+     *         vectorQueries (Optional): [
+     *              (Optional){
+     *                 kind: String(vector/text/imageUrl/imageBinary) (Required)
+     *                 k: Integer (Optional)
+     *                 fields: String (Optional)
+     *                 exhaustive: Boolean (Optional)
+     *                 oversampling: Double (Optional)
+     *                 weight: Double (Optional)
+     *                 threshold (Optional): {
+     *                     kind: String(vectorSimilarity/searchScore) (Required)
+     *                 }
+     *                 filterOverride: String (Optional)
+     *             }
+     *         ]
+     *         vectorFilterMode: String(postFilter/preFilter) (Optional)
+     *         hybridSearch (Optional): {
+     *             maxTextRecallSize: Integer (Optional)
+     *             countAndFacetMode: String(countRetrievableResults/countAllResults) (Optional)
+     *         }
+     *     }
+     *     value (Required): [
+     *          (Required){
+     *             @search.score: double (Required)
+     *             @search.rerankerScore: Double (Optional)
+     *             @search.highlights (Optional): {
+     *                 String (Required): [
+     *                     String (Required)
+     *                 ]
+     *             }
+     *             @search.captions (Optional): [
+     *                  (Optional){
+     *                     text: String (Optional)
+     *                     highlights: String (Optional)
+     *                      (Optional): {
+     *                         String: BinaryData (Required)
+     *                     }
+     *                 }
+     *             ]
+     *             @search.documentDebugInfo (Optional): [
+     *                  (Optional){
+     *                     semantic (Optional): {
+     *                         titleField (Optional): {
+     *                             name: String (Optional)
+     *                             state: String(used/unused/partial) (Optional)
+     *                         }
+     *                         contentFields (Optional): [
+     *                             (recursive schema, see above)
+     *                         ]
+     *                         keywordFields (Optional): [
+     *                             (recursive schema, see above)
+     *                         ]
+     *                         rerankerInput (Optional): {
+     *                             title: String (Optional)
+     *                             content: String (Optional)
+     *                             keywords: String (Optional)
+     *                         }
+     *                     }
+     *                     vectors (Optional): {
+     *                         subscores (Optional): {
+     *                             text (Optional): {
+     *                                 searchScore: Double (Optional)
+     *                             }
+     *                             vectors (Optional): [
+     *                                  (Optional){
+     *                                     String (Required): {
+     *                                         searchScore: Double (Optional)
+     *                                         vectorSimilarity: Double (Optional)
+     *                                     }
+     *                                 }
+     *                             ]
+     *                             documentBoost: Double (Optional)
+     *                         }
+     *                     }
+     *                 }
+     *             ]
+     *              (Optional): {
+     *                 String: BinaryData (Required)
+     *             }
+     *         }
+     *     ]
+     *     @odata.nextLink: String (Optional)
+     *     @search.semanticPartialResponseReason: String(maxWaitExceeded/capacityOverloaded/transient) (Optional)
+     *     @search.semanticPartialResponseType: String(baseResults/rerankedResults) (Optional)
+     *     @search.semanticQueryRewritesResultType: String(originalQueryOnly) (Optional)
+     * }
+     * }
+     * 
+ * + * @param indexName The name of the index. + * @param searchRequest The definition of the Search request. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return response containing search results from an index along with {@link Response} on successful completion of + * {@link Mono}. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono> searchPostWithResponse(String indexName, BinaryData searchRequest, + RequestOptions requestOptions) { + return this.serviceClient.searchPostWithResponseAsync(indexName, searchRequest, requestOptions); + } + + /** + * Retrieves a document from the index. + *

Query Parameters

+ * + * + * + * + *
Query Parameters
NameTypeRequiredDescription
$selectList<String>NoList of field names to retrieve for the document; + * Any field not retrieved will + * be missing from the returned document. In the form of "," separated string.
+ * You can add these to a request with {@link RequestOptions#addQueryParam} + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *      (Optional): {
+     *         String: BinaryData (Required)
+     *     }
+     * }
+     * }
+     * 
+ * + * @param key The key of the document to retrieve. + * @param indexName The name of the index. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return a document retrieved via a document lookup operation along with {@link Response} on successful completion + * of {@link Mono}. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono> getWithResponse(String key, String indexName, RequestOptions requestOptions) { + return this.serviceClient.getWithResponseAsync(key, indexName, requestOptions); + } + + /** + * Suggests documents in the index that match the given partial query text. + *

Query Parameters

+ * + * + * + * + * + * + * + * + * + * + * + * + *
Query Parameters
NameTypeRequiredDescription
$filterStringNoAn OData expression that filters the documents considered for + * suggestions.
fuzzyBooleanNoA 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.
highlightPostTagStringNoA string tag that is appended to hit highlights. Must + * be set with + * highlightPreTag. If omitted, hit highlighting of suggestions is disabled.
highlightPreTagStringNoA string tag that is prepended to hit highlights. Must + * be set with + * highlightPostTag. If omitted, hit highlighting of suggestions is disabled.
minimumCoverageDoubleNoA 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.
$orderbyList<String>NoThe 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. In the form of "," separated string.
searchFieldsList<String>NoThe list of field names to search for the + * specified search text. Target fields + * must be included in the specified suggester. In the form of "," separated string.
$selectList<String>NoThe list of fields to retrieve. If unspecified, + * only the key field will be + * included in the results. In the form of "," separated string.
$topIntegerNoThe number of suggestions to retrieve. The value must be a number + * between 1 and + * 100. The default is 5.
+ * You can add these to a request with {@link RequestOptions#addQueryParam} + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     value (Required): [
+     *          (Required){
+     *             @search.text: String (Required)
+     *              (Optional): {
+     *                 String: BinaryData (Required)
+     *             }
+     *         }
+     *     ]
+     *     @search.coverage: Double (Optional)
+     * }
+     * }
+     * 
+ * + * @param searchText The search text to use to suggest documents. Must be at least 1 character, and + * no more than 100 characters. + * @param suggesterName The name of the suggester as specified in the suggesters collection that's part + * of the index definition. + * @param indexName The name of the index. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return response containing suggestion query results from an index along with {@link Response} on successful + * completion of {@link Mono}. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono> suggestGetWithResponse(String searchText, String suggesterName, String indexName, + RequestOptions requestOptions) { + return this.serviceClient.suggestGetWithResponseAsync(searchText, suggesterName, indexName, requestOptions); + } + + /** + * Suggests documents in the index that match the given partial query text. + *

Request Body Schema

+ * + *
+     * {@code
+     * {
+     *     filter: String (Optional)
+     *     fuzzy: Boolean (Optional)
+     *     highlightPostTag: String (Optional)
+     *     highlightPreTag: String (Optional)
+     *     minimumCoverage: Double (Optional)
+     *     orderby: String (Optional)
+     *     search: String (Required)
+     *     searchFields: String (Optional)
+     *     select: String (Optional)
+     *     suggesterName: String (Required)
+     *     top: Integer (Optional)
+     * }
+     * }
+     * 
+ * + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     value (Required): [
+     *          (Required){
+     *             @search.text: String (Required)
+     *              (Optional): {
+     *                 String: BinaryData (Required)
+     *             }
+     *         }
+     *     ]
+     *     @search.coverage: Double (Optional)
+     * }
+     * }
+     * 
+ * + * @param indexName The name of the index. + * @param suggestRequest The Suggest request. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return response containing suggestion query results from an index along with {@link Response} on successful + * completion of {@link Mono}. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono> suggestPostWithResponse(String indexName, BinaryData suggestRequest, + RequestOptions requestOptions) { + return this.serviceClient.suggestPostWithResponseAsync(indexName, suggestRequest, requestOptions); + } + + /** + * Sends a batch of document write actions to the index. + *

Request Body Schema

+ * + *
+     * {@code
+     * {
+     *     value (Required): [
+     *          (Required){
+     *             @search.action: String(upload/merge/mergeOrUpload/delete) (Optional)
+     *              (Optional): {
+     *                 String: BinaryData (Required)
+     *             }
+     *         }
+     *     ]
+     * }
+     * }
+     * 
+ * + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     value (Required): [
+     *          (Required){
+     *             key: String (Required)
+     *             errorMessage: String (Optional)
+     *             status: boolean (Required)
+     *             statusCode: int (Required)
+     *         }
+     *     ]
+     * }
+     * }
+     * 
+ * + * @param indexName The name of the index. + * @param batch The batch of index actions. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return response containing the status of operations for all documents in the indexing + * request along with {@link Response} on successful completion of {@link Mono}. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono> indexWithResponse(String indexName, BinaryData batch, + RequestOptions requestOptions) { + return this.serviceClient.indexWithResponseAsync(indexName, batch, requestOptions); + } + + /** + * Autocompletes incomplete query terms based on input text and matching terms in + * the index. + *

Query Parameters

+ * + * + * + * + * + * + * + * + * + * + * + *
Query Parameters
NameTypeRequiredDescription
autocompleteModeStringNoSpecifies 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. Allowed values: "oneTerm", "twoTerms", "oneTermWithContext".
$filterStringNoAn OData expression that filters the documents used to produce + * completed terms + * for the Autocomplete result.
fuzzyBooleanNoA 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.
highlightPostTagStringNoA string tag that is appended to hit highlights. Must + * be set with + * highlightPreTag. If omitted, hit highlighting is disabled.
highlightPreTagStringNoA string tag that is prepended to hit highlights. Must + * be set with + * highlightPostTag. If omitted, hit highlighting is disabled.
minimumCoverageDoubleNoA 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.
searchFieldsList<String>NoThe list of field names to consider when + * querying for auto-completed terms. + * Target fields must be included in the specified suggester. In the form of "," separated string.
$topIntegerNoThe number of auto-completed terms to retrieve. This must be a + * value between 1 + * and 100. The default is 5.
+ * You can add these to a request with {@link RequestOptions#addQueryParam} + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     @search.coverage: Double (Optional)
+     *     value (Required): [
+     *          (Required){
+     *             text: String (Required)
+     *             queryPlusText: String (Required)
+     *         }
+     *     ]
+     * }
+     * }
+     * 
+ * + * @param searchText The incomplete term which should be auto-completed. + * @param suggesterName The name of the suggester as specified in the suggesters collection that's part + * of the index definition. + * @param indexName The name of the index. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return the result of Autocomplete query along with {@link Response} on successful completion of {@link Mono}. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono> autocompleteGetWithResponse(String searchText, String suggesterName, + String indexName, RequestOptions requestOptions) { + return this.serviceClient.autocompleteGetWithResponseAsync(searchText, suggesterName, indexName, + requestOptions); + } + + /** + * Autocompletes incomplete query terms based on input text and matching terms in + * the index. + *

Request Body Schema

+ * + *
+     * {@code
+     * {
+     *     search: String (Required)
+     *     autocompleteMode: String(oneTerm/twoTerms/oneTermWithContext) (Optional)
+     *     filter: String (Optional)
+     *     fuzzy: Boolean (Optional)
+     *     highlightPostTag: String (Optional)
+     *     highlightPreTag: String (Optional)
+     *     minimumCoverage: Double (Optional)
+     *     searchFields: String (Optional)
+     *     suggesterName: String (Required)
+     *     top: Integer (Optional)
+     * }
+     * }
+     * 
+ * + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     @search.coverage: Double (Optional)
+     *     value (Required): [
+     *          (Required){
+     *             text: String (Required)
+     *             queryPlusText: String (Required)
+     *         }
+     *     ]
+     * }
+     * }
+     * 
+ * + * @param indexName The name of the index. + * @param autocompleteRequest The definition of the Autocomplete request. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return the result of Autocomplete query along with {@link Response} on successful completion of {@link Mono}. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono> autocompletePostWithResponse(String indexName, BinaryData autocompleteRequest, + RequestOptions requestOptions) { + return this.serviceClient.autocompletePostWithResponseAsync(indexName, autocompleteRequest, requestOptions); + } + + /** + * Queries the number of documents in the index. + * + * @param indexName The name of the index. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a 32-bit integer on successful completion of {@link Mono}. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono count(String indexName) { + // Generated convenience method for countWithResponse + RequestOptions requestOptions = new RequestOptions(); + return countWithResponse(indexName, requestOptions).flatMap(FluxUtil::toMono) + .map(protocolMethodData -> protocolMethodData.toString()); + } + + /** + * Searches for documents in the index. + * + * @param indexName The name of the index. + * @param searchText A full-text search query expression; Use "*" or omit this parameter to match + * all documents. + * @param includeTotalResultCount 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. + * @param 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. + * @param filter The OData $filter expression to apply to the search query. + * @param highlightFields The list of field names to use for hit highlights. Only searchable fields can + * be used for hit highlighting. + * @param highlightPostTag A string tag that is appended to hit highlights. Must be set with + * highlightPreTag. Default is &lt;/em&gt;. + * @param highlightPreTag A string tag that is prepended to hit highlights. Must be set with + * highlightPostTag. Default is &lt;em&gt;. + * @param minimumCoverage 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. + * @param orderBy 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. + * @param queryType A value that specifies the syntax of the search query. The default is 'simple'. + * Use 'full' if your query uses the Lucene query syntax. + * @param scoringParameters 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). + * @param scoringProfile The name of a scoring profile to evaluate match scores for matching documents + * in order to sort the results. + * @param searchFields 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. + * @param searchMode A value that specifies whether any or all of the search terms must be matched + * in order to count the document as a match. + * @param scoringStatistics 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. + * @param sessionId 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. + * @param select The list of fields to retrieve. If unspecified, all fields marked as + * retrievable in the schema are included. + * @param 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. + * @param 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. + * @param semanticConfiguration The name of the semantic configuration that lists which fields should be used + * for semantic ranking, captions, highlights, and answers. + * @param semanticErrorHandling Allows the user to choose whether a semantic call should fail completely, or to + * return partial results (default). + * @param semanticMaxWaitInMilliseconds 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. + * @param 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-<number of answers>` 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-<confidence 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-<number of maximum character length>', + * such as 'extractive|maxcharlength-600'. + * @param 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-<true/false>` 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-<number of maximum + * character length>', such as 'extractive|maxcharlength-600'. + * @param semanticQuery 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. + * @param queryRewrites 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-<number of rewrites>` option, such as + * `generative|count-3`. Defaults to `None`. This parameter is only valid if the + * query type is `semantic`. + * @param debug Enables a debugging tool that can be used to further explore your search + * results. + * @param queryLanguage The language of the query. + * @param speller Improve search recall by spell-correcting individual search query terms. + * @param semanticFields The list of field names used for semantic ranking. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return response containing search results from an index on successful completion of {@link Mono}. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono searchGet(String indexName, String searchText, Boolean includeTotalResultCount, + List facets, String filter, List highlightFields, String highlightPostTag, + String highlightPreTag, Double minimumCoverage, List orderBy, QueryType queryType, + List scoringParameters, String scoringProfile, List searchFields, SearchMode searchMode, + ScoringStatistics scoringStatistics, String sessionId, List select, Integer skip, Integer top, + String semanticConfiguration, SemanticErrorMode semanticErrorHandling, Integer semanticMaxWaitInMilliseconds, + QueryAnswerType answers, QueryCaptionType captions, String semanticQuery, QueryRewritesType queryRewrites, + QueryDebugMode debug, QueryLanguage queryLanguage, QuerySpellerType speller, List semanticFields) { + // Generated convenience method for searchGetWithResponse + RequestOptions requestOptions = new RequestOptions(); + if (searchText != null) { + requestOptions.addQueryParam("search", searchText, false); + } + if (includeTotalResultCount != null) { + requestOptions.addQueryParam("$count", String.valueOf(includeTotalResultCount), false); + } + if (facets != null) { + for (String paramItemValue : facets) { + if (paramItemValue != null) { + requestOptions.addQueryParam("facet", paramItemValue, false); + } + } + } + if (filter != null) { + requestOptions.addQueryParam("$filter", filter, false); + } + if (highlightFields != null) { + requestOptions.addQueryParam("highlight", + highlightFields.stream() + .map(paramItemValue -> Objects.toString(paramItemValue, "")) + .collect(Collectors.joining(",")), + false); + } + if (highlightPostTag != null) { + requestOptions.addQueryParam("highlightPostTag", highlightPostTag, false); + } + if (highlightPreTag != null) { + requestOptions.addQueryParam("highlightPreTag", highlightPreTag, false); + } + if (minimumCoverage != null) { + requestOptions.addQueryParam("minimumCoverage", String.valueOf(minimumCoverage), false); + } + if (orderBy != null) { + requestOptions.addQueryParam("$orderby", + orderBy.stream() + .map(paramItemValue -> Objects.toString(paramItemValue, "")) + .collect(Collectors.joining(",")), + false); + } + if (queryType != null) { + requestOptions.addQueryParam("queryType", queryType.toString(), false); + } + if (scoringParameters != null) { + for (String paramItemValue : scoringParameters) { + if (paramItemValue != null) { + requestOptions.addQueryParam("scoringParameter", paramItemValue, false); + } + } + } + if (scoringProfile != null) { + requestOptions.addQueryParam("scoringProfile", scoringProfile, false); + } + if (searchFields != null) { + requestOptions.addQueryParam("searchFields", + searchFields.stream() + .map(paramItemValue -> Objects.toString(paramItemValue, "")) + .collect(Collectors.joining(",")), + false); + } + if (searchMode != null) { + requestOptions.addQueryParam("searchMode", searchMode.toString(), false); + } + if (scoringStatistics != null) { + requestOptions.addQueryParam("scoringStatistics", scoringStatistics.toString(), false); + } + if (sessionId != null) { + requestOptions.addQueryParam("sessionId", sessionId, false); + } + if (select != null) { + requestOptions.addQueryParam("$select", + select.stream() + .map(paramItemValue -> Objects.toString(paramItemValue, "")) + .collect(Collectors.joining(",")), + false); + } + if (skip != null) { + requestOptions.addQueryParam("$skip", String.valueOf(skip), false); + } + if (top != null) { + requestOptions.addQueryParam("$top", String.valueOf(top), false); + } + if (semanticConfiguration != null) { + requestOptions.addQueryParam("semanticConfiguration", semanticConfiguration, false); + } + if (semanticErrorHandling != null) { + requestOptions.addQueryParam("semanticErrorHandling", semanticErrorHandling.toString(), false); + } + if (semanticMaxWaitInMilliseconds != null) { + requestOptions.addQueryParam("semanticMaxWaitInMilliseconds", String.valueOf(semanticMaxWaitInMilliseconds), + false); + } + if (answers != null) { + requestOptions.addQueryParam("answers", answers.toString(), false); + } + if (captions != null) { + requestOptions.addQueryParam("captions", captions.toString(), false); + } + if (semanticQuery != null) { + requestOptions.addQueryParam("semanticQuery", semanticQuery, false); + } + if (queryRewrites != null) { + requestOptions.addQueryParam("queryRewrites", queryRewrites.toString(), false); + } + if (debug != null) { + requestOptions.addQueryParam("debug", debug.toString(), false); + } + if (queryLanguage != null) { + requestOptions.addQueryParam("queryLanguage", queryLanguage.toString(), false); + } + if (speller != null) { + requestOptions.addQueryParam("speller", speller.toString(), false); + } + if (semanticFields != null) { + requestOptions.addQueryParam("semanticFields", + semanticFields.stream() + .map(paramItemValue -> Objects.toString(paramItemValue, "")) + .collect(Collectors.joining(",")), + false); + } + return searchGetWithResponse(indexName, requestOptions).flatMap(FluxUtil::toMono) + .map(protocolMethodData -> protocolMethodData.toObject(SearchDocumentsResult.class)); + } + + /** + * Searches for documents in the index. + * + * @param indexName The name of the index. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return response containing search results from an index on successful completion of {@link Mono}. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono searchGet(String indexName) { + // Generated convenience method for searchGetWithResponse + RequestOptions requestOptions = new RequestOptions(); + return searchGetWithResponse(indexName, requestOptions).flatMap(FluxUtil::toMono) + .map(protocolMethodData -> protocolMethodData.toObject(SearchDocumentsResult.class)); + } + + /** + * Searches for documents in the index. + * + * @param indexName The name of the index. + * @param searchRequest The definition of the Search request. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return response containing search results from an index on successful completion of {@link Mono}. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono searchPost(String indexName, SearchRequest searchRequest) { + // Generated convenience method for searchPostWithResponse + RequestOptions requestOptions = new RequestOptions(); + return searchPostWithResponse(indexName, BinaryData.fromObject(searchRequest), requestOptions) + .flatMap(FluxUtil::toMono) + .map(protocolMethodData -> protocolMethodData.toObject(SearchDocumentsResult.class)); + } + + /** + * Retrieves a document from the index. + * + * @param key The key of the document to retrieve. + * @param indexName The name of the index. + * @param selectedFields List of field names to retrieve for the document; Any field not retrieved will + * be missing from the returned document. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a document retrieved via a document lookup operation on successful completion of {@link Mono}. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono get(String key, String indexName, List selectedFields) { + // Generated convenience method for getWithResponse + RequestOptions requestOptions = new RequestOptions(); + if (selectedFields != null) { + requestOptions.addQueryParam("$select", + selectedFields.stream() + .map(paramItemValue -> Objects.toString(paramItemValue, "")) + .collect(Collectors.joining(",")), + false); + } + return getWithResponse(key, indexName, requestOptions).flatMap(FluxUtil::toMono) + .map(protocolMethodData -> protocolMethodData.toObject(LookupDocument.class)); + } + + /** + * Retrieves a document from the index. + * + * @param key The key of the document to retrieve. + * @param indexName The name of the index. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a document retrieved via a document lookup operation on successful completion of {@link Mono}. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono get(String key, String indexName) { + // Generated convenience method for getWithResponse + RequestOptions requestOptions = new RequestOptions(); + return getWithResponse(key, indexName, requestOptions).flatMap(FluxUtil::toMono) + .map(protocolMethodData -> protocolMethodData.toObject(LookupDocument.class)); + } + + /** + * Suggests documents in the index that match the given partial query text. + * + * @param searchText The search text to use to suggest documents. Must be at least 1 character, and + * no more than 100 characters. + * @param suggesterName The name of the suggester as specified in the suggesters collection that's part + * of the index definition. + * @param indexName The name of the index. + * @param filter An OData expression that filters the documents considered for suggestions. + * @param useFuzzyMatching 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. + * @param highlightPostTag A string tag that is appended to hit highlights. Must be set with + * highlightPreTag. If omitted, hit highlighting of suggestions is disabled. + * @param highlightPreTag A string tag that is prepended to hit highlights. Must be set with + * highlightPostTag. If omitted, hit highlighting of suggestions is disabled. + * @param minimumCoverage 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. + * @param orderBy 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. + * @param searchFields The list of field names to search for the specified search text. Target fields + * must be included in the specified suggester. + * @param select The list of fields to retrieve. If unspecified, only the key field will be + * included in the results. + * @param top The number of suggestions to retrieve. The value must be a number between 1 and + * 100. The default is 5. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return response containing suggestion query results from an index on successful completion of {@link Mono}. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono suggestGet(String searchText, String suggesterName, String indexName, + String filter, Boolean useFuzzyMatching, String highlightPostTag, String highlightPreTag, + Double minimumCoverage, List orderBy, List searchFields, List select, Integer top) { + // Generated convenience method for suggestGetWithResponse + RequestOptions requestOptions = new RequestOptions(); + if (filter != null) { + requestOptions.addQueryParam("$filter", filter, false); + } + if (useFuzzyMatching != null) { + requestOptions.addQueryParam("fuzzy", String.valueOf(useFuzzyMatching), false); + } + if (highlightPostTag != null) { + requestOptions.addQueryParam("highlightPostTag", highlightPostTag, false); + } + if (highlightPreTag != null) { + requestOptions.addQueryParam("highlightPreTag", highlightPreTag, false); + } + if (minimumCoverage != null) { + requestOptions.addQueryParam("minimumCoverage", String.valueOf(minimumCoverage), false); + } + if (orderBy != null) { + requestOptions.addQueryParam("$orderby", + orderBy.stream() + .map(paramItemValue -> Objects.toString(paramItemValue, "")) + .collect(Collectors.joining(",")), + false); + } + if (searchFields != null) { + requestOptions.addQueryParam("searchFields", + searchFields.stream() + .map(paramItemValue -> Objects.toString(paramItemValue, "")) + .collect(Collectors.joining(",")), + false); + } + if (select != null) { + requestOptions.addQueryParam("$select", + select.stream() + .map(paramItemValue -> Objects.toString(paramItemValue, "")) + .collect(Collectors.joining(",")), + false); + } + if (top != null) { + requestOptions.addQueryParam("$top", String.valueOf(top), false); + } + return suggestGetWithResponse(searchText, suggesterName, indexName, requestOptions).flatMap(FluxUtil::toMono) + .map(protocolMethodData -> protocolMethodData.toObject(SuggestDocumentsResult.class)); + } + + /** + * Suggests documents in the index that match the given partial query text. + * + * @param searchText The search text to use to suggest documents. Must be at least 1 character, and + * no more than 100 characters. + * @param suggesterName The name of the suggester as specified in the suggesters collection that's part + * of the index definition. + * @param indexName The name of the index. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return response containing suggestion query results from an index on successful completion of {@link Mono}. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono suggestGet(String searchText, String suggesterName, String indexName) { + // Generated convenience method for suggestGetWithResponse + RequestOptions requestOptions = new RequestOptions(); + return suggestGetWithResponse(searchText, suggesterName, indexName, requestOptions).flatMap(FluxUtil::toMono) + .map(protocolMethodData -> protocolMethodData.toObject(SuggestDocumentsResult.class)); + } + + /** + * Suggests documents in the index that match the given partial query text. + * + * @param indexName The name of the index. + * @param suggestRequest The Suggest request. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return response containing suggestion query results from an index on successful completion of {@link Mono}. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono suggestPost(String indexName, SuggestRequest suggestRequest) { + // Generated convenience method for suggestPostWithResponse + RequestOptions requestOptions = new RequestOptions(); + return suggestPostWithResponse(indexName, BinaryData.fromObject(suggestRequest), requestOptions) + .flatMap(FluxUtil::toMono) + .map(protocolMethodData -> protocolMethodData.toObject(SuggestDocumentsResult.class)); + } + + /** + * Sends a batch of document write actions to the index. + * + * @param indexName The name of the index. + * @param batch The batch of index actions. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return response containing the status of operations for all documents in the indexing + * request on successful completion of {@link Mono}. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono index(String indexName, IndexBatch batch) { + // Generated convenience method for indexWithResponse + RequestOptions requestOptions = new RequestOptions(); + return indexWithResponse(indexName, BinaryData.fromObject(batch), requestOptions).flatMap(FluxUtil::toMono) + .map(protocolMethodData -> protocolMethodData.toObject(IndexDocumentsResult.class)); + } + + /** + * Autocompletes incomplete query terms based on input text and matching terms in + * the index. + * + * @param searchText The incomplete term which should be auto-completed. + * @param suggesterName The name of the suggester as specified in the suggesters collection that's part + * of the index definition. + * @param indexName The name of the index. + * @param autocompleteMode 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. + * @param filter An OData expression that filters the documents used to produce completed terms + * for the Autocomplete result. + * @param useFuzzyMatching 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. + * @param highlightPostTag A string tag that is appended to hit highlights. Must be set with + * highlightPreTag. If omitted, hit highlighting is disabled. + * @param highlightPreTag A string tag that is prepended to hit highlights. Must be set with + * highlightPostTag. If omitted, hit highlighting is disabled. + * @param minimumCoverage 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. + * @param searchFields The list of field names to consider when querying for auto-completed terms. + * Target fields must be included in the specified suggester. + * @param top The number of auto-completed terms to retrieve. This must be a value between 1 + * and 100. The default is 5. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the result of Autocomplete query on successful completion of {@link Mono}. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono autocompleteGet(String searchText, String suggesterName, String indexName, + AutocompleteMode autocompleteMode, String filter, Boolean useFuzzyMatching, String highlightPostTag, + String highlightPreTag, Double minimumCoverage, List searchFields, Integer top) { + // Generated convenience method for autocompleteGetWithResponse + RequestOptions requestOptions = new RequestOptions(); + if (autocompleteMode != null) { + requestOptions.addQueryParam("autocompleteMode", autocompleteMode.toString(), false); + } + if (filter != null) { + requestOptions.addQueryParam("$filter", filter, false); + } + if (useFuzzyMatching != null) { + requestOptions.addQueryParam("fuzzy", String.valueOf(useFuzzyMatching), false); + } + if (highlightPostTag != null) { + requestOptions.addQueryParam("highlightPostTag", highlightPostTag, false); + } + if (highlightPreTag != null) { + requestOptions.addQueryParam("highlightPreTag", highlightPreTag, false); + } + if (minimumCoverage != null) { + requestOptions.addQueryParam("minimumCoverage", String.valueOf(minimumCoverage), false); + } + if (searchFields != null) { + requestOptions.addQueryParam("searchFields", + searchFields.stream() + .map(paramItemValue -> Objects.toString(paramItemValue, "")) + .collect(Collectors.joining(",")), + false); + } + if (top != null) { + requestOptions.addQueryParam("$top", String.valueOf(top), false); + } + return autocompleteGetWithResponse(searchText, suggesterName, indexName, requestOptions) + .flatMap(FluxUtil::toMono) + .map(protocolMethodData -> protocolMethodData.toObject(AutocompleteResult.class)); + } + + /** + * Autocompletes incomplete query terms based on input text and matching terms in + * the index. + * + * @param searchText The incomplete term which should be auto-completed. + * @param suggesterName The name of the suggester as specified in the suggesters collection that's part + * of the index definition. + * @param indexName The name of the index. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the result of Autocomplete query on successful completion of {@link Mono}. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono autocompleteGet(String searchText, String suggesterName, String indexName) { + // Generated convenience method for autocompleteGetWithResponse + RequestOptions requestOptions = new RequestOptions(); + return autocompleteGetWithResponse(searchText, suggesterName, indexName, requestOptions) + .flatMap(FluxUtil::toMono) + .map(protocolMethodData -> protocolMethodData.toObject(AutocompleteResult.class)); + } + + /** + * Autocompletes incomplete query terms based on input text and matching terms in + * the index. + * + * @param indexName The name of the index. + * @param autocompleteRequest The definition of the Autocomplete request. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the result of Autocomplete query on successful completion of {@link Mono}. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono autocompletePost(String indexName, AutocompleteRequest autocompleteRequest) { + // Generated convenience method for autocompletePostWithResponse + RequestOptions requestOptions = new RequestOptions(); + return autocompletePostWithResponse(indexName, BinaryData.fromObject(autocompleteRequest), requestOptions) + .flatMap(FluxUtil::toMono) + .map(protocolMethodData -> protocolMethodData.toObject(AutocompleteResult.class)); + } +} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/DocumentsClient.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/DocumentsClient.java new file mode 100644 index 000000000000..dea4c604cc01 --- /dev/null +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/DocumentsClient.java @@ -0,0 +1,1664 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.search.documents; + +import com.azure.core.annotation.Generated; +import com.azure.core.annotation.ReturnType; +import com.azure.core.annotation.ServiceClient; +import com.azure.core.annotation.ServiceMethod; +import com.azure.core.exception.ClientAuthenticationException; +import com.azure.core.exception.HttpResponseException; +import com.azure.core.exception.ResourceModifiedException; +import com.azure.core.exception.ResourceNotFoundException; +import com.azure.core.http.rest.RequestOptions; +import com.azure.core.http.rest.Response; +import com.azure.core.util.BinaryData; +import com.azure.search.documents.implementation.DocumentsImpl; +import com.azure.search.documents.models.AutocompleteMode; +import com.azure.search.documents.models.AutocompleteRequest; +import com.azure.search.documents.models.AutocompleteResult; +import com.azure.search.documents.models.IndexBatch; +import com.azure.search.documents.models.IndexDocumentsResult; +import com.azure.search.documents.models.LookupDocument; +import com.azure.search.documents.models.QueryAnswerType; +import com.azure.search.documents.models.QueryCaptionType; +import com.azure.search.documents.models.QueryDebugMode; +import com.azure.search.documents.models.QueryLanguage; +import com.azure.search.documents.models.QueryRewritesType; +import com.azure.search.documents.models.QuerySpellerType; +import com.azure.search.documents.models.QueryType; +import com.azure.search.documents.models.ScoringStatistics; +import com.azure.search.documents.models.SearchDocumentsResult; +import com.azure.search.documents.models.SearchMode; +import com.azure.search.documents.models.SearchRequest; +import com.azure.search.documents.models.SemanticErrorMode; +import com.azure.search.documents.models.SuggestDocumentsResult; +import com.azure.search.documents.models.SuggestRequest; +import java.util.List; +import java.util.Objects; +import java.util.stream.Collectors; + +/** + * Initializes a new instance of the synchronous SearchClient type. + */ +@ServiceClient(builder = SearchClientBuilder.class) +public final class DocumentsClient { + @Generated + private final DocumentsImpl serviceClient; + + /** + * Initializes an instance of DocumentsClient class. + * + * @param serviceClient the service client implementation. + */ + @Generated + DocumentsClient(DocumentsImpl serviceClient) { + this.serviceClient = serviceClient; + } + + /** + * Queries the number of documents in the index. + *

Response Body Schema

+ * + *
+     * {@code
+     * int
+     * }
+     * 
+ * + * @param indexName The name of the index. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return a 32-bit integer along with {@link Response}. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public Response countWithResponse(String indexName, RequestOptions requestOptions) { + return this.serviceClient.countWithResponse(indexName, requestOptions); + } + + /** + * Searches for documents in the index. + *

Query Parameters

+ * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + *
Query Parameters
NameTypeRequiredDescription
searchStringNoA full-text search query expression; Use "*" or omit this + * parameter to match + * all documents.
$countBooleanNoA 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.
facetList<String>NoThe 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. Call {@link RequestOptions#addQueryParam} to add string to array.
$filterStringNoThe OData $filter expression to apply to the search + * query.
highlightList<String>NoThe list of field names to use for hit + * highlights. Only searchable fields can + * be used for hit highlighting. In the form of "," separated string.
highlightPostTagStringNoA string tag that is appended to hit highlights. Must + * be set with + * highlightPreTag. Default is &lt;/em&gt;.
highlightPreTagStringNoA string tag that is prepended to hit highlights. Must + * be set with + * highlightPostTag. Default is &lt;em&gt;.
minimumCoverageDoubleNoA 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.
$orderbyList<String>NoThe 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. In the form of "," separated string.
queryTypeStringNoA value that specifies the syntax of the search query. The + * default is 'simple'. + * Use 'full' if your query uses the Lucene query syntax. Allowed values: "simple", "full", "semantic".
scoringParameterList<String>NoThe 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). Call + * {@link RequestOptions#addQueryParam} to add string to array.
scoringProfileStringNoThe name of a scoring profile to evaluate match scores + * for matching documents + * in order to sort the results.
searchFieldsList<String>NoThe 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. In the form of "," separated string.
searchModeStringNoA value that specifies whether any or all of the search + * terms must be matched + * in order to count the document as a match. Allowed values: "any", "all".
scoringStatisticsStringNoA value that specifies whether we want to calculate + * scoring statistics (such as + * document frequency) globally for more consistent scoring, or locally, for lower + * latency. Allowed values: "local", "global".
sessionIdStringNoA 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.
$selectList<String>NoThe list of fields to retrieve. If unspecified, all + * fields marked as + * retrievable in the schema are included. In the form of "," separated string.
$skipIntegerNoThe 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.
$topIntegerNoThe 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.
semanticConfigurationStringNoThe name of the semantic configuration that lists + * which fields should be used + * for semantic ranking, captions, highlights, and answers
semanticErrorHandlingStringNoAllows the user to choose whether a semantic call + * should fail completely, or to + * return partial results (default). Allowed values: "partial", "fail".
semanticMaxWaitInMillisecondsIntegerNoAllows the user to set an upper bound on + * the amount of time it takes for + * semantic enrichment to finish processing before the request fails.
answersStringNoThis 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-<number of answers>` 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-<confidence 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-<number of maximum character length>', + * such as 'extractive|maxcharlength-600'. Allowed values: "none", "extractive".
captionsStringNoThis 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-<true/false>` 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-<number of maximum + * character length>', such as 'extractive|maxcharlength-600'. Allowed values: "none", "extractive".
semanticQueryStringNoAllows 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.
queryRewritesStringNoWhen 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-<number of rewrites>` option, such as + * `generative|count-3`. Defaults to `None`. This parameter is only valid if the + * query type is `semantic`. Allowed values: "none", "generative".
debugStringNoEnables a debugging tool that can be used to further explore your + * search + * results. Allowed values: "disabled", "semantic", "vector", "queryRewrites", "all".
queryLanguageStringNoThe language of the query. Allowed values: "none", + * "en-us", "en-gb", "en-in", "en-ca", "en-au", "fr-fr", "fr-ca", "de-de", "es-es", "es-mx", "zh-cn", "zh-tw", + * "pt-br", "pt-pt", "it-it", "ja-jp", "ko-kr", "ru-ru", "cs-cz", "nl-be", "nl-nl", "hu-hu", "pl-pl", "sv-se", + * "tr-tr", "hi-in", "ar-sa", "ar-eg", "ar-ma", "ar-kw", "ar-jo", "da-dk", "no-no", "bg-bg", "hr-hr", "hr-ba", + * "ms-my", "ms-bn", "sl-sl", "ta-in", "vi-vn", "el-gr", "ro-ro", "is-is", "id-id", "th-th", "lt-lt", "uk-ua", + * "lv-lv", "et-ee", "ca-es", "fi-fi", "sr-ba", "sr-me", "sr-rs", "sk-sk", "nb-no", "hy-am", "bn-in", "eu-es", + * "gl-es", "gu-in", "he-il", "ga-ie", "kn-in", "ml-in", "mr-in", "fa-ae", "pa-in", "te-in", "ur-pk".
spellerStringNoImprove search recall by spell-correcting individual search + * query terms. Allowed values: "none", "lexicon".
semanticFieldsList<String>NoThe list of field names used for semantic + * ranking. In the form of "," separated string.
+ * You can add these to a request with {@link RequestOptions#addQueryParam} + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     @odata.count: Long (Optional)
+     *     @search.coverage: Double (Optional)
+     *     @search.facets (Optional): {
+     *         String (Required): [
+     *              (Required){
+     *                 count: Long (Optional)
+     *                 @search.facets (Optional): {
+     *                     String (Required): [
+     *                         (recursive schema, see above)
+     *                     ]
+     *                 }
+     *                 sum: Long (Optional)
+     *                  (Optional): {
+     *                     String: BinaryData (Required)
+     *                 }
+     *             }
+     *         ]
+     *     }
+     *     @search.answers (Optional): [
+     *          (Optional){
+     *             score: Double (Optional)
+     *             key: String (Optional)
+     *             text: String (Optional)
+     *             highlights: String (Optional)
+     *              (Optional): {
+     *                 String: BinaryData (Required)
+     *             }
+     *         }
+     *     ]
+     *     @search.debug (Optional): {
+     *         queryRewrites (Optional): {
+     *             text (Optional): {
+     *                 inputQuery: String (Optional)
+     *                 rewrites (Optional): [
+     *                     String (Optional)
+     *                 ]
+     *             }
+     *             vectors (Optional): [
+     *                 (recursive schema, see above)
+     *             ]
+     *         }
+     *     }
+     *     @search.nextPageParameters (Optional): {
+     *         count: Boolean (Optional)
+     *         facets (Optional): [
+     *             String (Optional)
+     *         ]
+     *         filter: String (Optional)
+     *         highlight: String (Optional)
+     *         highlightPostTag: String (Optional)
+     *         highlightPreTag: String (Optional)
+     *         minimumCoverage: Double (Optional)
+     *         orderby: String (Optional)
+     *         queryType: String(simple/full/semantic) (Optional)
+     *         scoringStatistics: String(local/global) (Optional)
+     *         sessionId: String (Optional)
+     *         scoringParameters (Optional): [
+     *             String (Optional)
+     *         ]
+     *         scoringProfile: String (Optional)
+     *         debug: String(disabled/semantic/vector/queryRewrites/all) (Optional)
+     *         search: String (Optional)
+     *         searchFields: String (Optional)
+     *         searchMode: String(any/all) (Optional)
+     *         queryLanguage: String(none/en-us/en-gb/en-in/en-ca/en-au/fr-fr/fr-ca/de-de/es-es/es-mx/zh-cn/zh-tw/pt-br/pt-pt/it-it/ja-jp/ko-kr/ru-ru/cs-cz/nl-be/nl-nl/hu-hu/pl-pl/sv-se/tr-tr/hi-in/ar-sa/ar-eg/ar-ma/ar-kw/ar-jo/da-dk/no-no/bg-bg/hr-hr/hr-ba/ms-my/ms-bn/sl-sl/ta-in/vi-vn/el-gr/ro-ro/is-is/id-id/th-th/lt-lt/uk-ua/lv-lv/et-ee/ca-es/fi-fi/sr-ba/sr-me/sr-rs/sk-sk/nb-no/hy-am/bn-in/eu-es/gl-es/gu-in/he-il/ga-ie/kn-in/ml-in/mr-in/fa-ae/pa-in/te-in/ur-pk) (Optional)
+     *         speller: String(none/lexicon) (Optional)
+     *         select: String (Optional)
+     *         skip: Integer (Optional)
+     *         top: Integer (Optional)
+     *         semanticConfiguration: String (Optional)
+     *         semanticErrorHandling: String(partial/fail) (Optional)
+     *         semanticMaxWaitInMilliseconds: Integer (Optional)
+     *         semanticQuery: String (Optional)
+     *         answers: String(none/extractive) (Optional)
+     *         captions: String(none/extractive) (Optional)
+     *         queryRewrites: String(none/generative) (Optional)
+     *         semanticFields: String (Optional)
+     *         vectorQueries (Optional): [
+     *              (Optional){
+     *                 kind: String(vector/text/imageUrl/imageBinary) (Required)
+     *                 k: Integer (Optional)
+     *                 fields: String (Optional)
+     *                 exhaustive: Boolean (Optional)
+     *                 oversampling: Double (Optional)
+     *                 weight: Double (Optional)
+     *                 threshold (Optional): {
+     *                     kind: String(vectorSimilarity/searchScore) (Required)
+     *                 }
+     *                 filterOverride: String (Optional)
+     *             }
+     *         ]
+     *         vectorFilterMode: String(postFilter/preFilter) (Optional)
+     *         hybridSearch (Optional): {
+     *             maxTextRecallSize: Integer (Optional)
+     *             countAndFacetMode: String(countRetrievableResults/countAllResults) (Optional)
+     *         }
+     *     }
+     *     value (Required): [
+     *          (Required){
+     *             @search.score: double (Required)
+     *             @search.rerankerScore: Double (Optional)
+     *             @search.highlights (Optional): {
+     *                 String (Required): [
+     *                     String (Required)
+     *                 ]
+     *             }
+     *             @search.captions (Optional): [
+     *                  (Optional){
+     *                     text: String (Optional)
+     *                     highlights: String (Optional)
+     *                      (Optional): {
+     *                         String: BinaryData (Required)
+     *                     }
+     *                 }
+     *             ]
+     *             @search.documentDebugInfo (Optional): [
+     *                  (Optional){
+     *                     semantic (Optional): {
+     *                         titleField (Optional): {
+     *                             name: String (Optional)
+     *                             state: String(used/unused/partial) (Optional)
+     *                         }
+     *                         contentFields (Optional): [
+     *                             (recursive schema, see above)
+     *                         ]
+     *                         keywordFields (Optional): [
+     *                             (recursive schema, see above)
+     *                         ]
+     *                         rerankerInput (Optional): {
+     *                             title: String (Optional)
+     *                             content: String (Optional)
+     *                             keywords: String (Optional)
+     *                         }
+     *                     }
+     *                     vectors (Optional): {
+     *                         subscores (Optional): {
+     *                             text (Optional): {
+     *                                 searchScore: Double (Optional)
+     *                             }
+     *                             vectors (Optional): [
+     *                                  (Optional){
+     *                                     String (Required): {
+     *                                         searchScore: Double (Optional)
+     *                                         vectorSimilarity: Double (Optional)
+     *                                     }
+     *                                 }
+     *                             ]
+     *                             documentBoost: Double (Optional)
+     *                         }
+     *                     }
+     *                 }
+     *             ]
+     *              (Optional): {
+     *                 String: BinaryData (Required)
+     *             }
+     *         }
+     *     ]
+     *     @odata.nextLink: String (Optional)
+     *     @search.semanticPartialResponseReason: String(maxWaitExceeded/capacityOverloaded/transient) (Optional)
+     *     @search.semanticPartialResponseType: String(baseResults/rerankedResults) (Optional)
+     *     @search.semanticQueryRewritesResultType: String(originalQueryOnly) (Optional)
+     * }
+     * }
+     * 
+ * + * @param indexName The name of the index. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return response containing search results from an index along with {@link Response}. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public Response searchGetWithResponse(String indexName, RequestOptions requestOptions) { + return this.serviceClient.searchGetWithResponse(indexName, requestOptions); + } + + /** + * Searches for documents in the index. + *

Request Body Schema

+ * + *
+     * {@code
+     * {
+     *     count: Boolean (Optional)
+     *     facets (Optional): [
+     *         String (Optional)
+     *     ]
+     *     filter: String (Optional)
+     *     highlight: String (Optional)
+     *     highlightPostTag: String (Optional)
+     *     highlightPreTag: String (Optional)
+     *     minimumCoverage: Double (Optional)
+     *     orderby: String (Optional)
+     *     queryType: String(simple/full/semantic) (Optional)
+     *     scoringStatistics: String(local/global) (Optional)
+     *     sessionId: String (Optional)
+     *     scoringParameters (Optional): [
+     *         String (Optional)
+     *     ]
+     *     scoringProfile: String (Optional)
+     *     debug: String(disabled/semantic/vector/queryRewrites/all) (Optional)
+     *     search: String (Optional)
+     *     searchFields: String (Optional)
+     *     searchMode: String(any/all) (Optional)
+     *     queryLanguage: String(none/en-us/en-gb/en-in/en-ca/en-au/fr-fr/fr-ca/de-de/es-es/es-mx/zh-cn/zh-tw/pt-br/pt-pt/it-it/ja-jp/ko-kr/ru-ru/cs-cz/nl-be/nl-nl/hu-hu/pl-pl/sv-se/tr-tr/hi-in/ar-sa/ar-eg/ar-ma/ar-kw/ar-jo/da-dk/no-no/bg-bg/hr-hr/hr-ba/ms-my/ms-bn/sl-sl/ta-in/vi-vn/el-gr/ro-ro/is-is/id-id/th-th/lt-lt/uk-ua/lv-lv/et-ee/ca-es/fi-fi/sr-ba/sr-me/sr-rs/sk-sk/nb-no/hy-am/bn-in/eu-es/gl-es/gu-in/he-il/ga-ie/kn-in/ml-in/mr-in/fa-ae/pa-in/te-in/ur-pk) (Optional)
+     *     speller: String(none/lexicon) (Optional)
+     *     select: String (Optional)
+     *     skip: Integer (Optional)
+     *     top: Integer (Optional)
+     *     semanticConfiguration: String (Optional)
+     *     semanticErrorHandling: String(partial/fail) (Optional)
+     *     semanticMaxWaitInMilliseconds: Integer (Optional)
+     *     semanticQuery: String (Optional)
+     *     answers: String(none/extractive) (Optional)
+     *     captions: String(none/extractive) (Optional)
+     *     queryRewrites: String(none/generative) (Optional)
+     *     semanticFields: String (Optional)
+     *     vectorQueries (Optional): [
+     *          (Optional){
+     *             kind: String(vector/text/imageUrl/imageBinary) (Required)
+     *             k: Integer (Optional)
+     *             fields: String (Optional)
+     *             exhaustive: Boolean (Optional)
+     *             oversampling: Double (Optional)
+     *             weight: Double (Optional)
+     *             threshold (Optional): {
+     *                 kind: String(vectorSimilarity/searchScore) (Required)
+     *             }
+     *             filterOverride: String (Optional)
+     *         }
+     *     ]
+     *     vectorFilterMode: String(postFilter/preFilter) (Optional)
+     *     hybridSearch (Optional): {
+     *         maxTextRecallSize: Integer (Optional)
+     *         countAndFacetMode: String(countRetrievableResults/countAllResults) (Optional)
+     *     }
+     * }
+     * }
+     * 
+ * + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     @odata.count: Long (Optional)
+     *     @search.coverage: Double (Optional)
+     *     @search.facets (Optional): {
+     *         String (Required): [
+     *              (Required){
+     *                 count: Long (Optional)
+     *                 @search.facets (Optional): {
+     *                     String (Required): [
+     *                         (recursive schema, see above)
+     *                     ]
+     *                 }
+     *                 sum: Long (Optional)
+     *                  (Optional): {
+     *                     String: BinaryData (Required)
+     *                 }
+     *             }
+     *         ]
+     *     }
+     *     @search.answers (Optional): [
+     *          (Optional){
+     *             score: Double (Optional)
+     *             key: String (Optional)
+     *             text: String (Optional)
+     *             highlights: String (Optional)
+     *              (Optional): {
+     *                 String: BinaryData (Required)
+     *             }
+     *         }
+     *     ]
+     *     @search.debug (Optional): {
+     *         queryRewrites (Optional): {
+     *             text (Optional): {
+     *                 inputQuery: String (Optional)
+     *                 rewrites (Optional): [
+     *                     String (Optional)
+     *                 ]
+     *             }
+     *             vectors (Optional): [
+     *                 (recursive schema, see above)
+     *             ]
+     *         }
+     *     }
+     *     @search.nextPageParameters (Optional): {
+     *         count: Boolean (Optional)
+     *         facets (Optional): [
+     *             String (Optional)
+     *         ]
+     *         filter: String (Optional)
+     *         highlight: String (Optional)
+     *         highlightPostTag: String (Optional)
+     *         highlightPreTag: String (Optional)
+     *         minimumCoverage: Double (Optional)
+     *         orderby: String (Optional)
+     *         queryType: String(simple/full/semantic) (Optional)
+     *         scoringStatistics: String(local/global) (Optional)
+     *         sessionId: String (Optional)
+     *         scoringParameters (Optional): [
+     *             String (Optional)
+     *         ]
+     *         scoringProfile: String (Optional)
+     *         debug: String(disabled/semantic/vector/queryRewrites/all) (Optional)
+     *         search: String (Optional)
+     *         searchFields: String (Optional)
+     *         searchMode: String(any/all) (Optional)
+     *         queryLanguage: String(none/en-us/en-gb/en-in/en-ca/en-au/fr-fr/fr-ca/de-de/es-es/es-mx/zh-cn/zh-tw/pt-br/pt-pt/it-it/ja-jp/ko-kr/ru-ru/cs-cz/nl-be/nl-nl/hu-hu/pl-pl/sv-se/tr-tr/hi-in/ar-sa/ar-eg/ar-ma/ar-kw/ar-jo/da-dk/no-no/bg-bg/hr-hr/hr-ba/ms-my/ms-bn/sl-sl/ta-in/vi-vn/el-gr/ro-ro/is-is/id-id/th-th/lt-lt/uk-ua/lv-lv/et-ee/ca-es/fi-fi/sr-ba/sr-me/sr-rs/sk-sk/nb-no/hy-am/bn-in/eu-es/gl-es/gu-in/he-il/ga-ie/kn-in/ml-in/mr-in/fa-ae/pa-in/te-in/ur-pk) (Optional)
+     *         speller: String(none/lexicon) (Optional)
+     *         select: String (Optional)
+     *         skip: Integer (Optional)
+     *         top: Integer (Optional)
+     *         semanticConfiguration: String (Optional)
+     *         semanticErrorHandling: String(partial/fail) (Optional)
+     *         semanticMaxWaitInMilliseconds: Integer (Optional)
+     *         semanticQuery: String (Optional)
+     *         answers: String(none/extractive) (Optional)
+     *         captions: String(none/extractive) (Optional)
+     *         queryRewrites: String(none/generative) (Optional)
+     *         semanticFields: String (Optional)
+     *         vectorQueries (Optional): [
+     *              (Optional){
+     *                 kind: String(vector/text/imageUrl/imageBinary) (Required)
+     *                 k: Integer (Optional)
+     *                 fields: String (Optional)
+     *                 exhaustive: Boolean (Optional)
+     *                 oversampling: Double (Optional)
+     *                 weight: Double (Optional)
+     *                 threshold (Optional): {
+     *                     kind: String(vectorSimilarity/searchScore) (Required)
+     *                 }
+     *                 filterOverride: String (Optional)
+     *             }
+     *         ]
+     *         vectorFilterMode: String(postFilter/preFilter) (Optional)
+     *         hybridSearch (Optional): {
+     *             maxTextRecallSize: Integer (Optional)
+     *             countAndFacetMode: String(countRetrievableResults/countAllResults) (Optional)
+     *         }
+     *     }
+     *     value (Required): [
+     *          (Required){
+     *             @search.score: double (Required)
+     *             @search.rerankerScore: Double (Optional)
+     *             @search.highlights (Optional): {
+     *                 String (Required): [
+     *                     String (Required)
+     *                 ]
+     *             }
+     *             @search.captions (Optional): [
+     *                  (Optional){
+     *                     text: String (Optional)
+     *                     highlights: String (Optional)
+     *                      (Optional): {
+     *                         String: BinaryData (Required)
+     *                     }
+     *                 }
+     *             ]
+     *             @search.documentDebugInfo (Optional): [
+     *                  (Optional){
+     *                     semantic (Optional): {
+     *                         titleField (Optional): {
+     *                             name: String (Optional)
+     *                             state: String(used/unused/partial) (Optional)
+     *                         }
+     *                         contentFields (Optional): [
+     *                             (recursive schema, see above)
+     *                         ]
+     *                         keywordFields (Optional): [
+     *                             (recursive schema, see above)
+     *                         ]
+     *                         rerankerInput (Optional): {
+     *                             title: String (Optional)
+     *                             content: String (Optional)
+     *                             keywords: String (Optional)
+     *                         }
+     *                     }
+     *                     vectors (Optional): {
+     *                         subscores (Optional): {
+     *                             text (Optional): {
+     *                                 searchScore: Double (Optional)
+     *                             }
+     *                             vectors (Optional): [
+     *                                  (Optional){
+     *                                     String (Required): {
+     *                                         searchScore: Double (Optional)
+     *                                         vectorSimilarity: Double (Optional)
+     *                                     }
+     *                                 }
+     *                             ]
+     *                             documentBoost: Double (Optional)
+     *                         }
+     *                     }
+     *                 }
+     *             ]
+     *              (Optional): {
+     *                 String: BinaryData (Required)
+     *             }
+     *         }
+     *     ]
+     *     @odata.nextLink: String (Optional)
+     *     @search.semanticPartialResponseReason: String(maxWaitExceeded/capacityOverloaded/transient) (Optional)
+     *     @search.semanticPartialResponseType: String(baseResults/rerankedResults) (Optional)
+     *     @search.semanticQueryRewritesResultType: String(originalQueryOnly) (Optional)
+     * }
+     * }
+     * 
+ * + * @param indexName The name of the index. + * @param searchRequest The definition of the Search request. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return response containing search results from an index along with {@link Response}. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public Response searchPostWithResponse(String indexName, BinaryData searchRequest, + RequestOptions requestOptions) { + return this.serviceClient.searchPostWithResponse(indexName, searchRequest, requestOptions); + } + + /** + * Retrieves a document from the index. + *

Query Parameters

+ * + * + * + * + *
Query Parameters
NameTypeRequiredDescription
$selectList<String>NoList of field names to retrieve for the document; + * Any field not retrieved will + * be missing from the returned document. In the form of "," separated string.
+ * You can add these to a request with {@link RequestOptions#addQueryParam} + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *      (Optional): {
+     *         String: BinaryData (Required)
+     *     }
+     * }
+     * }
+     * 
+ * + * @param key The key of the document to retrieve. + * @param indexName The name of the index. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return a document retrieved via a document lookup operation along with {@link Response}. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public Response getWithResponse(String key, String indexName, RequestOptions requestOptions) { + return this.serviceClient.getWithResponse(key, indexName, requestOptions); + } + + /** + * Suggests documents in the index that match the given partial query text. + *

Query Parameters

+ * + * + * + * + * + * + * + * + * + * + * + * + *
Query Parameters
NameTypeRequiredDescription
$filterStringNoAn OData expression that filters the documents considered for + * suggestions.
fuzzyBooleanNoA 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.
highlightPostTagStringNoA string tag that is appended to hit highlights. Must + * be set with + * highlightPreTag. If omitted, hit highlighting of suggestions is disabled.
highlightPreTagStringNoA string tag that is prepended to hit highlights. Must + * be set with + * highlightPostTag. If omitted, hit highlighting of suggestions is disabled.
minimumCoverageDoubleNoA 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.
$orderbyList<String>NoThe 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. In the form of "," separated string.
searchFieldsList<String>NoThe list of field names to search for the + * specified search text. Target fields + * must be included in the specified suggester. In the form of "," separated string.
$selectList<String>NoThe list of fields to retrieve. If unspecified, + * only the key field will be + * included in the results. In the form of "," separated string.
$topIntegerNoThe number of suggestions to retrieve. The value must be a number + * between 1 and + * 100. The default is 5.
+ * You can add these to a request with {@link RequestOptions#addQueryParam} + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     value (Required): [
+     *          (Required){
+     *             @search.text: String (Required)
+     *              (Optional): {
+     *                 String: BinaryData (Required)
+     *             }
+     *         }
+     *     ]
+     *     @search.coverage: Double (Optional)
+     * }
+     * }
+     * 
+ * + * @param searchText The search text to use to suggest documents. Must be at least 1 character, and + * no more than 100 characters. + * @param suggesterName The name of the suggester as specified in the suggesters collection that's part + * of the index definition. + * @param indexName The name of the index. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return response containing suggestion query results from an index along with {@link Response}. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public Response suggestGetWithResponse(String searchText, String suggesterName, String indexName, + RequestOptions requestOptions) { + return this.serviceClient.suggestGetWithResponse(searchText, suggesterName, indexName, requestOptions); + } + + /** + * Suggests documents in the index that match the given partial query text. + *

Request Body Schema

+ * + *
+     * {@code
+     * {
+     *     filter: String (Optional)
+     *     fuzzy: Boolean (Optional)
+     *     highlightPostTag: String (Optional)
+     *     highlightPreTag: String (Optional)
+     *     minimumCoverage: Double (Optional)
+     *     orderby: String (Optional)
+     *     search: String (Required)
+     *     searchFields: String (Optional)
+     *     select: String (Optional)
+     *     suggesterName: String (Required)
+     *     top: Integer (Optional)
+     * }
+     * }
+     * 
+ * + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     value (Required): [
+     *          (Required){
+     *             @search.text: String (Required)
+     *              (Optional): {
+     *                 String: BinaryData (Required)
+     *             }
+     *         }
+     *     ]
+     *     @search.coverage: Double (Optional)
+     * }
+     * }
+     * 
+ * + * @param indexName The name of the index. + * @param suggestRequest The Suggest request. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return response containing suggestion query results from an index along with {@link Response}. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public Response suggestPostWithResponse(String indexName, BinaryData suggestRequest, + RequestOptions requestOptions) { + return this.serviceClient.suggestPostWithResponse(indexName, suggestRequest, requestOptions); + } + + /** + * Sends a batch of document write actions to the index. + *

Request Body Schema

+ * + *
+     * {@code
+     * {
+     *     value (Required): [
+     *          (Required){
+     *             @search.action: String(upload/merge/mergeOrUpload/delete) (Optional)
+     *              (Optional): {
+     *                 String: BinaryData (Required)
+     *             }
+     *         }
+     *     ]
+     * }
+     * }
+     * 
+ * + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     value (Required): [
+     *          (Required){
+     *             key: String (Required)
+     *             errorMessage: String (Optional)
+     *             status: boolean (Required)
+     *             statusCode: int (Required)
+     *         }
+     *     ]
+     * }
+     * }
+     * 
+ * + * @param indexName The name of the index. + * @param batch The batch of index actions. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return response containing the status of operations for all documents in the indexing + * request along with {@link Response}. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public Response indexWithResponse(String indexName, BinaryData batch, RequestOptions requestOptions) { + return this.serviceClient.indexWithResponse(indexName, batch, requestOptions); + } + + /** + * Autocompletes incomplete query terms based on input text and matching terms in + * the index. + *

Query Parameters

+ * + * + * + * + * + * + * + * + * + * + * + *
Query Parameters
NameTypeRequiredDescription
autocompleteModeStringNoSpecifies 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. Allowed values: "oneTerm", "twoTerms", "oneTermWithContext".
$filterStringNoAn OData expression that filters the documents used to produce + * completed terms + * for the Autocomplete result.
fuzzyBooleanNoA 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.
highlightPostTagStringNoA string tag that is appended to hit highlights. Must + * be set with + * highlightPreTag. If omitted, hit highlighting is disabled.
highlightPreTagStringNoA string tag that is prepended to hit highlights. Must + * be set with + * highlightPostTag. If omitted, hit highlighting is disabled.
minimumCoverageDoubleNoA 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.
searchFieldsList<String>NoThe list of field names to consider when + * querying for auto-completed terms. + * Target fields must be included in the specified suggester. In the form of "," separated string.
$topIntegerNoThe number of auto-completed terms to retrieve. This must be a + * value between 1 + * and 100. The default is 5.
+ * You can add these to a request with {@link RequestOptions#addQueryParam} + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     @search.coverage: Double (Optional)
+     *     value (Required): [
+     *          (Required){
+     *             text: String (Required)
+     *             queryPlusText: String (Required)
+     *         }
+     *     ]
+     * }
+     * }
+     * 
+ * + * @param searchText The incomplete term which should be auto-completed. + * @param suggesterName The name of the suggester as specified in the suggesters collection that's part + * of the index definition. + * @param indexName The name of the index. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return the result of Autocomplete query along with {@link Response}. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public Response autocompleteGetWithResponse(String searchText, String suggesterName, String indexName, + RequestOptions requestOptions) { + return this.serviceClient.autocompleteGetWithResponse(searchText, suggesterName, indexName, requestOptions); + } + + /** + * Autocompletes incomplete query terms based on input text and matching terms in + * the index. + *

Request Body Schema

+ * + *
+     * {@code
+     * {
+     *     search: String (Required)
+     *     autocompleteMode: String(oneTerm/twoTerms/oneTermWithContext) (Optional)
+     *     filter: String (Optional)
+     *     fuzzy: Boolean (Optional)
+     *     highlightPostTag: String (Optional)
+     *     highlightPreTag: String (Optional)
+     *     minimumCoverage: Double (Optional)
+     *     searchFields: String (Optional)
+     *     suggesterName: String (Required)
+     *     top: Integer (Optional)
+     * }
+     * }
+     * 
+ * + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     @search.coverage: Double (Optional)
+     *     value (Required): [
+     *          (Required){
+     *             text: String (Required)
+     *             queryPlusText: String (Required)
+     *         }
+     *     ]
+     * }
+     * }
+     * 
+ * + * @param indexName The name of the index. + * @param autocompleteRequest The definition of the Autocomplete request. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return the result of Autocomplete query along with {@link Response}. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public Response autocompletePostWithResponse(String indexName, BinaryData autocompleteRequest, + RequestOptions requestOptions) { + return this.serviceClient.autocompletePostWithResponse(indexName, autocompleteRequest, requestOptions); + } + + /** + * Queries the number of documents in the index. + * + * @param indexName The name of the index. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a 32-bit integer. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public int count(String indexName) { + // Generated convenience method for countWithResponse + RequestOptions requestOptions = new RequestOptions(); + return countWithResponse(indexName, requestOptions).getValue().toString(); + } + + /** + * Searches for documents in the index. + * + * @param indexName The name of the index. + * @param searchText A full-text search query expression; Use "*" or omit this parameter to match + * all documents. + * @param includeTotalResultCount 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. + * @param 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. + * @param filter The OData $filter expression to apply to the search query. + * @param highlightFields The list of field names to use for hit highlights. Only searchable fields can + * be used for hit highlighting. + * @param highlightPostTag A string tag that is appended to hit highlights. Must be set with + * highlightPreTag. Default is &lt;/em&gt;. + * @param highlightPreTag A string tag that is prepended to hit highlights. Must be set with + * highlightPostTag. Default is &lt;em&gt;. + * @param minimumCoverage 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. + * @param orderBy 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. + * @param queryType A value that specifies the syntax of the search query. The default is 'simple'. + * Use 'full' if your query uses the Lucene query syntax. + * @param scoringParameters 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). + * @param scoringProfile The name of a scoring profile to evaluate match scores for matching documents + * in order to sort the results. + * @param searchFields 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. + * @param searchMode A value that specifies whether any or all of the search terms must be matched + * in order to count the document as a match. + * @param scoringStatistics 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. + * @param sessionId 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. + * @param select The list of fields to retrieve. If unspecified, all fields marked as + * retrievable in the schema are included. + * @param 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. + * @param 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. + * @param semanticConfiguration The name of the semantic configuration that lists which fields should be used + * for semantic ranking, captions, highlights, and answers. + * @param semanticErrorHandling Allows the user to choose whether a semantic call should fail completely, or to + * return partial results (default). + * @param semanticMaxWaitInMilliseconds 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. + * @param 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-<number of answers>` 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-<confidence 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-<number of maximum character length>', + * such as 'extractive|maxcharlength-600'. + * @param 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-<true/false>` 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-<number of maximum + * character length>', such as 'extractive|maxcharlength-600'. + * @param semanticQuery 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. + * @param queryRewrites 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-<number of rewrites>` option, such as + * `generative|count-3`. Defaults to `None`. This parameter is only valid if the + * query type is `semantic`. + * @param debug Enables a debugging tool that can be used to further explore your search + * results. + * @param queryLanguage The language of the query. + * @param speller Improve search recall by spell-correcting individual search query terms. + * @param semanticFields The list of field names used for semantic ranking. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return response containing search results from an index. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public SearchDocumentsResult searchGet(String indexName, String searchText, Boolean includeTotalResultCount, + List facets, String filter, List highlightFields, String highlightPostTag, + String highlightPreTag, Double minimumCoverage, List orderBy, QueryType queryType, + List scoringParameters, String scoringProfile, List searchFields, SearchMode searchMode, + ScoringStatistics scoringStatistics, String sessionId, List select, Integer skip, Integer top, + String semanticConfiguration, SemanticErrorMode semanticErrorHandling, Integer semanticMaxWaitInMilliseconds, + QueryAnswerType answers, QueryCaptionType captions, String semanticQuery, QueryRewritesType queryRewrites, + QueryDebugMode debug, QueryLanguage queryLanguage, QuerySpellerType speller, List semanticFields) { + // Generated convenience method for searchGetWithResponse + RequestOptions requestOptions = new RequestOptions(); + if (searchText != null) { + requestOptions.addQueryParam("search", searchText, false); + } + if (includeTotalResultCount != null) { + requestOptions.addQueryParam("$count", String.valueOf(includeTotalResultCount), false); + } + if (facets != null) { + for (String paramItemValue : facets) { + if (paramItemValue != null) { + requestOptions.addQueryParam("facet", paramItemValue, false); + } + } + } + if (filter != null) { + requestOptions.addQueryParam("$filter", filter, false); + } + if (highlightFields != null) { + requestOptions.addQueryParam("highlight", + highlightFields.stream() + .map(paramItemValue -> Objects.toString(paramItemValue, "")) + .collect(Collectors.joining(",")), + false); + } + if (highlightPostTag != null) { + requestOptions.addQueryParam("highlightPostTag", highlightPostTag, false); + } + if (highlightPreTag != null) { + requestOptions.addQueryParam("highlightPreTag", highlightPreTag, false); + } + if (minimumCoverage != null) { + requestOptions.addQueryParam("minimumCoverage", String.valueOf(minimumCoverage), false); + } + if (orderBy != null) { + requestOptions.addQueryParam("$orderby", + orderBy.stream() + .map(paramItemValue -> Objects.toString(paramItemValue, "")) + .collect(Collectors.joining(",")), + false); + } + if (queryType != null) { + requestOptions.addQueryParam("queryType", queryType.toString(), false); + } + if (scoringParameters != null) { + for (String paramItemValue : scoringParameters) { + if (paramItemValue != null) { + requestOptions.addQueryParam("scoringParameter", paramItemValue, false); + } + } + } + if (scoringProfile != null) { + requestOptions.addQueryParam("scoringProfile", scoringProfile, false); + } + if (searchFields != null) { + requestOptions.addQueryParam("searchFields", + searchFields.stream() + .map(paramItemValue -> Objects.toString(paramItemValue, "")) + .collect(Collectors.joining(",")), + false); + } + if (searchMode != null) { + requestOptions.addQueryParam("searchMode", searchMode.toString(), false); + } + if (scoringStatistics != null) { + requestOptions.addQueryParam("scoringStatistics", scoringStatistics.toString(), false); + } + if (sessionId != null) { + requestOptions.addQueryParam("sessionId", sessionId, false); + } + if (select != null) { + requestOptions.addQueryParam("$select", + select.stream() + .map(paramItemValue -> Objects.toString(paramItemValue, "")) + .collect(Collectors.joining(",")), + false); + } + if (skip != null) { + requestOptions.addQueryParam("$skip", String.valueOf(skip), false); + } + if (top != null) { + requestOptions.addQueryParam("$top", String.valueOf(top), false); + } + if (semanticConfiguration != null) { + requestOptions.addQueryParam("semanticConfiguration", semanticConfiguration, false); + } + if (semanticErrorHandling != null) { + requestOptions.addQueryParam("semanticErrorHandling", semanticErrorHandling.toString(), false); + } + if (semanticMaxWaitInMilliseconds != null) { + requestOptions.addQueryParam("semanticMaxWaitInMilliseconds", String.valueOf(semanticMaxWaitInMilliseconds), + false); + } + if (answers != null) { + requestOptions.addQueryParam("answers", answers.toString(), false); + } + if (captions != null) { + requestOptions.addQueryParam("captions", captions.toString(), false); + } + if (semanticQuery != null) { + requestOptions.addQueryParam("semanticQuery", semanticQuery, false); + } + if (queryRewrites != null) { + requestOptions.addQueryParam("queryRewrites", queryRewrites.toString(), false); + } + if (debug != null) { + requestOptions.addQueryParam("debug", debug.toString(), false); + } + if (queryLanguage != null) { + requestOptions.addQueryParam("queryLanguage", queryLanguage.toString(), false); + } + if (speller != null) { + requestOptions.addQueryParam("speller", speller.toString(), false); + } + if (semanticFields != null) { + requestOptions.addQueryParam("semanticFields", + semanticFields.stream() + .map(paramItemValue -> Objects.toString(paramItemValue, "")) + .collect(Collectors.joining(",")), + false); + } + return searchGetWithResponse(indexName, requestOptions).getValue().toObject(SearchDocumentsResult.class); + } + + /** + * Searches for documents in the index. + * + * @param indexName The name of the index. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return response containing search results from an index. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public SearchDocumentsResult searchGet(String indexName) { + // Generated convenience method for searchGetWithResponse + RequestOptions requestOptions = new RequestOptions(); + return searchGetWithResponse(indexName, requestOptions).getValue().toObject(SearchDocumentsResult.class); + } + + /** + * Searches for documents in the index. + * + * @param indexName The name of the index. + * @param searchRequest The definition of the Search request. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return response containing search results from an index. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public SearchDocumentsResult searchPost(String indexName, SearchRequest searchRequest) { + // Generated convenience method for searchPostWithResponse + RequestOptions requestOptions = new RequestOptions(); + return searchPostWithResponse(indexName, BinaryData.fromObject(searchRequest), requestOptions).getValue() + .toObject(SearchDocumentsResult.class); + } + + /** + * Retrieves a document from the index. + * + * @param key The key of the document to retrieve. + * @param indexName The name of the index. + * @param selectedFields List of field names to retrieve for the document; Any field not retrieved will + * be missing from the returned document. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a document retrieved via a document lookup operation. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public LookupDocument get(String key, String indexName, List selectedFields) { + // Generated convenience method for getWithResponse + RequestOptions requestOptions = new RequestOptions(); + if (selectedFields != null) { + requestOptions.addQueryParam("$select", + selectedFields.stream() + .map(paramItemValue -> Objects.toString(paramItemValue, "")) + .collect(Collectors.joining(",")), + false); + } + return getWithResponse(key, indexName, requestOptions).getValue().toObject(LookupDocument.class); + } + + /** + * Retrieves a document from the index. + * + * @param key The key of the document to retrieve. + * @param indexName The name of the index. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a document retrieved via a document lookup operation. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public LookupDocument get(String key, String indexName) { + // Generated convenience method for getWithResponse + RequestOptions requestOptions = new RequestOptions(); + return getWithResponse(key, indexName, requestOptions).getValue().toObject(LookupDocument.class); + } + + /** + * Suggests documents in the index that match the given partial query text. + * + * @param searchText The search text to use to suggest documents. Must be at least 1 character, and + * no more than 100 characters. + * @param suggesterName The name of the suggester as specified in the suggesters collection that's part + * of the index definition. + * @param indexName The name of the index. + * @param filter An OData expression that filters the documents considered for suggestions. + * @param useFuzzyMatching 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. + * @param highlightPostTag A string tag that is appended to hit highlights. Must be set with + * highlightPreTag. If omitted, hit highlighting of suggestions is disabled. + * @param highlightPreTag A string tag that is prepended to hit highlights. Must be set with + * highlightPostTag. If omitted, hit highlighting of suggestions is disabled. + * @param minimumCoverage 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. + * @param orderBy 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. + * @param searchFields The list of field names to search for the specified search text. Target fields + * must be included in the specified suggester. + * @param select The list of fields to retrieve. If unspecified, only the key field will be + * included in the results. + * @param top The number of suggestions to retrieve. The value must be a number between 1 and + * 100. The default is 5. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return response containing suggestion query results from an index. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public SuggestDocumentsResult suggestGet(String searchText, String suggesterName, String indexName, String filter, + Boolean useFuzzyMatching, String highlightPostTag, String highlightPreTag, Double minimumCoverage, + List orderBy, List searchFields, List select, Integer top) { + // Generated convenience method for suggestGetWithResponse + RequestOptions requestOptions = new RequestOptions(); + if (filter != null) { + requestOptions.addQueryParam("$filter", filter, false); + } + if (useFuzzyMatching != null) { + requestOptions.addQueryParam("fuzzy", String.valueOf(useFuzzyMatching), false); + } + if (highlightPostTag != null) { + requestOptions.addQueryParam("highlightPostTag", highlightPostTag, false); + } + if (highlightPreTag != null) { + requestOptions.addQueryParam("highlightPreTag", highlightPreTag, false); + } + if (minimumCoverage != null) { + requestOptions.addQueryParam("minimumCoverage", String.valueOf(minimumCoverage), false); + } + if (orderBy != null) { + requestOptions.addQueryParam("$orderby", + orderBy.stream() + .map(paramItemValue -> Objects.toString(paramItemValue, "")) + .collect(Collectors.joining(",")), + false); + } + if (searchFields != null) { + requestOptions.addQueryParam("searchFields", + searchFields.stream() + .map(paramItemValue -> Objects.toString(paramItemValue, "")) + .collect(Collectors.joining(",")), + false); + } + if (select != null) { + requestOptions.addQueryParam("$select", + select.stream() + .map(paramItemValue -> Objects.toString(paramItemValue, "")) + .collect(Collectors.joining(",")), + false); + } + if (top != null) { + requestOptions.addQueryParam("$top", String.valueOf(top), false); + } + return suggestGetWithResponse(searchText, suggesterName, indexName, requestOptions).getValue() + .toObject(SuggestDocumentsResult.class); + } + + /** + * Suggests documents in the index that match the given partial query text. + * + * @param searchText The search text to use to suggest documents. Must be at least 1 character, and + * no more than 100 characters. + * @param suggesterName The name of the suggester as specified in the suggesters collection that's part + * of the index definition. + * @param indexName The name of the index. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return response containing suggestion query results from an index. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public SuggestDocumentsResult suggestGet(String searchText, String suggesterName, String indexName) { + // Generated convenience method for suggestGetWithResponse + RequestOptions requestOptions = new RequestOptions(); + return suggestGetWithResponse(searchText, suggesterName, indexName, requestOptions).getValue() + .toObject(SuggestDocumentsResult.class); + } + + /** + * Suggests documents in the index that match the given partial query text. + * + * @param indexName The name of the index. + * @param suggestRequest The Suggest request. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return response containing suggestion query results from an index. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public SuggestDocumentsResult suggestPost(String indexName, SuggestRequest suggestRequest) { + // Generated convenience method for suggestPostWithResponse + RequestOptions requestOptions = new RequestOptions(); + return suggestPostWithResponse(indexName, BinaryData.fromObject(suggestRequest), requestOptions).getValue() + .toObject(SuggestDocumentsResult.class); + } + + /** + * Sends a batch of document write actions to the index. + * + * @param indexName The name of the index. + * @param batch The batch of index actions. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return response containing the status of operations for all documents in the indexing + * request. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public IndexDocumentsResult index(String indexName, IndexBatch batch) { + // Generated convenience method for indexWithResponse + RequestOptions requestOptions = new RequestOptions(); + return indexWithResponse(indexName, BinaryData.fromObject(batch), requestOptions).getValue() + .toObject(IndexDocumentsResult.class); + } + + /** + * Autocompletes incomplete query terms based on input text and matching terms in + * the index. + * + * @param searchText The incomplete term which should be auto-completed. + * @param suggesterName The name of the suggester as specified in the suggesters collection that's part + * of the index definition. + * @param indexName The name of the index. + * @param autocompleteMode 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. + * @param filter An OData expression that filters the documents used to produce completed terms + * for the Autocomplete result. + * @param useFuzzyMatching 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. + * @param highlightPostTag A string tag that is appended to hit highlights. Must be set with + * highlightPreTag. If omitted, hit highlighting is disabled. + * @param highlightPreTag A string tag that is prepended to hit highlights. Must be set with + * highlightPostTag. If omitted, hit highlighting is disabled. + * @param minimumCoverage 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. + * @param searchFields The list of field names to consider when querying for auto-completed terms. + * Target fields must be included in the specified suggester. + * @param top The number of auto-completed terms to retrieve. This must be a value between 1 + * and 100. The default is 5. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the result of Autocomplete query. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public AutocompleteResult autocompleteGet(String searchText, String suggesterName, String indexName, + AutocompleteMode autocompleteMode, String filter, Boolean useFuzzyMatching, String highlightPostTag, + String highlightPreTag, Double minimumCoverage, List searchFields, Integer top) { + // Generated convenience method for autocompleteGetWithResponse + RequestOptions requestOptions = new RequestOptions(); + if (autocompleteMode != null) { + requestOptions.addQueryParam("autocompleteMode", autocompleteMode.toString(), false); + } + if (filter != null) { + requestOptions.addQueryParam("$filter", filter, false); + } + if (useFuzzyMatching != null) { + requestOptions.addQueryParam("fuzzy", String.valueOf(useFuzzyMatching), false); + } + if (highlightPostTag != null) { + requestOptions.addQueryParam("highlightPostTag", highlightPostTag, false); + } + if (highlightPreTag != null) { + requestOptions.addQueryParam("highlightPreTag", highlightPreTag, false); + } + if (minimumCoverage != null) { + requestOptions.addQueryParam("minimumCoverage", String.valueOf(minimumCoverage), false); + } + if (searchFields != null) { + requestOptions.addQueryParam("searchFields", + searchFields.stream() + .map(paramItemValue -> Objects.toString(paramItemValue, "")) + .collect(Collectors.joining(",")), + false); + } + if (top != null) { + requestOptions.addQueryParam("$top", String.valueOf(top), false); + } + return autocompleteGetWithResponse(searchText, suggesterName, indexName, requestOptions).getValue() + .toObject(AutocompleteResult.class); + } + + /** + * Autocompletes incomplete query terms based on input text and matching terms in + * the index. + * + * @param searchText The incomplete term which should be auto-completed. + * @param suggesterName The name of the suggester as specified in the suggesters collection that's part + * of the index definition. + * @param indexName The name of the index. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the result of Autocomplete query. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public AutocompleteResult autocompleteGet(String searchText, String suggesterName, String indexName) { + // Generated convenience method for autocompleteGetWithResponse + RequestOptions requestOptions = new RequestOptions(); + return autocompleteGetWithResponse(searchText, suggesterName, indexName, requestOptions).getValue() + .toObject(AutocompleteResult.class); + } + + /** + * Autocompletes incomplete query terms based on input text and matching terms in + * the index. + * + * @param indexName The name of the index. + * @param autocompleteRequest The definition of the Autocomplete request. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the result of Autocomplete query. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public AutocompleteResult autocompletePost(String indexName, AutocompleteRequest autocompleteRequest) { + // Generated convenience method for autocompletePostWithResponse + RequestOptions requestOptions = new RequestOptions(); + return autocompletePostWithResponse(indexName, BinaryData.fromObject(autocompleteRequest), requestOptions) + .getValue() + .toObject(AutocompleteResult.class); + } +} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/IndexersAsyncClient.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/IndexersAsyncClient.java new file mode 100644 index 000000000000..afda436f6e17 --- /dev/null +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/IndexersAsyncClient.java @@ -0,0 +1,1132 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.search.documents; + +import com.azure.core.annotation.Generated; +import com.azure.core.annotation.ReturnType; +import com.azure.core.annotation.ServiceClient; +import com.azure.core.annotation.ServiceMethod; +import com.azure.core.exception.ClientAuthenticationException; +import com.azure.core.exception.HttpResponseException; +import com.azure.core.exception.ResourceModifiedException; +import com.azure.core.exception.ResourceNotFoundException; +import com.azure.core.http.HttpHeaderName; +import com.azure.core.http.MatchConditions; +import com.azure.core.http.rest.RequestOptions; +import com.azure.core.http.rest.Response; +import com.azure.core.util.BinaryData; +import com.azure.core.util.FluxUtil; +import com.azure.search.documents.implementation.IndexersImpl; +import com.azure.search.documents.models.DocumentKeysOrIds; +import com.azure.search.documents.models.ListIndexersResult; +import com.azure.search.documents.models.SearchIndexer; +import com.azure.search.documents.models.SearchIndexerStatus; +import reactor.core.publisher.Mono; + +/** + * Initializes a new instance of the asynchronous SearchClient type. + */ +@ServiceClient(builder = SearchClientBuilder.class, isAsync = true) +public final class IndexersAsyncClient { + @Generated + private final IndexersImpl serviceClient; + + /** + * Initializes an instance of IndexersAsyncClient class. + * + * @param serviceClient the service client implementation. + */ + @Generated + IndexersAsyncClient(IndexersImpl serviceClient) { + this.serviceClient = serviceClient; + } + + /** + * Resets the change tracking state associated with an indexer. + * + * @param indexerName The name of the indexer. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return the {@link Response} on successful completion of {@link Mono}. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono> resetWithResponse(String indexerName, RequestOptions requestOptions) { + return this.serviceClient.resetWithResponseAsync(indexerName, requestOptions); + } + + /** + * Resets specific documents in the datasource to be selectively re-ingested by + * the indexer. + *

Query Parameters

+ * + * + * + * + *
Query Parameters
NameTypeRequiredDescription
overwriteBooleanNoIf 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.
+ * You can add these to a request with {@link RequestOptions#addQueryParam} + *

Header Parameters

+ * + * + * + * + *
Header Parameters
NameTypeRequiredDescription
Content-TypeStringNoThe content type. Allowed values: + * "application/json".
+ * You can add these to a request with {@link RequestOptions#addHeader} + *

Request Body Schema

+ * + *
+     * {@code
+     * {
+     *     documentKeys (Optional): [
+     *         String (Optional)
+     *     ]
+     *     datasourceDocumentIds (Optional): [
+     *         String (Optional)
+     *     ]
+     * }
+     * }
+     * 
+ * + * @param indexerName The name of the indexer. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return the {@link Response} on successful completion of {@link Mono}. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono> resetDocsWithResponse(String indexerName, RequestOptions requestOptions) { + return this.serviceClient.resetDocsWithResponseAsync(indexerName, requestOptions); + } + + /** + * Runs an indexer on-demand. + * + * @param indexerName The name of the indexer. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return the {@link Response} on successful completion of {@link Mono}. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono> runWithResponse(String indexerName, RequestOptions requestOptions) { + return this.serviceClient.runWithResponseAsync(indexerName, requestOptions); + } + + /** + * Creates a new indexer or updates an indexer if it already exists. + *

Query Parameters

+ * + * + * + * + * + *
Query Parameters
NameTypeRequiredDescription
ignoreResetRequirementsBooleanNoIgnores cache reset requirements.
disableCacheReprocessingChangeDetectionBooleanNoDisables cache reprocessing + * change detection.
+ * You can add these to a request with {@link RequestOptions#addQueryParam} + *

Header Parameters

+ * + * + * + * + * + *
Header Parameters
NameTypeRequiredDescription
If-MatchStringNoDefines the If-Match condition. The operation will be + * performed only if the ETag on the server matches this value.
If-None-MatchStringNoDefines the If-None-Match condition. The operation will + * be performed only if the ETag on the server does not match this value.
+ * You can add these to a request with {@link RequestOptions#addHeader} + *

Request Body Schema

+ * + *
+     * {@code
+     * {
+     *     name: String (Required)
+     *     description: String (Optional)
+     *     dataSourceName: String (Required)
+     *     skillsetName: String (Optional)
+     *     targetIndexName: String (Required)
+     *     schedule (Optional): {
+     *         interval: Duration (Required)
+     *         startTime: OffsetDateTime (Optional)
+     *     }
+     *     parameters (Optional): {
+     *         batchSize: Integer (Optional)
+     *         maxFailedItems: Integer (Optional)
+     *         maxFailedItemsPerBatch: Integer (Optional)
+     *         configuration (Optional): {
+     *             parsingMode: String(default/text/delimitedText/json/jsonArray/jsonLines/markdown) (Optional)
+     *             excludedFileNameExtensions: String (Optional)
+     *             indexedFileNameExtensions: String (Optional)
+     *             failOnUnsupportedContentType: Boolean (Optional)
+     *             failOnUnprocessableDocument: Boolean (Optional)
+     *             indexStorageMetadataOnlyForOversizedDocuments: Boolean (Optional)
+     *             delimitedTextHeaders: String (Optional)
+     *             delimitedTextDelimiter: String (Optional)
+     *             firstLineContainsHeaders: Boolean (Optional)
+     *             markdownParsingSubmode: String(oneToMany/oneToOne) (Optional)
+     *             markdownHeaderDepth: String(h1/h2/h3/h4/h5/h6) (Optional)
+     *             documentRoot: String (Optional)
+     *             dataToExtract: String(storageMetadata/allMetadata/contentAndMetadata) (Optional)
+     *             imageAction: String(none/generateNormalizedImages/generateNormalizedImagePerPage) (Optional)
+     *             allowSkillsetToReadFileData: Boolean (Optional)
+     *             pdfTextRotationAlgorithm: String(none/detectAngles) (Optional)
+     *             executionEnvironment: String(standard/private) (Optional)
+     *             queryTimeout: String (Optional)
+     *              (Optional): {
+     *                 String: BinaryData (Required)
+     *             }
+     *         }
+     *     }
+     *     fieldMappings (Optional): [
+     *          (Optional){
+     *             sourceFieldName: String (Required)
+     *             targetFieldName: String (Optional)
+     *             mappingFunction (Optional): {
+     *                 name: String (Required)
+     *                 parameters (Optional): {
+     *                     String: BinaryData (Required)
+     *                 }
+     *             }
+     *         }
+     *     ]
+     *     outputFieldMappings (Optional): [
+     *         (recursive schema, see above)
+     *     ]
+     *     disabled: Boolean (Optional)
+     *     @odata.etag: String (Optional)
+     *     encryptionKey (Optional): {
+     *         keyVaultKeyName: String (Required)
+     *         keyVaultKeyVersion: String (Optional)
+     *         keyVaultUri: String (Required)
+     *         accessCredentials (Optional): {
+     *             applicationId: String (Required)
+     *             applicationSecret: String (Optional)
+     *         }
+     *         identity (Optional): {
+     *             @odata.type: String (Required)
+     *         }
+     *     }
+     *     cache (Optional): {
+     *         storageConnectionString: String (Optional)
+     *         enableReprocessing: Boolean (Optional)
+     *         identity (Optional): (recursive schema, see identity above)
+     *         id: String (Optional)
+     *     }
+     * }
+     * }
+     * 
+ * + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     name: String (Required)
+     *     description: String (Optional)
+     *     dataSourceName: String (Required)
+     *     skillsetName: String (Optional)
+     *     targetIndexName: String (Required)
+     *     schedule (Optional): {
+     *         interval: Duration (Required)
+     *         startTime: OffsetDateTime (Optional)
+     *     }
+     *     parameters (Optional): {
+     *         batchSize: Integer (Optional)
+     *         maxFailedItems: Integer (Optional)
+     *         maxFailedItemsPerBatch: Integer (Optional)
+     *         configuration (Optional): {
+     *             parsingMode: String(default/text/delimitedText/json/jsonArray/jsonLines/markdown) (Optional)
+     *             excludedFileNameExtensions: String (Optional)
+     *             indexedFileNameExtensions: String (Optional)
+     *             failOnUnsupportedContentType: Boolean (Optional)
+     *             failOnUnprocessableDocument: Boolean (Optional)
+     *             indexStorageMetadataOnlyForOversizedDocuments: Boolean (Optional)
+     *             delimitedTextHeaders: String (Optional)
+     *             delimitedTextDelimiter: String (Optional)
+     *             firstLineContainsHeaders: Boolean (Optional)
+     *             markdownParsingSubmode: String(oneToMany/oneToOne) (Optional)
+     *             markdownHeaderDepth: String(h1/h2/h3/h4/h5/h6) (Optional)
+     *             documentRoot: String (Optional)
+     *             dataToExtract: String(storageMetadata/allMetadata/contentAndMetadata) (Optional)
+     *             imageAction: String(none/generateNormalizedImages/generateNormalizedImagePerPage) (Optional)
+     *             allowSkillsetToReadFileData: Boolean (Optional)
+     *             pdfTextRotationAlgorithm: String(none/detectAngles) (Optional)
+     *             executionEnvironment: String(standard/private) (Optional)
+     *             queryTimeout: String (Optional)
+     *              (Optional): {
+     *                 String: BinaryData (Required)
+     *             }
+     *         }
+     *     }
+     *     fieldMappings (Optional): [
+     *          (Optional){
+     *             sourceFieldName: String (Required)
+     *             targetFieldName: String (Optional)
+     *             mappingFunction (Optional): {
+     *                 name: String (Required)
+     *                 parameters (Optional): {
+     *                     String: BinaryData (Required)
+     *                 }
+     *             }
+     *         }
+     *     ]
+     *     outputFieldMappings (Optional): [
+     *         (recursive schema, see above)
+     *     ]
+     *     disabled: Boolean (Optional)
+     *     @odata.etag: String (Optional)
+     *     encryptionKey (Optional): {
+     *         keyVaultKeyName: String (Required)
+     *         keyVaultKeyVersion: String (Optional)
+     *         keyVaultUri: String (Required)
+     *         accessCredentials (Optional): {
+     *             applicationId: String (Required)
+     *             applicationSecret: String (Optional)
+     *         }
+     *         identity (Optional): {
+     *             @odata.type: String (Required)
+     *         }
+     *     }
+     *     cache (Optional): {
+     *         storageConnectionString: String (Optional)
+     *         enableReprocessing: Boolean (Optional)
+     *         identity (Optional): (recursive schema, see identity above)
+     *         id: String (Optional)
+     *     }
+     * }
+     * }
+     * 
+ * + * @param indexerName The name of the indexer. + * @param indexer The definition of the indexer to create or update. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return represents an indexer along with {@link Response} on successful completion of {@link Mono}. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono> createOrUpdateWithResponse(String indexerName, BinaryData indexer, + RequestOptions requestOptions) { + return this.serviceClient.createOrUpdateWithResponseAsync(indexerName, indexer, requestOptions); + } + + /** + * Deletes an indexer. + *

Header Parameters

+ * + * + * + * + * + *
Header Parameters
NameTypeRequiredDescription
If-MatchStringNoDefines the If-Match condition. The operation will be + * performed only if the ETag on the server matches this value.
If-None-MatchStringNoDefines the If-None-Match condition. The operation will + * be performed only if the ETag on the server does not match this value.
+ * You can add these to a request with {@link RequestOptions#addHeader} + * + * @param indexerName The name of the indexer. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return the {@link Response} on successful completion of {@link Mono}. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono> deleteWithResponse(String indexerName, RequestOptions requestOptions) { + return this.serviceClient.deleteWithResponseAsync(indexerName, requestOptions); + } + + /** + * Retrieves an indexer definition. + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     name: String (Required)
+     *     description: String (Optional)
+     *     dataSourceName: String (Required)
+     *     skillsetName: String (Optional)
+     *     targetIndexName: String (Required)
+     *     schedule (Optional): {
+     *         interval: Duration (Required)
+     *         startTime: OffsetDateTime (Optional)
+     *     }
+     *     parameters (Optional): {
+     *         batchSize: Integer (Optional)
+     *         maxFailedItems: Integer (Optional)
+     *         maxFailedItemsPerBatch: Integer (Optional)
+     *         configuration (Optional): {
+     *             parsingMode: String(default/text/delimitedText/json/jsonArray/jsonLines/markdown) (Optional)
+     *             excludedFileNameExtensions: String (Optional)
+     *             indexedFileNameExtensions: String (Optional)
+     *             failOnUnsupportedContentType: Boolean (Optional)
+     *             failOnUnprocessableDocument: Boolean (Optional)
+     *             indexStorageMetadataOnlyForOversizedDocuments: Boolean (Optional)
+     *             delimitedTextHeaders: String (Optional)
+     *             delimitedTextDelimiter: String (Optional)
+     *             firstLineContainsHeaders: Boolean (Optional)
+     *             markdownParsingSubmode: String(oneToMany/oneToOne) (Optional)
+     *             markdownHeaderDepth: String(h1/h2/h3/h4/h5/h6) (Optional)
+     *             documentRoot: String (Optional)
+     *             dataToExtract: String(storageMetadata/allMetadata/contentAndMetadata) (Optional)
+     *             imageAction: String(none/generateNormalizedImages/generateNormalizedImagePerPage) (Optional)
+     *             allowSkillsetToReadFileData: Boolean (Optional)
+     *             pdfTextRotationAlgorithm: String(none/detectAngles) (Optional)
+     *             executionEnvironment: String(standard/private) (Optional)
+     *             queryTimeout: String (Optional)
+     *              (Optional): {
+     *                 String: BinaryData (Required)
+     *             }
+     *         }
+     *     }
+     *     fieldMappings (Optional): [
+     *          (Optional){
+     *             sourceFieldName: String (Required)
+     *             targetFieldName: String (Optional)
+     *             mappingFunction (Optional): {
+     *                 name: String (Required)
+     *                 parameters (Optional): {
+     *                     String: BinaryData (Required)
+     *                 }
+     *             }
+     *         }
+     *     ]
+     *     outputFieldMappings (Optional): [
+     *         (recursive schema, see above)
+     *     ]
+     *     disabled: Boolean (Optional)
+     *     @odata.etag: String (Optional)
+     *     encryptionKey (Optional): {
+     *         keyVaultKeyName: String (Required)
+     *         keyVaultKeyVersion: String (Optional)
+     *         keyVaultUri: String (Required)
+     *         accessCredentials (Optional): {
+     *             applicationId: String (Required)
+     *             applicationSecret: String (Optional)
+     *         }
+     *         identity (Optional): {
+     *             @odata.type: String (Required)
+     *         }
+     *     }
+     *     cache (Optional): {
+     *         storageConnectionString: String (Optional)
+     *         enableReprocessing: Boolean (Optional)
+     *         identity (Optional): (recursive schema, see identity above)
+     *         id: String (Optional)
+     *     }
+     * }
+     * }
+     * 
+ * + * @param indexerName The name of the indexer. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return represents an indexer along with {@link Response} on successful completion of {@link Mono}. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono> getWithResponse(String indexerName, RequestOptions requestOptions) { + return this.serviceClient.getWithResponseAsync(indexerName, requestOptions); + } + + /** + * Lists all indexers available for a search service. + *

Query Parameters

+ * + * + * + * + *
Query Parameters
NameTypeRequiredDescription
$selectStringNoSelects 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.
+ * You can add these to a request with {@link RequestOptions#addQueryParam} + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     value (Required): [
+     *          (Required){
+     *             name: String (Required)
+     *             description: String (Optional)
+     *             dataSourceName: String (Required)
+     *             skillsetName: String (Optional)
+     *             targetIndexName: String (Required)
+     *             schedule (Optional): {
+     *                 interval: Duration (Required)
+     *                 startTime: OffsetDateTime (Optional)
+     *             }
+     *             parameters (Optional): {
+     *                 batchSize: Integer (Optional)
+     *                 maxFailedItems: Integer (Optional)
+     *                 maxFailedItemsPerBatch: Integer (Optional)
+     *                 configuration (Optional): {
+     *                     parsingMode: String(default/text/delimitedText/json/jsonArray/jsonLines/markdown) (Optional)
+     *                     excludedFileNameExtensions: String (Optional)
+     *                     indexedFileNameExtensions: String (Optional)
+     *                     failOnUnsupportedContentType: Boolean (Optional)
+     *                     failOnUnprocessableDocument: Boolean (Optional)
+     *                     indexStorageMetadataOnlyForOversizedDocuments: Boolean (Optional)
+     *                     delimitedTextHeaders: String (Optional)
+     *                     delimitedTextDelimiter: String (Optional)
+     *                     firstLineContainsHeaders: Boolean (Optional)
+     *                     markdownParsingSubmode: String(oneToMany/oneToOne) (Optional)
+     *                     markdownHeaderDepth: String(h1/h2/h3/h4/h5/h6) (Optional)
+     *                     documentRoot: String (Optional)
+     *                     dataToExtract: String(storageMetadata/allMetadata/contentAndMetadata) (Optional)
+     *                     imageAction: String(none/generateNormalizedImages/generateNormalizedImagePerPage) (Optional)
+     *                     allowSkillsetToReadFileData: Boolean (Optional)
+     *                     pdfTextRotationAlgorithm: String(none/detectAngles) (Optional)
+     *                     executionEnvironment: String(standard/private) (Optional)
+     *                     queryTimeout: String (Optional)
+     *                      (Optional): {
+     *                         String: BinaryData (Required)
+     *                     }
+     *                 }
+     *             }
+     *             fieldMappings (Optional): [
+     *                  (Optional){
+     *                     sourceFieldName: String (Required)
+     *                     targetFieldName: String (Optional)
+     *                     mappingFunction (Optional): {
+     *                         name: String (Required)
+     *                         parameters (Optional): {
+     *                             String: BinaryData (Required)
+     *                         }
+     *                     }
+     *                 }
+     *             ]
+     *             outputFieldMappings (Optional): [
+     *                 (recursive schema, see above)
+     *             ]
+     *             disabled: Boolean (Optional)
+     *             @odata.etag: String (Optional)
+     *             encryptionKey (Optional): {
+     *                 keyVaultKeyName: String (Required)
+     *                 keyVaultKeyVersion: String (Optional)
+     *                 keyVaultUri: String (Required)
+     *                 accessCredentials (Optional): {
+     *                     applicationId: String (Required)
+     *                     applicationSecret: String (Optional)
+     *                 }
+     *                 identity (Optional): {
+     *                     @odata.type: String (Required)
+     *                 }
+     *             }
+     *             cache (Optional): {
+     *                 storageConnectionString: String (Optional)
+     *                 enableReprocessing: Boolean (Optional)
+     *                 identity (Optional): (recursive schema, see identity above)
+     *                 id: String (Optional)
+     *             }
+     *         }
+     *     ]
+     * }
+     * }
+     * 
+ * + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return response from a List Indexers request along with {@link Response} on successful completion of + * {@link Mono}. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono> listWithResponse(RequestOptions requestOptions) { + return this.serviceClient.listWithResponseAsync(requestOptions); + } + + /** + * Creates a new indexer. + *

Request Body Schema

+ * + *
+     * {@code
+     * {
+     *     name: String (Required)
+     *     description: String (Optional)
+     *     dataSourceName: String (Required)
+     *     skillsetName: String (Optional)
+     *     targetIndexName: String (Required)
+     *     schedule (Optional): {
+     *         interval: Duration (Required)
+     *         startTime: OffsetDateTime (Optional)
+     *     }
+     *     parameters (Optional): {
+     *         batchSize: Integer (Optional)
+     *         maxFailedItems: Integer (Optional)
+     *         maxFailedItemsPerBatch: Integer (Optional)
+     *         configuration (Optional): {
+     *             parsingMode: String(default/text/delimitedText/json/jsonArray/jsonLines/markdown) (Optional)
+     *             excludedFileNameExtensions: String (Optional)
+     *             indexedFileNameExtensions: String (Optional)
+     *             failOnUnsupportedContentType: Boolean (Optional)
+     *             failOnUnprocessableDocument: Boolean (Optional)
+     *             indexStorageMetadataOnlyForOversizedDocuments: Boolean (Optional)
+     *             delimitedTextHeaders: String (Optional)
+     *             delimitedTextDelimiter: String (Optional)
+     *             firstLineContainsHeaders: Boolean (Optional)
+     *             markdownParsingSubmode: String(oneToMany/oneToOne) (Optional)
+     *             markdownHeaderDepth: String(h1/h2/h3/h4/h5/h6) (Optional)
+     *             documentRoot: String (Optional)
+     *             dataToExtract: String(storageMetadata/allMetadata/contentAndMetadata) (Optional)
+     *             imageAction: String(none/generateNormalizedImages/generateNormalizedImagePerPage) (Optional)
+     *             allowSkillsetToReadFileData: Boolean (Optional)
+     *             pdfTextRotationAlgorithm: String(none/detectAngles) (Optional)
+     *             executionEnvironment: String(standard/private) (Optional)
+     *             queryTimeout: String (Optional)
+     *              (Optional): {
+     *                 String: BinaryData (Required)
+     *             }
+     *         }
+     *     }
+     *     fieldMappings (Optional): [
+     *          (Optional){
+     *             sourceFieldName: String (Required)
+     *             targetFieldName: String (Optional)
+     *             mappingFunction (Optional): {
+     *                 name: String (Required)
+     *                 parameters (Optional): {
+     *                     String: BinaryData (Required)
+     *                 }
+     *             }
+     *         }
+     *     ]
+     *     outputFieldMappings (Optional): [
+     *         (recursive schema, see above)
+     *     ]
+     *     disabled: Boolean (Optional)
+     *     @odata.etag: String (Optional)
+     *     encryptionKey (Optional): {
+     *         keyVaultKeyName: String (Required)
+     *         keyVaultKeyVersion: String (Optional)
+     *         keyVaultUri: String (Required)
+     *         accessCredentials (Optional): {
+     *             applicationId: String (Required)
+     *             applicationSecret: String (Optional)
+     *         }
+     *         identity (Optional): {
+     *             @odata.type: String (Required)
+     *         }
+     *     }
+     *     cache (Optional): {
+     *         storageConnectionString: String (Optional)
+     *         enableReprocessing: Boolean (Optional)
+     *         identity (Optional): (recursive schema, see identity above)
+     *         id: String (Optional)
+     *     }
+     * }
+     * }
+     * 
+ * + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     name: String (Required)
+     *     description: String (Optional)
+     *     dataSourceName: String (Required)
+     *     skillsetName: String (Optional)
+     *     targetIndexName: String (Required)
+     *     schedule (Optional): {
+     *         interval: Duration (Required)
+     *         startTime: OffsetDateTime (Optional)
+     *     }
+     *     parameters (Optional): {
+     *         batchSize: Integer (Optional)
+     *         maxFailedItems: Integer (Optional)
+     *         maxFailedItemsPerBatch: Integer (Optional)
+     *         configuration (Optional): {
+     *             parsingMode: String(default/text/delimitedText/json/jsonArray/jsonLines/markdown) (Optional)
+     *             excludedFileNameExtensions: String (Optional)
+     *             indexedFileNameExtensions: String (Optional)
+     *             failOnUnsupportedContentType: Boolean (Optional)
+     *             failOnUnprocessableDocument: Boolean (Optional)
+     *             indexStorageMetadataOnlyForOversizedDocuments: Boolean (Optional)
+     *             delimitedTextHeaders: String (Optional)
+     *             delimitedTextDelimiter: String (Optional)
+     *             firstLineContainsHeaders: Boolean (Optional)
+     *             markdownParsingSubmode: String(oneToMany/oneToOne) (Optional)
+     *             markdownHeaderDepth: String(h1/h2/h3/h4/h5/h6) (Optional)
+     *             documentRoot: String (Optional)
+     *             dataToExtract: String(storageMetadata/allMetadata/contentAndMetadata) (Optional)
+     *             imageAction: String(none/generateNormalizedImages/generateNormalizedImagePerPage) (Optional)
+     *             allowSkillsetToReadFileData: Boolean (Optional)
+     *             pdfTextRotationAlgorithm: String(none/detectAngles) (Optional)
+     *             executionEnvironment: String(standard/private) (Optional)
+     *             queryTimeout: String (Optional)
+     *              (Optional): {
+     *                 String: BinaryData (Required)
+     *             }
+     *         }
+     *     }
+     *     fieldMappings (Optional): [
+     *          (Optional){
+     *             sourceFieldName: String (Required)
+     *             targetFieldName: String (Optional)
+     *             mappingFunction (Optional): {
+     *                 name: String (Required)
+     *                 parameters (Optional): {
+     *                     String: BinaryData (Required)
+     *                 }
+     *             }
+     *         }
+     *     ]
+     *     outputFieldMappings (Optional): [
+     *         (recursive schema, see above)
+     *     ]
+     *     disabled: Boolean (Optional)
+     *     @odata.etag: String (Optional)
+     *     encryptionKey (Optional): {
+     *         keyVaultKeyName: String (Required)
+     *         keyVaultKeyVersion: String (Optional)
+     *         keyVaultUri: String (Required)
+     *         accessCredentials (Optional): {
+     *             applicationId: String (Required)
+     *             applicationSecret: String (Optional)
+     *         }
+     *         identity (Optional): {
+     *             @odata.type: String (Required)
+     *         }
+     *     }
+     *     cache (Optional): {
+     *         storageConnectionString: String (Optional)
+     *         enableReprocessing: Boolean (Optional)
+     *         identity (Optional): (recursive schema, see identity above)
+     *         id: String (Optional)
+     *     }
+     * }
+     * }
+     * 
+ * + * @param indexer The definition of the indexer to create. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return represents an indexer along with {@link Response} on successful completion of {@link Mono}. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono> createWithResponse(BinaryData indexer, RequestOptions requestOptions) { + return this.serviceClient.createWithResponseAsync(indexer, requestOptions); + } + + /** + * Returns the current status and execution history of an indexer. + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     status: String(unknown/error/running) (Required)
+     *     lastResult (Optional): {
+     *         status: String(transientFailure/success/inProgress/reset) (Required)
+     *         statusDetail: String(resetDocs) (Optional)
+     *         currentState (Optional): {
+     *             mode: String(indexingAllDocs/indexingResetDocs) (Optional)
+     *             allDocsInitialChangeTrackingState: String (Optional)
+     *             allDocsFinalChangeTrackingState: String (Optional)
+     *             resetDocsInitialChangeTrackingState: String (Optional)
+     *             resetDocsFinalChangeTrackingState: String (Optional)
+     *             resetDocumentKeys (Optional): [
+     *                 String (Optional)
+     *             ]
+     *             resetDatasourceDocumentIds (Optional): [
+     *                 String (Optional)
+     *             ]
+     *         }
+     *         errorMessage: String (Optional)
+     *         startTime: OffsetDateTime (Optional)
+     *         endTime: OffsetDateTime (Optional)
+     *         errors (Required): [
+     *              (Required){
+     *                 key: String (Optional)
+     *                 errorMessage: String (Required)
+     *                 statusCode: int (Required)
+     *                 name: String (Optional)
+     *                 details: String (Optional)
+     *                 documentationLink: String (Optional)
+     *             }
+     *         ]
+     *         warnings (Required): [
+     *              (Required){
+     *                 key: String (Optional)
+     *                 message: String (Required)
+     *                 name: String (Optional)
+     *                 details: String (Optional)
+     *                 documentationLink: String (Optional)
+     *             }
+     *         ]
+     *         itemsProcessed: int (Required)
+     *         itemsFailed: int (Required)
+     *         initialTrackingState: String (Optional)
+     *         finalTrackingState: String (Optional)
+     *     }
+     *     executionHistory (Required): [
+     *         (recursive schema, see above)
+     *     ]
+     *     limits (Required): {
+     *         maxRunTime: Duration (Optional)
+     *         maxDocumentExtractionSize: Long (Optional)
+     *         maxDocumentContentCharactersToExtract: Long (Optional)
+     *     }
+     * }
+     * }
+     * 
+ * + * @param indexerName The name of the indexer. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return represents the current status and execution history of an indexer along with {@link Response} on + * successful completion of {@link Mono}. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono> getStatusWithResponse(String indexerName, RequestOptions requestOptions) { + return this.serviceClient.getStatusWithResponseAsync(indexerName, requestOptions); + } + + /** + * Resets the change tracking state associated with an indexer. + * + * @param indexerName The name of the indexer. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return A {@link Mono} that completes when a successful response is received. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono reset(String indexerName) { + // Generated convenience method for resetWithResponse + RequestOptions requestOptions = new RequestOptions(); + return resetWithResponse(indexerName, requestOptions).flatMap(FluxUtil::toMono); + } + + /** + * Resets specific documents in the datasource to be selectively re-ingested by + * the indexer. + * + * @param indexerName The name of the indexer. + * @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. + * @param keysOrIds 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. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return A {@link Mono} that completes when a successful response is received. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono resetDocs(String indexerName, Boolean overwrite, DocumentKeysOrIds keysOrIds) { + // Generated convenience method for resetDocsWithResponse + RequestOptions requestOptions = new RequestOptions(); + if (overwrite != null) { + requestOptions.addQueryParam("overwrite", String.valueOf(overwrite), false); + } + if (keysOrIds != null) { + requestOptions.setBody(BinaryData.fromObject(keysOrIds)); + } + return resetDocsWithResponse(indexerName, requestOptions).flatMap(FluxUtil::toMono); + } + + /** + * Resets specific documents in the datasource to be selectively re-ingested by + * the indexer. + * + * @param indexerName The name of the indexer. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return A {@link Mono} that completes when a successful response is received. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono resetDocs(String indexerName) { + // Generated convenience method for resetDocsWithResponse + RequestOptions requestOptions = new RequestOptions(); + return resetDocsWithResponse(indexerName, requestOptions).flatMap(FluxUtil::toMono); + } + + /** + * Runs an indexer on-demand. + * + * @param indexerName The name of the indexer. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return A {@link Mono} that completes when a successful response is received. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono run(String indexerName) { + // Generated convenience method for runWithResponse + RequestOptions requestOptions = new RequestOptions(); + return runWithResponse(indexerName, requestOptions).flatMap(FluxUtil::toMono); + } + + /** + * Creates a new indexer or updates an indexer if it already exists. + * + * @param indexerName The name of the indexer. + * @param indexer The definition of the indexer to create or update. + * @param skipIndexerResetRequirementForCache Ignores cache reset requirements. + * @param disableCacheReprocessingChangeDetection Disables cache reprocessing change detection. + * @param matchConditions Specifies HTTP options for conditional requests. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return represents an indexer on successful completion of {@link Mono}. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono createOrUpdate(String indexerName, SearchIndexer indexer, + Boolean skipIndexerResetRequirementForCache, Boolean disableCacheReprocessingChangeDetection, + MatchConditions matchConditions) { + // Generated convenience method for createOrUpdateWithResponse + RequestOptions requestOptions = new RequestOptions(); + String ifMatch = matchConditions == null ? null : matchConditions.getIfMatch(); + String ifNoneMatch = matchConditions == null ? null : matchConditions.getIfNoneMatch(); + if (skipIndexerResetRequirementForCache != null) { + requestOptions.addQueryParam("ignoreResetRequirements", String.valueOf(skipIndexerResetRequirementForCache), + false); + } + if (disableCacheReprocessingChangeDetection != null) { + requestOptions.addQueryParam("disableCacheReprocessingChangeDetection", + String.valueOf(disableCacheReprocessingChangeDetection), false); + } + if (ifMatch != null) { + requestOptions.setHeader(HttpHeaderName.IF_MATCH, ifMatch); + } + if (ifNoneMatch != null) { + requestOptions.setHeader(HttpHeaderName.IF_NONE_MATCH, ifNoneMatch); + } + return createOrUpdateWithResponse(indexerName, BinaryData.fromObject(indexer), requestOptions) + .flatMap(FluxUtil::toMono) + .map(protocolMethodData -> protocolMethodData.toObject(SearchIndexer.class)); + } + + /** + * Creates a new indexer or updates an indexer if it already exists. + * + * @param indexerName The name of the indexer. + * @param indexer The definition of the indexer to create or update. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return represents an indexer on successful completion of {@link Mono}. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono createOrUpdate(String indexerName, SearchIndexer indexer) { + // Generated convenience method for createOrUpdateWithResponse + RequestOptions requestOptions = new RequestOptions(); + return createOrUpdateWithResponse(indexerName, BinaryData.fromObject(indexer), requestOptions) + .flatMap(FluxUtil::toMono) + .map(protocolMethodData -> protocolMethodData.toObject(SearchIndexer.class)); + } + + /** + * Deletes an indexer. + * + * @param indexerName The name of the indexer. + * @param matchConditions Specifies HTTP options for conditional requests. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return A {@link Mono} that completes when a successful response is received. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono delete(String indexerName, MatchConditions matchConditions) { + // Generated convenience method for deleteWithResponse + RequestOptions requestOptions = new RequestOptions(); + String ifMatch = matchConditions == null ? null : matchConditions.getIfMatch(); + String ifNoneMatch = matchConditions == null ? null : matchConditions.getIfNoneMatch(); + if (ifMatch != null) { + requestOptions.setHeader(HttpHeaderName.IF_MATCH, ifMatch); + } + if (ifNoneMatch != null) { + requestOptions.setHeader(HttpHeaderName.IF_NONE_MATCH, ifNoneMatch); + } + return deleteWithResponse(indexerName, requestOptions).flatMap(FluxUtil::toMono); + } + + /** + * Deletes an indexer. + * + * @param indexerName The name of the indexer. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return A {@link Mono} that completes when a successful response is received. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono delete(String indexerName) { + // Generated convenience method for deleteWithResponse + RequestOptions requestOptions = new RequestOptions(); + return deleteWithResponse(indexerName, requestOptions).flatMap(FluxUtil::toMono); + } + + /** + * Retrieves an indexer definition. + * + * @param indexerName The name of the indexer. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return represents an indexer on successful completion of {@link Mono}. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono get(String indexerName) { + // Generated convenience method for getWithResponse + RequestOptions requestOptions = new RequestOptions(); + return getWithResponse(indexerName, requestOptions).flatMap(FluxUtil::toMono) + .map(protocolMethodData -> protocolMethodData.toObject(SearchIndexer.class)); + } + + /** + * Lists all indexers available for a search service. + * + * @param 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. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return response from a List Indexers request on successful completion of {@link Mono}. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono list(String select) { + // Generated convenience method for listWithResponse + RequestOptions requestOptions = new RequestOptions(); + if (select != null) { + requestOptions.addQueryParam("$select", select, false); + } + return listWithResponse(requestOptions).flatMap(FluxUtil::toMono) + .map(protocolMethodData -> protocolMethodData.toObject(ListIndexersResult.class)); + } + + /** + * Lists all indexers available for a search service. + * + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return response from a List Indexers request on successful completion of {@link Mono}. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono list() { + // Generated convenience method for listWithResponse + RequestOptions requestOptions = new RequestOptions(); + return listWithResponse(requestOptions).flatMap(FluxUtil::toMono) + .map(protocolMethodData -> protocolMethodData.toObject(ListIndexersResult.class)); + } + + /** + * Creates a new indexer. + * + * @param indexer The definition of the indexer to create. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return represents an indexer on successful completion of {@link Mono}. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono create(SearchIndexer indexer) { + // Generated convenience method for createWithResponse + RequestOptions requestOptions = new RequestOptions(); + return createWithResponse(BinaryData.fromObject(indexer), requestOptions).flatMap(FluxUtil::toMono) + .map(protocolMethodData -> protocolMethodData.toObject(SearchIndexer.class)); + } + + /** + * Returns the current status and execution history of an indexer. + * + * @param indexerName The name of the indexer. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return represents the current status and execution history of an indexer on successful completion of + * {@link Mono}. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono getStatus(String indexerName) { + // Generated convenience method for getStatusWithResponse + RequestOptions requestOptions = new RequestOptions(); + return getStatusWithResponse(indexerName, requestOptions).flatMap(FluxUtil::toMono) + .map(protocolMethodData -> protocolMethodData.toObject(SearchIndexerStatus.class)); + } +} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/IndexersClient.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/IndexersClient.java new file mode 100644 index 000000000000..8a8e4c873dcc --- /dev/null +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/IndexersClient.java @@ -0,0 +1,1115 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.search.documents; + +import com.azure.core.annotation.Generated; +import com.azure.core.annotation.ReturnType; +import com.azure.core.annotation.ServiceClient; +import com.azure.core.annotation.ServiceMethod; +import com.azure.core.exception.ClientAuthenticationException; +import com.azure.core.exception.HttpResponseException; +import com.azure.core.exception.ResourceModifiedException; +import com.azure.core.exception.ResourceNotFoundException; +import com.azure.core.http.HttpHeaderName; +import com.azure.core.http.MatchConditions; +import com.azure.core.http.rest.RequestOptions; +import com.azure.core.http.rest.Response; +import com.azure.core.util.BinaryData; +import com.azure.search.documents.implementation.IndexersImpl; +import com.azure.search.documents.models.DocumentKeysOrIds; +import com.azure.search.documents.models.ListIndexersResult; +import com.azure.search.documents.models.SearchIndexer; +import com.azure.search.documents.models.SearchIndexerStatus; + +/** + * Initializes a new instance of the synchronous SearchClient type. + */ +@ServiceClient(builder = SearchClientBuilder.class) +public final class IndexersClient { + @Generated + private final IndexersImpl serviceClient; + + /** + * Initializes an instance of IndexersClient class. + * + * @param serviceClient the service client implementation. + */ + @Generated + IndexersClient(IndexersImpl serviceClient) { + this.serviceClient = serviceClient; + } + + /** + * Resets the change tracking state associated with an indexer. + * + * @param indexerName The name of the indexer. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return the {@link Response}. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public Response resetWithResponse(String indexerName, RequestOptions requestOptions) { + return this.serviceClient.resetWithResponse(indexerName, requestOptions); + } + + /** + * Resets specific documents in the datasource to be selectively re-ingested by + * the indexer. + *

Query Parameters

+ * + * + * + * + *
Query Parameters
NameTypeRequiredDescription
overwriteBooleanNoIf 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.
+ * You can add these to a request with {@link RequestOptions#addQueryParam} + *

Header Parameters

+ * + * + * + * + *
Header Parameters
NameTypeRequiredDescription
Content-TypeStringNoThe content type. Allowed values: + * "application/json".
+ * You can add these to a request with {@link RequestOptions#addHeader} + *

Request Body Schema

+ * + *
+     * {@code
+     * {
+     *     documentKeys (Optional): [
+     *         String (Optional)
+     *     ]
+     *     datasourceDocumentIds (Optional): [
+     *         String (Optional)
+     *     ]
+     * }
+     * }
+     * 
+ * + * @param indexerName The name of the indexer. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return the {@link Response}. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public Response resetDocsWithResponse(String indexerName, RequestOptions requestOptions) { + return this.serviceClient.resetDocsWithResponse(indexerName, requestOptions); + } + + /** + * Runs an indexer on-demand. + * + * @param indexerName The name of the indexer. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return the {@link Response}. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public Response runWithResponse(String indexerName, RequestOptions requestOptions) { + return this.serviceClient.runWithResponse(indexerName, requestOptions); + } + + /** + * Creates a new indexer or updates an indexer if it already exists. + *

Query Parameters

+ * + * + * + * + * + *
Query Parameters
NameTypeRequiredDescription
ignoreResetRequirementsBooleanNoIgnores cache reset requirements.
disableCacheReprocessingChangeDetectionBooleanNoDisables cache reprocessing + * change detection.
+ * You can add these to a request with {@link RequestOptions#addQueryParam} + *

Header Parameters

+ * + * + * + * + * + *
Header Parameters
NameTypeRequiredDescription
If-MatchStringNoDefines the If-Match condition. The operation will be + * performed only if the ETag on the server matches this value.
If-None-MatchStringNoDefines the If-None-Match condition. The operation will + * be performed only if the ETag on the server does not match this value.
+ * You can add these to a request with {@link RequestOptions#addHeader} + *

Request Body Schema

+ * + *
+     * {@code
+     * {
+     *     name: String (Required)
+     *     description: String (Optional)
+     *     dataSourceName: String (Required)
+     *     skillsetName: String (Optional)
+     *     targetIndexName: String (Required)
+     *     schedule (Optional): {
+     *         interval: Duration (Required)
+     *         startTime: OffsetDateTime (Optional)
+     *     }
+     *     parameters (Optional): {
+     *         batchSize: Integer (Optional)
+     *         maxFailedItems: Integer (Optional)
+     *         maxFailedItemsPerBatch: Integer (Optional)
+     *         configuration (Optional): {
+     *             parsingMode: String(default/text/delimitedText/json/jsonArray/jsonLines/markdown) (Optional)
+     *             excludedFileNameExtensions: String (Optional)
+     *             indexedFileNameExtensions: String (Optional)
+     *             failOnUnsupportedContentType: Boolean (Optional)
+     *             failOnUnprocessableDocument: Boolean (Optional)
+     *             indexStorageMetadataOnlyForOversizedDocuments: Boolean (Optional)
+     *             delimitedTextHeaders: String (Optional)
+     *             delimitedTextDelimiter: String (Optional)
+     *             firstLineContainsHeaders: Boolean (Optional)
+     *             markdownParsingSubmode: String(oneToMany/oneToOne) (Optional)
+     *             markdownHeaderDepth: String(h1/h2/h3/h4/h5/h6) (Optional)
+     *             documentRoot: String (Optional)
+     *             dataToExtract: String(storageMetadata/allMetadata/contentAndMetadata) (Optional)
+     *             imageAction: String(none/generateNormalizedImages/generateNormalizedImagePerPage) (Optional)
+     *             allowSkillsetToReadFileData: Boolean (Optional)
+     *             pdfTextRotationAlgorithm: String(none/detectAngles) (Optional)
+     *             executionEnvironment: String(standard/private) (Optional)
+     *             queryTimeout: String (Optional)
+     *              (Optional): {
+     *                 String: BinaryData (Required)
+     *             }
+     *         }
+     *     }
+     *     fieldMappings (Optional): [
+     *          (Optional){
+     *             sourceFieldName: String (Required)
+     *             targetFieldName: String (Optional)
+     *             mappingFunction (Optional): {
+     *                 name: String (Required)
+     *                 parameters (Optional): {
+     *                     String: BinaryData (Required)
+     *                 }
+     *             }
+     *         }
+     *     ]
+     *     outputFieldMappings (Optional): [
+     *         (recursive schema, see above)
+     *     ]
+     *     disabled: Boolean (Optional)
+     *     @odata.etag: String (Optional)
+     *     encryptionKey (Optional): {
+     *         keyVaultKeyName: String (Required)
+     *         keyVaultKeyVersion: String (Optional)
+     *         keyVaultUri: String (Required)
+     *         accessCredentials (Optional): {
+     *             applicationId: String (Required)
+     *             applicationSecret: String (Optional)
+     *         }
+     *         identity (Optional): {
+     *             @odata.type: String (Required)
+     *         }
+     *     }
+     *     cache (Optional): {
+     *         storageConnectionString: String (Optional)
+     *         enableReprocessing: Boolean (Optional)
+     *         identity (Optional): (recursive schema, see identity above)
+     *         id: String (Optional)
+     *     }
+     * }
+     * }
+     * 
+ * + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     name: String (Required)
+     *     description: String (Optional)
+     *     dataSourceName: String (Required)
+     *     skillsetName: String (Optional)
+     *     targetIndexName: String (Required)
+     *     schedule (Optional): {
+     *         interval: Duration (Required)
+     *         startTime: OffsetDateTime (Optional)
+     *     }
+     *     parameters (Optional): {
+     *         batchSize: Integer (Optional)
+     *         maxFailedItems: Integer (Optional)
+     *         maxFailedItemsPerBatch: Integer (Optional)
+     *         configuration (Optional): {
+     *             parsingMode: String(default/text/delimitedText/json/jsonArray/jsonLines/markdown) (Optional)
+     *             excludedFileNameExtensions: String (Optional)
+     *             indexedFileNameExtensions: String (Optional)
+     *             failOnUnsupportedContentType: Boolean (Optional)
+     *             failOnUnprocessableDocument: Boolean (Optional)
+     *             indexStorageMetadataOnlyForOversizedDocuments: Boolean (Optional)
+     *             delimitedTextHeaders: String (Optional)
+     *             delimitedTextDelimiter: String (Optional)
+     *             firstLineContainsHeaders: Boolean (Optional)
+     *             markdownParsingSubmode: String(oneToMany/oneToOne) (Optional)
+     *             markdownHeaderDepth: String(h1/h2/h3/h4/h5/h6) (Optional)
+     *             documentRoot: String (Optional)
+     *             dataToExtract: String(storageMetadata/allMetadata/contentAndMetadata) (Optional)
+     *             imageAction: String(none/generateNormalizedImages/generateNormalizedImagePerPage) (Optional)
+     *             allowSkillsetToReadFileData: Boolean (Optional)
+     *             pdfTextRotationAlgorithm: String(none/detectAngles) (Optional)
+     *             executionEnvironment: String(standard/private) (Optional)
+     *             queryTimeout: String (Optional)
+     *              (Optional): {
+     *                 String: BinaryData (Required)
+     *             }
+     *         }
+     *     }
+     *     fieldMappings (Optional): [
+     *          (Optional){
+     *             sourceFieldName: String (Required)
+     *             targetFieldName: String (Optional)
+     *             mappingFunction (Optional): {
+     *                 name: String (Required)
+     *                 parameters (Optional): {
+     *                     String: BinaryData (Required)
+     *                 }
+     *             }
+     *         }
+     *     ]
+     *     outputFieldMappings (Optional): [
+     *         (recursive schema, see above)
+     *     ]
+     *     disabled: Boolean (Optional)
+     *     @odata.etag: String (Optional)
+     *     encryptionKey (Optional): {
+     *         keyVaultKeyName: String (Required)
+     *         keyVaultKeyVersion: String (Optional)
+     *         keyVaultUri: String (Required)
+     *         accessCredentials (Optional): {
+     *             applicationId: String (Required)
+     *             applicationSecret: String (Optional)
+     *         }
+     *         identity (Optional): {
+     *             @odata.type: String (Required)
+     *         }
+     *     }
+     *     cache (Optional): {
+     *         storageConnectionString: String (Optional)
+     *         enableReprocessing: Boolean (Optional)
+     *         identity (Optional): (recursive schema, see identity above)
+     *         id: String (Optional)
+     *     }
+     * }
+     * }
+     * 
+ * + * @param indexerName The name of the indexer. + * @param indexer The definition of the indexer to create or update. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return represents an indexer along with {@link Response}. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public Response createOrUpdateWithResponse(String indexerName, BinaryData indexer, + RequestOptions requestOptions) { + return this.serviceClient.createOrUpdateWithResponse(indexerName, indexer, requestOptions); + } + + /** + * Deletes an indexer. + *

Header Parameters

+ * + * + * + * + * + *
Header Parameters
NameTypeRequiredDescription
If-MatchStringNoDefines the If-Match condition. The operation will be + * performed only if the ETag on the server matches this value.
If-None-MatchStringNoDefines the If-None-Match condition. The operation will + * be performed only if the ETag on the server does not match this value.
+ * You can add these to a request with {@link RequestOptions#addHeader} + * + * @param indexerName The name of the indexer. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return the {@link Response}. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public Response deleteWithResponse(String indexerName, RequestOptions requestOptions) { + return this.serviceClient.deleteWithResponse(indexerName, requestOptions); + } + + /** + * Retrieves an indexer definition. + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     name: String (Required)
+     *     description: String (Optional)
+     *     dataSourceName: String (Required)
+     *     skillsetName: String (Optional)
+     *     targetIndexName: String (Required)
+     *     schedule (Optional): {
+     *         interval: Duration (Required)
+     *         startTime: OffsetDateTime (Optional)
+     *     }
+     *     parameters (Optional): {
+     *         batchSize: Integer (Optional)
+     *         maxFailedItems: Integer (Optional)
+     *         maxFailedItemsPerBatch: Integer (Optional)
+     *         configuration (Optional): {
+     *             parsingMode: String(default/text/delimitedText/json/jsonArray/jsonLines/markdown) (Optional)
+     *             excludedFileNameExtensions: String (Optional)
+     *             indexedFileNameExtensions: String (Optional)
+     *             failOnUnsupportedContentType: Boolean (Optional)
+     *             failOnUnprocessableDocument: Boolean (Optional)
+     *             indexStorageMetadataOnlyForOversizedDocuments: Boolean (Optional)
+     *             delimitedTextHeaders: String (Optional)
+     *             delimitedTextDelimiter: String (Optional)
+     *             firstLineContainsHeaders: Boolean (Optional)
+     *             markdownParsingSubmode: String(oneToMany/oneToOne) (Optional)
+     *             markdownHeaderDepth: String(h1/h2/h3/h4/h5/h6) (Optional)
+     *             documentRoot: String (Optional)
+     *             dataToExtract: String(storageMetadata/allMetadata/contentAndMetadata) (Optional)
+     *             imageAction: String(none/generateNormalizedImages/generateNormalizedImagePerPage) (Optional)
+     *             allowSkillsetToReadFileData: Boolean (Optional)
+     *             pdfTextRotationAlgorithm: String(none/detectAngles) (Optional)
+     *             executionEnvironment: String(standard/private) (Optional)
+     *             queryTimeout: String (Optional)
+     *              (Optional): {
+     *                 String: BinaryData (Required)
+     *             }
+     *         }
+     *     }
+     *     fieldMappings (Optional): [
+     *          (Optional){
+     *             sourceFieldName: String (Required)
+     *             targetFieldName: String (Optional)
+     *             mappingFunction (Optional): {
+     *                 name: String (Required)
+     *                 parameters (Optional): {
+     *                     String: BinaryData (Required)
+     *                 }
+     *             }
+     *         }
+     *     ]
+     *     outputFieldMappings (Optional): [
+     *         (recursive schema, see above)
+     *     ]
+     *     disabled: Boolean (Optional)
+     *     @odata.etag: String (Optional)
+     *     encryptionKey (Optional): {
+     *         keyVaultKeyName: String (Required)
+     *         keyVaultKeyVersion: String (Optional)
+     *         keyVaultUri: String (Required)
+     *         accessCredentials (Optional): {
+     *             applicationId: String (Required)
+     *             applicationSecret: String (Optional)
+     *         }
+     *         identity (Optional): {
+     *             @odata.type: String (Required)
+     *         }
+     *     }
+     *     cache (Optional): {
+     *         storageConnectionString: String (Optional)
+     *         enableReprocessing: Boolean (Optional)
+     *         identity (Optional): (recursive schema, see identity above)
+     *         id: String (Optional)
+     *     }
+     * }
+     * }
+     * 
+ * + * @param indexerName The name of the indexer. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return represents an indexer along with {@link Response}. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public Response getWithResponse(String indexerName, RequestOptions requestOptions) { + return this.serviceClient.getWithResponse(indexerName, requestOptions); + } + + /** + * Lists all indexers available for a search service. + *

Query Parameters

+ * + * + * + * + *
Query Parameters
NameTypeRequiredDescription
$selectStringNoSelects 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.
+ * You can add these to a request with {@link RequestOptions#addQueryParam} + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     value (Required): [
+     *          (Required){
+     *             name: String (Required)
+     *             description: String (Optional)
+     *             dataSourceName: String (Required)
+     *             skillsetName: String (Optional)
+     *             targetIndexName: String (Required)
+     *             schedule (Optional): {
+     *                 interval: Duration (Required)
+     *                 startTime: OffsetDateTime (Optional)
+     *             }
+     *             parameters (Optional): {
+     *                 batchSize: Integer (Optional)
+     *                 maxFailedItems: Integer (Optional)
+     *                 maxFailedItemsPerBatch: Integer (Optional)
+     *                 configuration (Optional): {
+     *                     parsingMode: String(default/text/delimitedText/json/jsonArray/jsonLines/markdown) (Optional)
+     *                     excludedFileNameExtensions: String (Optional)
+     *                     indexedFileNameExtensions: String (Optional)
+     *                     failOnUnsupportedContentType: Boolean (Optional)
+     *                     failOnUnprocessableDocument: Boolean (Optional)
+     *                     indexStorageMetadataOnlyForOversizedDocuments: Boolean (Optional)
+     *                     delimitedTextHeaders: String (Optional)
+     *                     delimitedTextDelimiter: String (Optional)
+     *                     firstLineContainsHeaders: Boolean (Optional)
+     *                     markdownParsingSubmode: String(oneToMany/oneToOne) (Optional)
+     *                     markdownHeaderDepth: String(h1/h2/h3/h4/h5/h6) (Optional)
+     *                     documentRoot: String (Optional)
+     *                     dataToExtract: String(storageMetadata/allMetadata/contentAndMetadata) (Optional)
+     *                     imageAction: String(none/generateNormalizedImages/generateNormalizedImagePerPage) (Optional)
+     *                     allowSkillsetToReadFileData: Boolean (Optional)
+     *                     pdfTextRotationAlgorithm: String(none/detectAngles) (Optional)
+     *                     executionEnvironment: String(standard/private) (Optional)
+     *                     queryTimeout: String (Optional)
+     *                      (Optional): {
+     *                         String: BinaryData (Required)
+     *                     }
+     *                 }
+     *             }
+     *             fieldMappings (Optional): [
+     *                  (Optional){
+     *                     sourceFieldName: String (Required)
+     *                     targetFieldName: String (Optional)
+     *                     mappingFunction (Optional): {
+     *                         name: String (Required)
+     *                         parameters (Optional): {
+     *                             String: BinaryData (Required)
+     *                         }
+     *                     }
+     *                 }
+     *             ]
+     *             outputFieldMappings (Optional): [
+     *                 (recursive schema, see above)
+     *             ]
+     *             disabled: Boolean (Optional)
+     *             @odata.etag: String (Optional)
+     *             encryptionKey (Optional): {
+     *                 keyVaultKeyName: String (Required)
+     *                 keyVaultKeyVersion: String (Optional)
+     *                 keyVaultUri: String (Required)
+     *                 accessCredentials (Optional): {
+     *                     applicationId: String (Required)
+     *                     applicationSecret: String (Optional)
+     *                 }
+     *                 identity (Optional): {
+     *                     @odata.type: String (Required)
+     *                 }
+     *             }
+     *             cache (Optional): {
+     *                 storageConnectionString: String (Optional)
+     *                 enableReprocessing: Boolean (Optional)
+     *                 identity (Optional): (recursive schema, see identity above)
+     *                 id: String (Optional)
+     *             }
+     *         }
+     *     ]
+     * }
+     * }
+     * 
+ * + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return response from a List Indexers request along with {@link Response}. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public Response listWithResponse(RequestOptions requestOptions) { + return this.serviceClient.listWithResponse(requestOptions); + } + + /** + * Creates a new indexer. + *

Request Body Schema

+ * + *
+     * {@code
+     * {
+     *     name: String (Required)
+     *     description: String (Optional)
+     *     dataSourceName: String (Required)
+     *     skillsetName: String (Optional)
+     *     targetIndexName: String (Required)
+     *     schedule (Optional): {
+     *         interval: Duration (Required)
+     *         startTime: OffsetDateTime (Optional)
+     *     }
+     *     parameters (Optional): {
+     *         batchSize: Integer (Optional)
+     *         maxFailedItems: Integer (Optional)
+     *         maxFailedItemsPerBatch: Integer (Optional)
+     *         configuration (Optional): {
+     *             parsingMode: String(default/text/delimitedText/json/jsonArray/jsonLines/markdown) (Optional)
+     *             excludedFileNameExtensions: String (Optional)
+     *             indexedFileNameExtensions: String (Optional)
+     *             failOnUnsupportedContentType: Boolean (Optional)
+     *             failOnUnprocessableDocument: Boolean (Optional)
+     *             indexStorageMetadataOnlyForOversizedDocuments: Boolean (Optional)
+     *             delimitedTextHeaders: String (Optional)
+     *             delimitedTextDelimiter: String (Optional)
+     *             firstLineContainsHeaders: Boolean (Optional)
+     *             markdownParsingSubmode: String(oneToMany/oneToOne) (Optional)
+     *             markdownHeaderDepth: String(h1/h2/h3/h4/h5/h6) (Optional)
+     *             documentRoot: String (Optional)
+     *             dataToExtract: String(storageMetadata/allMetadata/contentAndMetadata) (Optional)
+     *             imageAction: String(none/generateNormalizedImages/generateNormalizedImagePerPage) (Optional)
+     *             allowSkillsetToReadFileData: Boolean (Optional)
+     *             pdfTextRotationAlgorithm: String(none/detectAngles) (Optional)
+     *             executionEnvironment: String(standard/private) (Optional)
+     *             queryTimeout: String (Optional)
+     *              (Optional): {
+     *                 String: BinaryData (Required)
+     *             }
+     *         }
+     *     }
+     *     fieldMappings (Optional): [
+     *          (Optional){
+     *             sourceFieldName: String (Required)
+     *             targetFieldName: String (Optional)
+     *             mappingFunction (Optional): {
+     *                 name: String (Required)
+     *                 parameters (Optional): {
+     *                     String: BinaryData (Required)
+     *                 }
+     *             }
+     *         }
+     *     ]
+     *     outputFieldMappings (Optional): [
+     *         (recursive schema, see above)
+     *     ]
+     *     disabled: Boolean (Optional)
+     *     @odata.etag: String (Optional)
+     *     encryptionKey (Optional): {
+     *         keyVaultKeyName: String (Required)
+     *         keyVaultKeyVersion: String (Optional)
+     *         keyVaultUri: String (Required)
+     *         accessCredentials (Optional): {
+     *             applicationId: String (Required)
+     *             applicationSecret: String (Optional)
+     *         }
+     *         identity (Optional): {
+     *             @odata.type: String (Required)
+     *         }
+     *     }
+     *     cache (Optional): {
+     *         storageConnectionString: String (Optional)
+     *         enableReprocessing: Boolean (Optional)
+     *         identity (Optional): (recursive schema, see identity above)
+     *         id: String (Optional)
+     *     }
+     * }
+     * }
+     * 
+ * + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     name: String (Required)
+     *     description: String (Optional)
+     *     dataSourceName: String (Required)
+     *     skillsetName: String (Optional)
+     *     targetIndexName: String (Required)
+     *     schedule (Optional): {
+     *         interval: Duration (Required)
+     *         startTime: OffsetDateTime (Optional)
+     *     }
+     *     parameters (Optional): {
+     *         batchSize: Integer (Optional)
+     *         maxFailedItems: Integer (Optional)
+     *         maxFailedItemsPerBatch: Integer (Optional)
+     *         configuration (Optional): {
+     *             parsingMode: String(default/text/delimitedText/json/jsonArray/jsonLines/markdown) (Optional)
+     *             excludedFileNameExtensions: String (Optional)
+     *             indexedFileNameExtensions: String (Optional)
+     *             failOnUnsupportedContentType: Boolean (Optional)
+     *             failOnUnprocessableDocument: Boolean (Optional)
+     *             indexStorageMetadataOnlyForOversizedDocuments: Boolean (Optional)
+     *             delimitedTextHeaders: String (Optional)
+     *             delimitedTextDelimiter: String (Optional)
+     *             firstLineContainsHeaders: Boolean (Optional)
+     *             markdownParsingSubmode: String(oneToMany/oneToOne) (Optional)
+     *             markdownHeaderDepth: String(h1/h2/h3/h4/h5/h6) (Optional)
+     *             documentRoot: String (Optional)
+     *             dataToExtract: String(storageMetadata/allMetadata/contentAndMetadata) (Optional)
+     *             imageAction: String(none/generateNormalizedImages/generateNormalizedImagePerPage) (Optional)
+     *             allowSkillsetToReadFileData: Boolean (Optional)
+     *             pdfTextRotationAlgorithm: String(none/detectAngles) (Optional)
+     *             executionEnvironment: String(standard/private) (Optional)
+     *             queryTimeout: String (Optional)
+     *              (Optional): {
+     *                 String: BinaryData (Required)
+     *             }
+     *         }
+     *     }
+     *     fieldMappings (Optional): [
+     *          (Optional){
+     *             sourceFieldName: String (Required)
+     *             targetFieldName: String (Optional)
+     *             mappingFunction (Optional): {
+     *                 name: String (Required)
+     *                 parameters (Optional): {
+     *                     String: BinaryData (Required)
+     *                 }
+     *             }
+     *         }
+     *     ]
+     *     outputFieldMappings (Optional): [
+     *         (recursive schema, see above)
+     *     ]
+     *     disabled: Boolean (Optional)
+     *     @odata.etag: String (Optional)
+     *     encryptionKey (Optional): {
+     *         keyVaultKeyName: String (Required)
+     *         keyVaultKeyVersion: String (Optional)
+     *         keyVaultUri: String (Required)
+     *         accessCredentials (Optional): {
+     *             applicationId: String (Required)
+     *             applicationSecret: String (Optional)
+     *         }
+     *         identity (Optional): {
+     *             @odata.type: String (Required)
+     *         }
+     *     }
+     *     cache (Optional): {
+     *         storageConnectionString: String (Optional)
+     *         enableReprocessing: Boolean (Optional)
+     *         identity (Optional): (recursive schema, see identity above)
+     *         id: String (Optional)
+     *     }
+     * }
+     * }
+     * 
+ * + * @param indexer The definition of the indexer to create. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return represents an indexer along with {@link Response}. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public Response createWithResponse(BinaryData indexer, RequestOptions requestOptions) { + return this.serviceClient.createWithResponse(indexer, requestOptions); + } + + /** + * Returns the current status and execution history of an indexer. + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     status: String(unknown/error/running) (Required)
+     *     lastResult (Optional): {
+     *         status: String(transientFailure/success/inProgress/reset) (Required)
+     *         statusDetail: String(resetDocs) (Optional)
+     *         currentState (Optional): {
+     *             mode: String(indexingAllDocs/indexingResetDocs) (Optional)
+     *             allDocsInitialChangeTrackingState: String (Optional)
+     *             allDocsFinalChangeTrackingState: String (Optional)
+     *             resetDocsInitialChangeTrackingState: String (Optional)
+     *             resetDocsFinalChangeTrackingState: String (Optional)
+     *             resetDocumentKeys (Optional): [
+     *                 String (Optional)
+     *             ]
+     *             resetDatasourceDocumentIds (Optional): [
+     *                 String (Optional)
+     *             ]
+     *         }
+     *         errorMessage: String (Optional)
+     *         startTime: OffsetDateTime (Optional)
+     *         endTime: OffsetDateTime (Optional)
+     *         errors (Required): [
+     *              (Required){
+     *                 key: String (Optional)
+     *                 errorMessage: String (Required)
+     *                 statusCode: int (Required)
+     *                 name: String (Optional)
+     *                 details: String (Optional)
+     *                 documentationLink: String (Optional)
+     *             }
+     *         ]
+     *         warnings (Required): [
+     *              (Required){
+     *                 key: String (Optional)
+     *                 message: String (Required)
+     *                 name: String (Optional)
+     *                 details: String (Optional)
+     *                 documentationLink: String (Optional)
+     *             }
+     *         ]
+     *         itemsProcessed: int (Required)
+     *         itemsFailed: int (Required)
+     *         initialTrackingState: String (Optional)
+     *         finalTrackingState: String (Optional)
+     *     }
+     *     executionHistory (Required): [
+     *         (recursive schema, see above)
+     *     ]
+     *     limits (Required): {
+     *         maxRunTime: Duration (Optional)
+     *         maxDocumentExtractionSize: Long (Optional)
+     *         maxDocumentContentCharactersToExtract: Long (Optional)
+     *     }
+     * }
+     * }
+     * 
+ * + * @param indexerName The name of the indexer. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return represents the current status and execution history of an indexer along with {@link Response}. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public Response getStatusWithResponse(String indexerName, RequestOptions requestOptions) { + return this.serviceClient.getStatusWithResponse(indexerName, requestOptions); + } + + /** + * Resets the change tracking state associated with an indexer. + * + * @param indexerName The name of the indexer. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public void reset(String indexerName) { + // Generated convenience method for resetWithResponse + RequestOptions requestOptions = new RequestOptions(); + resetWithResponse(indexerName, requestOptions).getValue(); + } + + /** + * Resets specific documents in the datasource to be selectively re-ingested by + * the indexer. + * + * @param indexerName The name of the indexer. + * @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. + * @param keysOrIds 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. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public void resetDocs(String indexerName, Boolean overwrite, DocumentKeysOrIds keysOrIds) { + // Generated convenience method for resetDocsWithResponse + RequestOptions requestOptions = new RequestOptions(); + if (overwrite != null) { + requestOptions.addQueryParam("overwrite", String.valueOf(overwrite), false); + } + if (keysOrIds != null) { + requestOptions.setBody(BinaryData.fromObject(keysOrIds)); + } + resetDocsWithResponse(indexerName, requestOptions).getValue(); + } + + /** + * Resets specific documents in the datasource to be selectively re-ingested by + * the indexer. + * + * @param indexerName The name of the indexer. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public void resetDocs(String indexerName) { + // Generated convenience method for resetDocsWithResponse + RequestOptions requestOptions = new RequestOptions(); + resetDocsWithResponse(indexerName, requestOptions).getValue(); + } + + /** + * Runs an indexer on-demand. + * + * @param indexerName The name of the indexer. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public void run(String indexerName) { + // Generated convenience method for runWithResponse + RequestOptions requestOptions = new RequestOptions(); + runWithResponse(indexerName, requestOptions).getValue(); + } + + /** + * Creates a new indexer or updates an indexer if it already exists. + * + * @param indexerName The name of the indexer. + * @param indexer The definition of the indexer to create or update. + * @param skipIndexerResetRequirementForCache Ignores cache reset requirements. + * @param disableCacheReprocessingChangeDetection Disables cache reprocessing change detection. + * @param matchConditions Specifies HTTP options for conditional requests. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return represents an indexer. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public SearchIndexer createOrUpdate(String indexerName, SearchIndexer indexer, + Boolean skipIndexerResetRequirementForCache, Boolean disableCacheReprocessingChangeDetection, + MatchConditions matchConditions) { + // Generated convenience method for createOrUpdateWithResponse + RequestOptions requestOptions = new RequestOptions(); + String ifMatch = matchConditions == null ? null : matchConditions.getIfMatch(); + String ifNoneMatch = matchConditions == null ? null : matchConditions.getIfNoneMatch(); + if (skipIndexerResetRequirementForCache != null) { + requestOptions.addQueryParam("ignoreResetRequirements", String.valueOf(skipIndexerResetRequirementForCache), + false); + } + if (disableCacheReprocessingChangeDetection != null) { + requestOptions.addQueryParam("disableCacheReprocessingChangeDetection", + String.valueOf(disableCacheReprocessingChangeDetection), false); + } + if (ifMatch != null) { + requestOptions.setHeader(HttpHeaderName.IF_MATCH, ifMatch); + } + if (ifNoneMatch != null) { + requestOptions.setHeader(HttpHeaderName.IF_NONE_MATCH, ifNoneMatch); + } + return createOrUpdateWithResponse(indexerName, BinaryData.fromObject(indexer), requestOptions).getValue() + .toObject(SearchIndexer.class); + } + + /** + * Creates a new indexer or updates an indexer if it already exists. + * + * @param indexerName The name of the indexer. + * @param indexer The definition of the indexer to create or update. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return represents an indexer. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public SearchIndexer createOrUpdate(String indexerName, SearchIndexer indexer) { + // Generated convenience method for createOrUpdateWithResponse + RequestOptions requestOptions = new RequestOptions(); + return createOrUpdateWithResponse(indexerName, BinaryData.fromObject(indexer), requestOptions).getValue() + .toObject(SearchIndexer.class); + } + + /** + * Deletes an indexer. + * + * @param indexerName The name of the indexer. + * @param matchConditions Specifies HTTP options for conditional requests. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public void delete(String indexerName, MatchConditions matchConditions) { + // Generated convenience method for deleteWithResponse + RequestOptions requestOptions = new RequestOptions(); + String ifMatch = matchConditions == null ? null : matchConditions.getIfMatch(); + String ifNoneMatch = matchConditions == null ? null : matchConditions.getIfNoneMatch(); + if (ifMatch != null) { + requestOptions.setHeader(HttpHeaderName.IF_MATCH, ifMatch); + } + if (ifNoneMatch != null) { + requestOptions.setHeader(HttpHeaderName.IF_NONE_MATCH, ifNoneMatch); + } + deleteWithResponse(indexerName, requestOptions).getValue(); + } + + /** + * Deletes an indexer. + * + * @param indexerName The name of the indexer. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public void delete(String indexerName) { + // Generated convenience method for deleteWithResponse + RequestOptions requestOptions = new RequestOptions(); + deleteWithResponse(indexerName, requestOptions).getValue(); + } + + /** + * Retrieves an indexer definition. + * + * @param indexerName The name of the indexer. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return represents an indexer. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public SearchIndexer get(String indexerName) { + // Generated convenience method for getWithResponse + RequestOptions requestOptions = new RequestOptions(); + return getWithResponse(indexerName, requestOptions).getValue().toObject(SearchIndexer.class); + } + + /** + * Lists all indexers available for a search service. + * + * @param 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. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return response from a List Indexers request. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public ListIndexersResult list(String select) { + // Generated convenience method for listWithResponse + RequestOptions requestOptions = new RequestOptions(); + if (select != null) { + requestOptions.addQueryParam("$select", select, false); + } + return listWithResponse(requestOptions).getValue().toObject(ListIndexersResult.class); + } + + /** + * Lists all indexers available for a search service. + * + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return response from a List Indexers request. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public ListIndexersResult list() { + // Generated convenience method for listWithResponse + RequestOptions requestOptions = new RequestOptions(); + return listWithResponse(requestOptions).getValue().toObject(ListIndexersResult.class); + } + + /** + * Creates a new indexer. + * + * @param indexer The definition of the indexer to create. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return represents an indexer. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public SearchIndexer create(SearchIndexer indexer) { + // Generated convenience method for createWithResponse + RequestOptions requestOptions = new RequestOptions(); + return createWithResponse(BinaryData.fromObject(indexer), requestOptions).getValue() + .toObject(SearchIndexer.class); + } + + /** + * Returns the current status and execution history of an indexer. + * + * @param indexerName The name of the indexer. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return represents the current status and execution history of an indexer. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public SearchIndexerStatus getStatus(String indexerName) { + // Generated convenience method for getStatusWithResponse + RequestOptions requestOptions = new RequestOptions(); + return getStatusWithResponse(indexerName, requestOptions).getValue().toObject(SearchIndexerStatus.class); + } +} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/IndexesAsyncClient.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/IndexesAsyncClient.java new file mode 100644 index 000000000000..09d8d91e7014 --- /dev/null +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/IndexesAsyncClient.java @@ -0,0 +1,1574 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.search.documents; + +import com.azure.core.annotation.Generated; +import com.azure.core.annotation.ReturnType; +import com.azure.core.annotation.ServiceClient; +import com.azure.core.annotation.ServiceMethod; +import com.azure.core.exception.ClientAuthenticationException; +import com.azure.core.exception.HttpResponseException; +import com.azure.core.exception.ResourceModifiedException; +import com.azure.core.exception.ResourceNotFoundException; +import com.azure.core.http.HttpHeaderName; +import com.azure.core.http.MatchConditions; +import com.azure.core.http.rest.PagedFlux; +import com.azure.core.http.rest.PagedResponse; +import com.azure.core.http.rest.PagedResponseBase; +import com.azure.core.http.rest.RequestOptions; +import com.azure.core.http.rest.Response; +import com.azure.core.util.BinaryData; +import com.azure.core.util.FluxUtil; +import com.azure.search.documents.implementation.IndexesImpl; +import com.azure.search.documents.models.AnalyzeRequest; +import com.azure.search.documents.models.AnalyzeResult; +import com.azure.search.documents.models.GetIndexStatisticsResult; +import com.azure.search.documents.models.SearchIndex; +import java.util.stream.Collectors; +import reactor.core.publisher.Flux; +import reactor.core.publisher.Mono; + +/** + * Initializes a new instance of the asynchronous SearchClient type. + */ +@ServiceClient(builder = SearchClientBuilder.class, isAsync = true) +public final class IndexesAsyncClient { + @Generated + private final IndexesImpl serviceClient; + + /** + * Initializes an instance of IndexesAsyncClient class. + * + * @param serviceClient the service client implementation. + */ + @Generated + IndexesAsyncClient(IndexesImpl serviceClient) { + this.serviceClient = serviceClient; + } + + /** + * Creates a new search index. + *

Request Body Schema

+ * + *
+     * {@code
+     * {
+     *     name: String (Required)
+     *     fields (Required): [
+     *          (Required){
+     *             name: String (Required)
+     *             type: String(Edm.String/Edm.Int32/Edm.Int64/Edm.Double/Edm.Boolean/Edm.DateTimeOffset/Edm.GeographyPoint/Edm.ComplexType/Edm.Single/Edm.Half/Edm.Int16/Edm.SByte/Edm.Byte) (Required)
+     *             key: Boolean (Optional)
+     *             retrievable: Boolean (Optional)
+     *             stored: Boolean (Optional)
+     *             searchable: Boolean (Optional)
+     *             filterable: Boolean (Optional)
+     *             sortable: Boolean (Optional)
+     *             facetable: Boolean (Optional)
+     *             analyzer: String(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) (Optional)
+     *             searchAnalyzer: String(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) (Optional)
+     *             indexAnalyzer: String(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) (Optional)
+     *             normalizer: String(asciifolding/elision/lowercase/standard/uppercase) (Optional)
+     *             dimensions: Integer (Optional)
+     *             vectorSearchProfile: String (Optional)
+     *             vectorEncoding: String(packedBit) (Optional)
+     *             synonymMaps (Optional): [
+     *                 String (Optional)
+     *             ]
+     *             fields (Optional): [
+     *                 (recursive schema, see above)
+     *             ]
+     *         }
+     *     ]
+     *     scoringProfiles (Optional): [
+     *          (Optional){
+     *             name: String (Required)
+     *             text (Optional): {
+     *                 weights (Required): {
+     *                     String: double (Required)
+     *                 }
+     *             }
+     *             functions (Optional): [
+     *                  (Optional){
+     *                     type: String (Required)
+     *                     fieldName: String (Required)
+     *                     boost: double (Required)
+     *                     interpolation: String(linear/constant/quadratic/logarithmic) (Optional)
+     *                 }
+     *             ]
+     *             functionAggregation: String(sum/average/minimum/maximum/firstMatching) (Optional)
+     *         }
+     *     ]
+     *     defaultScoringProfile: String (Optional)
+     *     corsOptions (Optional): {
+     *         allowedOrigins (Required): [
+     *             String (Required)
+     *         ]
+     *         maxAgeInSeconds: Long (Optional)
+     *     }
+     *     suggesters (Optional): [
+     *          (Optional){
+     *             name: String (Required)
+     *             searchMode: String (Required)
+     *             sourceFields (Required): [
+     *                 String (Required)
+     *             ]
+     *         }
+     *     ]
+     *     analyzers (Optional): [
+     *          (Optional){
+     *             @odata.type: String (Required)
+     *             name: String (Required)
+     *         }
+     *     ]
+     *     tokenizers (Optional): [
+     *          (Optional){
+     *             @odata.type: String (Required)
+     *             name: String (Required)
+     *         }
+     *     ]
+     *     tokenFilters (Optional): [
+     *          (Optional){
+     *             @odata.type: String (Required)
+     *             name: String (Required)
+     *         }
+     *     ]
+     *     charFilters (Optional): [
+     *          (Optional){
+     *             @odata.type: String (Required)
+     *             name: String (Required)
+     *         }
+     *     ]
+     *     normalizers (Optional): [
+     *          (Optional){
+     *             @odata.type: String (Required)
+     *             name: String (Required)
+     *         }
+     *     ]
+     *     encryptionKey (Optional): {
+     *         keyVaultKeyName: String (Required)
+     *         keyVaultKeyVersion: String (Optional)
+     *         keyVaultUri: String (Required)
+     *         accessCredentials (Optional): {
+     *             applicationId: String (Required)
+     *             applicationSecret: String (Optional)
+     *         }
+     *         identity (Optional): {
+     *             @odata.type: String (Required)
+     *         }
+     *     }
+     *     similarity (Optional): {
+     *         @odata.type: String (Required)
+     *     }
+     *     semantic (Optional): {
+     *         defaultConfiguration: String (Optional)
+     *         configurations (Optional): [
+     *              (Optional){
+     *                 name: String (Required)
+     *                 prioritizedFields (Required): {
+     *                     titleField (Optional): {
+     *                         fieldName: String (Required)
+     *                     }
+     *                     prioritizedContentFields (Optional): [
+     *                         (recursive schema, see above)
+     *                     ]
+     *                     prioritizedKeywordsFields (Optional): [
+     *                         (recursive schema, see above)
+     *                     ]
+     *                 }
+     *                 flightingOptIn: Boolean (Optional)
+     *             }
+     *         ]
+     *     }
+     *     vectorSearch (Optional): {
+     *         profiles (Optional): [
+     *              (Optional){
+     *                 name: String (Required)
+     *                 algorithm: String (Required)
+     *                 vectorizer: String (Optional)
+     *                 compression: String (Optional)
+     *             }
+     *         ]
+     *         algorithms (Optional): [
+     *              (Optional){
+     *                 kind: String(hnsw/exhaustiveKnn) (Required)
+     *                 name: String (Required)
+     *             }
+     *         ]
+     *         vectorizers (Optional): [
+     *              (Optional){
+     *                 kind: String(azureOpenAI/customWebApi/aiServicesVision/aml) (Required)
+     *                 name: String (Required)
+     *             }
+     *         ]
+     *         compressions (Optional): [
+     *              (Optional){
+     *                 kind: String(scalarQuantization/binaryQuantization) (Required)
+     *                 name: String (Required)
+     *                 rerankWithOriginalVectors: Boolean (Optional)
+     *                 defaultOversampling: Double (Optional)
+     *                 rescoringOptions (Optional): {
+     *                     enableRescoring: Boolean (Optional)
+     *                     defaultOversampling: Double (Optional)
+     *                     rescoreStorageMethod: String(preserveOriginals/discardOriginals) (Optional)
+     *                 }
+     *                 truncationDimension: Integer (Optional)
+     *             }
+     *         ]
+     *     }
+     *     @odata.etag: String (Optional)
+     * }
+     * }
+     * 
+ * + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     name: String (Required)
+     *     fields (Required): [
+     *          (Required){
+     *             name: String (Required)
+     *             type: String(Edm.String/Edm.Int32/Edm.Int64/Edm.Double/Edm.Boolean/Edm.DateTimeOffset/Edm.GeographyPoint/Edm.ComplexType/Edm.Single/Edm.Half/Edm.Int16/Edm.SByte/Edm.Byte) (Required)
+     *             key: Boolean (Optional)
+     *             retrievable: Boolean (Optional)
+     *             stored: Boolean (Optional)
+     *             searchable: Boolean (Optional)
+     *             filterable: Boolean (Optional)
+     *             sortable: Boolean (Optional)
+     *             facetable: Boolean (Optional)
+     *             analyzer: String(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) (Optional)
+     *             searchAnalyzer: String(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) (Optional)
+     *             indexAnalyzer: String(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) (Optional)
+     *             normalizer: String(asciifolding/elision/lowercase/standard/uppercase) (Optional)
+     *             dimensions: Integer (Optional)
+     *             vectorSearchProfile: String (Optional)
+     *             vectorEncoding: String(packedBit) (Optional)
+     *             synonymMaps (Optional): [
+     *                 String (Optional)
+     *             ]
+     *             fields (Optional): [
+     *                 (recursive schema, see above)
+     *             ]
+     *         }
+     *     ]
+     *     scoringProfiles (Optional): [
+     *          (Optional){
+     *             name: String (Required)
+     *             text (Optional): {
+     *                 weights (Required): {
+     *                     String: double (Required)
+     *                 }
+     *             }
+     *             functions (Optional): [
+     *                  (Optional){
+     *                     type: String (Required)
+     *                     fieldName: String (Required)
+     *                     boost: double (Required)
+     *                     interpolation: String(linear/constant/quadratic/logarithmic) (Optional)
+     *                 }
+     *             ]
+     *             functionAggregation: String(sum/average/minimum/maximum/firstMatching) (Optional)
+     *         }
+     *     ]
+     *     defaultScoringProfile: String (Optional)
+     *     corsOptions (Optional): {
+     *         allowedOrigins (Required): [
+     *             String (Required)
+     *         ]
+     *         maxAgeInSeconds: Long (Optional)
+     *     }
+     *     suggesters (Optional): [
+     *          (Optional){
+     *             name: String (Required)
+     *             searchMode: String (Required)
+     *             sourceFields (Required): [
+     *                 String (Required)
+     *             ]
+     *         }
+     *     ]
+     *     analyzers (Optional): [
+     *          (Optional){
+     *             @odata.type: String (Required)
+     *             name: String (Required)
+     *         }
+     *     ]
+     *     tokenizers (Optional): [
+     *          (Optional){
+     *             @odata.type: String (Required)
+     *             name: String (Required)
+     *         }
+     *     ]
+     *     tokenFilters (Optional): [
+     *          (Optional){
+     *             @odata.type: String (Required)
+     *             name: String (Required)
+     *         }
+     *     ]
+     *     charFilters (Optional): [
+     *          (Optional){
+     *             @odata.type: String (Required)
+     *             name: String (Required)
+     *         }
+     *     ]
+     *     normalizers (Optional): [
+     *          (Optional){
+     *             @odata.type: String (Required)
+     *             name: String (Required)
+     *         }
+     *     ]
+     *     encryptionKey (Optional): {
+     *         keyVaultKeyName: String (Required)
+     *         keyVaultKeyVersion: String (Optional)
+     *         keyVaultUri: String (Required)
+     *         accessCredentials (Optional): {
+     *             applicationId: String (Required)
+     *             applicationSecret: String (Optional)
+     *         }
+     *         identity (Optional): {
+     *             @odata.type: String (Required)
+     *         }
+     *     }
+     *     similarity (Optional): {
+     *         @odata.type: String (Required)
+     *     }
+     *     semantic (Optional): {
+     *         defaultConfiguration: String (Optional)
+     *         configurations (Optional): [
+     *              (Optional){
+     *                 name: String (Required)
+     *                 prioritizedFields (Required): {
+     *                     titleField (Optional): {
+     *                         fieldName: String (Required)
+     *                     }
+     *                     prioritizedContentFields (Optional): [
+     *                         (recursive schema, see above)
+     *                     ]
+     *                     prioritizedKeywordsFields (Optional): [
+     *                         (recursive schema, see above)
+     *                     ]
+     *                 }
+     *                 flightingOptIn: Boolean (Optional)
+     *             }
+     *         ]
+     *     }
+     *     vectorSearch (Optional): {
+     *         profiles (Optional): [
+     *              (Optional){
+     *                 name: String (Required)
+     *                 algorithm: String (Required)
+     *                 vectorizer: String (Optional)
+     *                 compression: String (Optional)
+     *             }
+     *         ]
+     *         algorithms (Optional): [
+     *              (Optional){
+     *                 kind: String(hnsw/exhaustiveKnn) (Required)
+     *                 name: String (Required)
+     *             }
+     *         ]
+     *         vectorizers (Optional): [
+     *              (Optional){
+     *                 kind: String(azureOpenAI/customWebApi/aiServicesVision/aml) (Required)
+     *                 name: String (Required)
+     *             }
+     *         ]
+     *         compressions (Optional): [
+     *              (Optional){
+     *                 kind: String(scalarQuantization/binaryQuantization) (Required)
+     *                 name: String (Required)
+     *                 rerankWithOriginalVectors: Boolean (Optional)
+     *                 defaultOversampling: Double (Optional)
+     *                 rescoringOptions (Optional): {
+     *                     enableRescoring: Boolean (Optional)
+     *                     defaultOversampling: Double (Optional)
+     *                     rescoreStorageMethod: String(preserveOriginals/discardOriginals) (Optional)
+     *                 }
+     *                 truncationDimension: Integer (Optional)
+     *             }
+     *         ]
+     *     }
+     *     @odata.etag: String (Optional)
+     * }
+     * }
+     * 
+ * + * @param index The definition of the index to create. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return represents a search index definition, which describes the fields and search + * behavior of an index along with {@link Response} on successful completion of {@link Mono}. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono> createWithResponse(BinaryData index, RequestOptions requestOptions) { + return this.serviceClient.createWithResponseAsync(index, requestOptions); + } + + /** + * Lists all indexes available for a search service. + *

Query Parameters

+ * + * + * + * + *
Query Parameters
NameTypeRequiredDescription
$selectStringNoSelects 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.
+ * You can add these to a request with {@link RequestOptions#addQueryParam} + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     name: String (Required)
+     *     fields (Required): [
+     *          (Required){
+     *             name: String (Required)
+     *             type: String(Edm.String/Edm.Int32/Edm.Int64/Edm.Double/Edm.Boolean/Edm.DateTimeOffset/Edm.GeographyPoint/Edm.ComplexType/Edm.Single/Edm.Half/Edm.Int16/Edm.SByte/Edm.Byte) (Required)
+     *             key: Boolean (Optional)
+     *             retrievable: Boolean (Optional)
+     *             stored: Boolean (Optional)
+     *             searchable: Boolean (Optional)
+     *             filterable: Boolean (Optional)
+     *             sortable: Boolean (Optional)
+     *             facetable: Boolean (Optional)
+     *             analyzer: String(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) (Optional)
+     *             searchAnalyzer: String(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) (Optional)
+     *             indexAnalyzer: String(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) (Optional)
+     *             normalizer: String(asciifolding/elision/lowercase/standard/uppercase) (Optional)
+     *             dimensions: Integer (Optional)
+     *             vectorSearchProfile: String (Optional)
+     *             vectorEncoding: String(packedBit) (Optional)
+     *             synonymMaps (Optional): [
+     *                 String (Optional)
+     *             ]
+     *             fields (Optional): [
+     *                 (recursive schema, see above)
+     *             ]
+     *         }
+     *     ]
+     *     scoringProfiles (Optional): [
+     *          (Optional){
+     *             name: String (Required)
+     *             text (Optional): {
+     *                 weights (Required): {
+     *                     String: double (Required)
+     *                 }
+     *             }
+     *             functions (Optional): [
+     *                  (Optional){
+     *                     type: String (Required)
+     *                     fieldName: String (Required)
+     *                     boost: double (Required)
+     *                     interpolation: String(linear/constant/quadratic/logarithmic) (Optional)
+     *                 }
+     *             ]
+     *             functionAggregation: String(sum/average/minimum/maximum/firstMatching) (Optional)
+     *         }
+     *     ]
+     *     defaultScoringProfile: String (Optional)
+     *     corsOptions (Optional): {
+     *         allowedOrigins (Required): [
+     *             String (Required)
+     *         ]
+     *         maxAgeInSeconds: Long (Optional)
+     *     }
+     *     suggesters (Optional): [
+     *          (Optional){
+     *             name: String (Required)
+     *             searchMode: String (Required)
+     *             sourceFields (Required): [
+     *                 String (Required)
+     *             ]
+     *         }
+     *     ]
+     *     analyzers (Optional): [
+     *          (Optional){
+     *             @odata.type: String (Required)
+     *             name: String (Required)
+     *         }
+     *     ]
+     *     tokenizers (Optional): [
+     *          (Optional){
+     *             @odata.type: String (Required)
+     *             name: String (Required)
+     *         }
+     *     ]
+     *     tokenFilters (Optional): [
+     *          (Optional){
+     *             @odata.type: String (Required)
+     *             name: String (Required)
+     *         }
+     *     ]
+     *     charFilters (Optional): [
+     *          (Optional){
+     *             @odata.type: String (Required)
+     *             name: String (Required)
+     *         }
+     *     ]
+     *     normalizers (Optional): [
+     *          (Optional){
+     *             @odata.type: String (Required)
+     *             name: String (Required)
+     *         }
+     *     ]
+     *     encryptionKey (Optional): {
+     *         keyVaultKeyName: String (Required)
+     *         keyVaultKeyVersion: String (Optional)
+     *         keyVaultUri: String (Required)
+     *         accessCredentials (Optional): {
+     *             applicationId: String (Required)
+     *             applicationSecret: String (Optional)
+     *         }
+     *         identity (Optional): {
+     *             @odata.type: String (Required)
+     *         }
+     *     }
+     *     similarity (Optional): {
+     *         @odata.type: String (Required)
+     *     }
+     *     semantic (Optional): {
+     *         defaultConfiguration: String (Optional)
+     *         configurations (Optional): [
+     *              (Optional){
+     *                 name: String (Required)
+     *                 prioritizedFields (Required): {
+     *                     titleField (Optional): {
+     *                         fieldName: String (Required)
+     *                     }
+     *                     prioritizedContentFields (Optional): [
+     *                         (recursive schema, see above)
+     *                     ]
+     *                     prioritizedKeywordsFields (Optional): [
+     *                         (recursive schema, see above)
+     *                     ]
+     *                 }
+     *                 flightingOptIn: Boolean (Optional)
+     *             }
+     *         ]
+     *     }
+     *     vectorSearch (Optional): {
+     *         profiles (Optional): [
+     *              (Optional){
+     *                 name: String (Required)
+     *                 algorithm: String (Required)
+     *                 vectorizer: String (Optional)
+     *                 compression: String (Optional)
+     *             }
+     *         ]
+     *         algorithms (Optional): [
+     *              (Optional){
+     *                 kind: String(hnsw/exhaustiveKnn) (Required)
+     *                 name: String (Required)
+     *             }
+     *         ]
+     *         vectorizers (Optional): [
+     *              (Optional){
+     *                 kind: String(azureOpenAI/customWebApi/aiServicesVision/aml) (Required)
+     *                 name: String (Required)
+     *             }
+     *         ]
+     *         compressions (Optional): [
+     *              (Optional){
+     *                 kind: String(scalarQuantization/binaryQuantization) (Required)
+     *                 name: String (Required)
+     *                 rerankWithOriginalVectors: Boolean (Optional)
+     *                 defaultOversampling: Double (Optional)
+     *                 rescoringOptions (Optional): {
+     *                     enableRescoring: Boolean (Optional)
+     *                     defaultOversampling: Double (Optional)
+     *                     rescoreStorageMethod: String(preserveOriginals/discardOriginals) (Optional)
+     *                 }
+     *                 truncationDimension: Integer (Optional)
+     *             }
+     *         ]
+     *     }
+     *     @odata.etag: String (Optional)
+     * }
+     * }
+     * 
+ * + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return response from a List Indexes request as paginated response with {@link PagedFlux}. + */ + @Generated + @ServiceMethod(returns = ReturnType.COLLECTION) + public PagedFlux list(RequestOptions requestOptions) { + return this.serviceClient.listAsync(requestOptions); + } + + /** + * Creates a new search index or updates an index if it already exists. + *

Query Parameters

+ * + * + * + * + *
Query Parameters
NameTypeRequiredDescription
allowIndexDowntimeBooleanNoAllows 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.
+ * You can add these to a request with {@link RequestOptions#addQueryParam} + *

Header Parameters

+ * + * + * + * + * + *
Header Parameters
NameTypeRequiredDescription
If-MatchStringNoDefines the If-Match condition. The operation will be + * performed only if the ETag on the server matches this value.
If-None-MatchStringNoDefines the If-None-Match condition. The operation will + * be performed only if the ETag on the server does not match this value.
+ * You can add these to a request with {@link RequestOptions#addHeader} + *

Request Body Schema

+ * + *
+     * {@code
+     * {
+     *     name: String (Required)
+     *     fields (Required): [
+     *          (Required){
+     *             name: String (Required)
+     *             type: String(Edm.String/Edm.Int32/Edm.Int64/Edm.Double/Edm.Boolean/Edm.DateTimeOffset/Edm.GeographyPoint/Edm.ComplexType/Edm.Single/Edm.Half/Edm.Int16/Edm.SByte/Edm.Byte) (Required)
+     *             key: Boolean (Optional)
+     *             retrievable: Boolean (Optional)
+     *             stored: Boolean (Optional)
+     *             searchable: Boolean (Optional)
+     *             filterable: Boolean (Optional)
+     *             sortable: Boolean (Optional)
+     *             facetable: Boolean (Optional)
+     *             analyzer: String(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) (Optional)
+     *             searchAnalyzer: String(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) (Optional)
+     *             indexAnalyzer: String(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) (Optional)
+     *             normalizer: String(asciifolding/elision/lowercase/standard/uppercase) (Optional)
+     *             dimensions: Integer (Optional)
+     *             vectorSearchProfile: String (Optional)
+     *             vectorEncoding: String(packedBit) (Optional)
+     *             synonymMaps (Optional): [
+     *                 String (Optional)
+     *             ]
+     *             fields (Optional): [
+     *                 (recursive schema, see above)
+     *             ]
+     *         }
+     *     ]
+     *     scoringProfiles (Optional): [
+     *          (Optional){
+     *             name: String (Required)
+     *             text (Optional): {
+     *                 weights (Required): {
+     *                     String: double (Required)
+     *                 }
+     *             }
+     *             functions (Optional): [
+     *                  (Optional){
+     *                     type: String (Required)
+     *                     fieldName: String (Required)
+     *                     boost: double (Required)
+     *                     interpolation: String(linear/constant/quadratic/logarithmic) (Optional)
+     *                 }
+     *             ]
+     *             functionAggregation: String(sum/average/minimum/maximum/firstMatching) (Optional)
+     *         }
+     *     ]
+     *     defaultScoringProfile: String (Optional)
+     *     corsOptions (Optional): {
+     *         allowedOrigins (Required): [
+     *             String (Required)
+     *         ]
+     *         maxAgeInSeconds: Long (Optional)
+     *     }
+     *     suggesters (Optional): [
+     *          (Optional){
+     *             name: String (Required)
+     *             searchMode: String (Required)
+     *             sourceFields (Required): [
+     *                 String (Required)
+     *             ]
+     *         }
+     *     ]
+     *     analyzers (Optional): [
+     *          (Optional){
+     *             @odata.type: String (Required)
+     *             name: String (Required)
+     *         }
+     *     ]
+     *     tokenizers (Optional): [
+     *          (Optional){
+     *             @odata.type: String (Required)
+     *             name: String (Required)
+     *         }
+     *     ]
+     *     tokenFilters (Optional): [
+     *          (Optional){
+     *             @odata.type: String (Required)
+     *             name: String (Required)
+     *         }
+     *     ]
+     *     charFilters (Optional): [
+     *          (Optional){
+     *             @odata.type: String (Required)
+     *             name: String (Required)
+     *         }
+     *     ]
+     *     normalizers (Optional): [
+     *          (Optional){
+     *             @odata.type: String (Required)
+     *             name: String (Required)
+     *         }
+     *     ]
+     *     encryptionKey (Optional): {
+     *         keyVaultKeyName: String (Required)
+     *         keyVaultKeyVersion: String (Optional)
+     *         keyVaultUri: String (Required)
+     *         accessCredentials (Optional): {
+     *             applicationId: String (Required)
+     *             applicationSecret: String (Optional)
+     *         }
+     *         identity (Optional): {
+     *             @odata.type: String (Required)
+     *         }
+     *     }
+     *     similarity (Optional): {
+     *         @odata.type: String (Required)
+     *     }
+     *     semantic (Optional): {
+     *         defaultConfiguration: String (Optional)
+     *         configurations (Optional): [
+     *              (Optional){
+     *                 name: String (Required)
+     *                 prioritizedFields (Required): {
+     *                     titleField (Optional): {
+     *                         fieldName: String (Required)
+     *                     }
+     *                     prioritizedContentFields (Optional): [
+     *                         (recursive schema, see above)
+     *                     ]
+     *                     prioritizedKeywordsFields (Optional): [
+     *                         (recursive schema, see above)
+     *                     ]
+     *                 }
+     *                 flightingOptIn: Boolean (Optional)
+     *             }
+     *         ]
+     *     }
+     *     vectorSearch (Optional): {
+     *         profiles (Optional): [
+     *              (Optional){
+     *                 name: String (Required)
+     *                 algorithm: String (Required)
+     *                 vectorizer: String (Optional)
+     *                 compression: String (Optional)
+     *             }
+     *         ]
+     *         algorithms (Optional): [
+     *              (Optional){
+     *                 kind: String(hnsw/exhaustiveKnn) (Required)
+     *                 name: String (Required)
+     *             }
+     *         ]
+     *         vectorizers (Optional): [
+     *              (Optional){
+     *                 kind: String(azureOpenAI/customWebApi/aiServicesVision/aml) (Required)
+     *                 name: String (Required)
+     *             }
+     *         ]
+     *         compressions (Optional): [
+     *              (Optional){
+     *                 kind: String(scalarQuantization/binaryQuantization) (Required)
+     *                 name: String (Required)
+     *                 rerankWithOriginalVectors: Boolean (Optional)
+     *                 defaultOversampling: Double (Optional)
+     *                 rescoringOptions (Optional): {
+     *                     enableRescoring: Boolean (Optional)
+     *                     defaultOversampling: Double (Optional)
+     *                     rescoreStorageMethod: String(preserveOriginals/discardOriginals) (Optional)
+     *                 }
+     *                 truncationDimension: Integer (Optional)
+     *             }
+     *         ]
+     *     }
+     *     @odata.etag: String (Optional)
+     * }
+     * }
+     * 
+ * + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     name: String (Required)
+     *     fields (Required): [
+     *          (Required){
+     *             name: String (Required)
+     *             type: String(Edm.String/Edm.Int32/Edm.Int64/Edm.Double/Edm.Boolean/Edm.DateTimeOffset/Edm.GeographyPoint/Edm.ComplexType/Edm.Single/Edm.Half/Edm.Int16/Edm.SByte/Edm.Byte) (Required)
+     *             key: Boolean (Optional)
+     *             retrievable: Boolean (Optional)
+     *             stored: Boolean (Optional)
+     *             searchable: Boolean (Optional)
+     *             filterable: Boolean (Optional)
+     *             sortable: Boolean (Optional)
+     *             facetable: Boolean (Optional)
+     *             analyzer: String(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) (Optional)
+     *             searchAnalyzer: String(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) (Optional)
+     *             indexAnalyzer: String(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) (Optional)
+     *             normalizer: String(asciifolding/elision/lowercase/standard/uppercase) (Optional)
+     *             dimensions: Integer (Optional)
+     *             vectorSearchProfile: String (Optional)
+     *             vectorEncoding: String(packedBit) (Optional)
+     *             synonymMaps (Optional): [
+     *                 String (Optional)
+     *             ]
+     *             fields (Optional): [
+     *                 (recursive schema, see above)
+     *             ]
+     *         }
+     *     ]
+     *     scoringProfiles (Optional): [
+     *          (Optional){
+     *             name: String (Required)
+     *             text (Optional): {
+     *                 weights (Required): {
+     *                     String: double (Required)
+     *                 }
+     *             }
+     *             functions (Optional): [
+     *                  (Optional){
+     *                     type: String (Required)
+     *                     fieldName: String (Required)
+     *                     boost: double (Required)
+     *                     interpolation: String(linear/constant/quadratic/logarithmic) (Optional)
+     *                 }
+     *             ]
+     *             functionAggregation: String(sum/average/minimum/maximum/firstMatching) (Optional)
+     *         }
+     *     ]
+     *     defaultScoringProfile: String (Optional)
+     *     corsOptions (Optional): {
+     *         allowedOrigins (Required): [
+     *             String (Required)
+     *         ]
+     *         maxAgeInSeconds: Long (Optional)
+     *     }
+     *     suggesters (Optional): [
+     *          (Optional){
+     *             name: String (Required)
+     *             searchMode: String (Required)
+     *             sourceFields (Required): [
+     *                 String (Required)
+     *             ]
+     *         }
+     *     ]
+     *     analyzers (Optional): [
+     *          (Optional){
+     *             @odata.type: String (Required)
+     *             name: String (Required)
+     *         }
+     *     ]
+     *     tokenizers (Optional): [
+     *          (Optional){
+     *             @odata.type: String (Required)
+     *             name: String (Required)
+     *         }
+     *     ]
+     *     tokenFilters (Optional): [
+     *          (Optional){
+     *             @odata.type: String (Required)
+     *             name: String (Required)
+     *         }
+     *     ]
+     *     charFilters (Optional): [
+     *          (Optional){
+     *             @odata.type: String (Required)
+     *             name: String (Required)
+     *         }
+     *     ]
+     *     normalizers (Optional): [
+     *          (Optional){
+     *             @odata.type: String (Required)
+     *             name: String (Required)
+     *         }
+     *     ]
+     *     encryptionKey (Optional): {
+     *         keyVaultKeyName: String (Required)
+     *         keyVaultKeyVersion: String (Optional)
+     *         keyVaultUri: String (Required)
+     *         accessCredentials (Optional): {
+     *             applicationId: String (Required)
+     *             applicationSecret: String (Optional)
+     *         }
+     *         identity (Optional): {
+     *             @odata.type: String (Required)
+     *         }
+     *     }
+     *     similarity (Optional): {
+     *         @odata.type: String (Required)
+     *     }
+     *     semantic (Optional): {
+     *         defaultConfiguration: String (Optional)
+     *         configurations (Optional): [
+     *              (Optional){
+     *                 name: String (Required)
+     *                 prioritizedFields (Required): {
+     *                     titleField (Optional): {
+     *                         fieldName: String (Required)
+     *                     }
+     *                     prioritizedContentFields (Optional): [
+     *                         (recursive schema, see above)
+     *                     ]
+     *                     prioritizedKeywordsFields (Optional): [
+     *                         (recursive schema, see above)
+     *                     ]
+     *                 }
+     *                 flightingOptIn: Boolean (Optional)
+     *             }
+     *         ]
+     *     }
+     *     vectorSearch (Optional): {
+     *         profiles (Optional): [
+     *              (Optional){
+     *                 name: String (Required)
+     *                 algorithm: String (Required)
+     *                 vectorizer: String (Optional)
+     *                 compression: String (Optional)
+     *             }
+     *         ]
+     *         algorithms (Optional): [
+     *              (Optional){
+     *                 kind: String(hnsw/exhaustiveKnn) (Required)
+     *                 name: String (Required)
+     *             }
+     *         ]
+     *         vectorizers (Optional): [
+     *              (Optional){
+     *                 kind: String(azureOpenAI/customWebApi/aiServicesVision/aml) (Required)
+     *                 name: String (Required)
+     *             }
+     *         ]
+     *         compressions (Optional): [
+     *              (Optional){
+     *                 kind: String(scalarQuantization/binaryQuantization) (Required)
+     *                 name: String (Required)
+     *                 rerankWithOriginalVectors: Boolean (Optional)
+     *                 defaultOversampling: Double (Optional)
+     *                 rescoringOptions (Optional): {
+     *                     enableRescoring: Boolean (Optional)
+     *                     defaultOversampling: Double (Optional)
+     *                     rescoreStorageMethod: String(preserveOriginals/discardOriginals) (Optional)
+     *                 }
+     *                 truncationDimension: Integer (Optional)
+     *             }
+     *         ]
+     *     }
+     *     @odata.etag: String (Optional)
+     * }
+     * }
+     * 
+ * + * @param indexName The name of the index. + * @param index The definition of the index to create or update. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return represents a search index definition, which describes the fields and search + * behavior of an index along with {@link Response} on successful completion of {@link Mono}. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono> createOrUpdateWithResponse(String indexName, BinaryData index, + RequestOptions requestOptions) { + return this.serviceClient.createOrUpdateWithResponseAsync(indexName, index, requestOptions); + } + + /** + * 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. + *

Header Parameters

+ * + * + * + * + * + *
Header Parameters
NameTypeRequiredDescription
If-MatchStringNoDefines the If-Match condition. The operation will be + * performed only if the ETag on the server matches this value.
If-None-MatchStringNoDefines the If-None-Match condition. The operation will + * be performed only if the ETag on the server does not match this value.
+ * You can add these to a request with {@link RequestOptions#addHeader} + * + * @param indexName The name of the index. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return the {@link Response} on successful completion of {@link Mono}. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono> deleteWithResponse(String indexName, RequestOptions requestOptions) { + return this.serviceClient.deleteWithResponseAsync(indexName, requestOptions); + } + + /** + * Retrieves an index definition. + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     name: String (Required)
+     *     fields (Required): [
+     *          (Required){
+     *             name: String (Required)
+     *             type: String(Edm.String/Edm.Int32/Edm.Int64/Edm.Double/Edm.Boolean/Edm.DateTimeOffset/Edm.GeographyPoint/Edm.ComplexType/Edm.Single/Edm.Half/Edm.Int16/Edm.SByte/Edm.Byte) (Required)
+     *             key: Boolean (Optional)
+     *             retrievable: Boolean (Optional)
+     *             stored: Boolean (Optional)
+     *             searchable: Boolean (Optional)
+     *             filterable: Boolean (Optional)
+     *             sortable: Boolean (Optional)
+     *             facetable: Boolean (Optional)
+     *             analyzer: String(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) (Optional)
+     *             searchAnalyzer: String(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) (Optional)
+     *             indexAnalyzer: String(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) (Optional)
+     *             normalizer: String(asciifolding/elision/lowercase/standard/uppercase) (Optional)
+     *             dimensions: Integer (Optional)
+     *             vectorSearchProfile: String (Optional)
+     *             vectorEncoding: String(packedBit) (Optional)
+     *             synonymMaps (Optional): [
+     *                 String (Optional)
+     *             ]
+     *             fields (Optional): [
+     *                 (recursive schema, see above)
+     *             ]
+     *         }
+     *     ]
+     *     scoringProfiles (Optional): [
+     *          (Optional){
+     *             name: String (Required)
+     *             text (Optional): {
+     *                 weights (Required): {
+     *                     String: double (Required)
+     *                 }
+     *             }
+     *             functions (Optional): [
+     *                  (Optional){
+     *                     type: String (Required)
+     *                     fieldName: String (Required)
+     *                     boost: double (Required)
+     *                     interpolation: String(linear/constant/quadratic/logarithmic) (Optional)
+     *                 }
+     *             ]
+     *             functionAggregation: String(sum/average/minimum/maximum/firstMatching) (Optional)
+     *         }
+     *     ]
+     *     defaultScoringProfile: String (Optional)
+     *     corsOptions (Optional): {
+     *         allowedOrigins (Required): [
+     *             String (Required)
+     *         ]
+     *         maxAgeInSeconds: Long (Optional)
+     *     }
+     *     suggesters (Optional): [
+     *          (Optional){
+     *             name: String (Required)
+     *             searchMode: String (Required)
+     *             sourceFields (Required): [
+     *                 String (Required)
+     *             ]
+     *         }
+     *     ]
+     *     analyzers (Optional): [
+     *          (Optional){
+     *             @odata.type: String (Required)
+     *             name: String (Required)
+     *         }
+     *     ]
+     *     tokenizers (Optional): [
+     *          (Optional){
+     *             @odata.type: String (Required)
+     *             name: String (Required)
+     *         }
+     *     ]
+     *     tokenFilters (Optional): [
+     *          (Optional){
+     *             @odata.type: String (Required)
+     *             name: String (Required)
+     *         }
+     *     ]
+     *     charFilters (Optional): [
+     *          (Optional){
+     *             @odata.type: String (Required)
+     *             name: String (Required)
+     *         }
+     *     ]
+     *     normalizers (Optional): [
+     *          (Optional){
+     *             @odata.type: String (Required)
+     *             name: String (Required)
+     *         }
+     *     ]
+     *     encryptionKey (Optional): {
+     *         keyVaultKeyName: String (Required)
+     *         keyVaultKeyVersion: String (Optional)
+     *         keyVaultUri: String (Required)
+     *         accessCredentials (Optional): {
+     *             applicationId: String (Required)
+     *             applicationSecret: String (Optional)
+     *         }
+     *         identity (Optional): {
+     *             @odata.type: String (Required)
+     *         }
+     *     }
+     *     similarity (Optional): {
+     *         @odata.type: String (Required)
+     *     }
+     *     semantic (Optional): {
+     *         defaultConfiguration: String (Optional)
+     *         configurations (Optional): [
+     *              (Optional){
+     *                 name: String (Required)
+     *                 prioritizedFields (Required): {
+     *                     titleField (Optional): {
+     *                         fieldName: String (Required)
+     *                     }
+     *                     prioritizedContentFields (Optional): [
+     *                         (recursive schema, see above)
+     *                     ]
+     *                     prioritizedKeywordsFields (Optional): [
+     *                         (recursive schema, see above)
+     *                     ]
+     *                 }
+     *                 flightingOptIn: Boolean (Optional)
+     *             }
+     *         ]
+     *     }
+     *     vectorSearch (Optional): {
+     *         profiles (Optional): [
+     *              (Optional){
+     *                 name: String (Required)
+     *                 algorithm: String (Required)
+     *                 vectorizer: String (Optional)
+     *                 compression: String (Optional)
+     *             }
+     *         ]
+     *         algorithms (Optional): [
+     *              (Optional){
+     *                 kind: String(hnsw/exhaustiveKnn) (Required)
+     *                 name: String (Required)
+     *             }
+     *         ]
+     *         vectorizers (Optional): [
+     *              (Optional){
+     *                 kind: String(azureOpenAI/customWebApi/aiServicesVision/aml) (Required)
+     *                 name: String (Required)
+     *             }
+     *         ]
+     *         compressions (Optional): [
+     *              (Optional){
+     *                 kind: String(scalarQuantization/binaryQuantization) (Required)
+     *                 name: String (Required)
+     *                 rerankWithOriginalVectors: Boolean (Optional)
+     *                 defaultOversampling: Double (Optional)
+     *                 rescoringOptions (Optional): {
+     *                     enableRescoring: Boolean (Optional)
+     *                     defaultOversampling: Double (Optional)
+     *                     rescoreStorageMethod: String(preserveOriginals/discardOriginals) (Optional)
+     *                 }
+     *                 truncationDimension: Integer (Optional)
+     *             }
+     *         ]
+     *     }
+     *     @odata.etag: String (Optional)
+     * }
+     * }
+     * 
+ * + * @param indexName The name of the index. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return represents a search index definition, which describes the fields and search + * behavior of an index along with {@link Response} on successful completion of {@link Mono}. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono> getWithResponse(String indexName, RequestOptions requestOptions) { + return this.serviceClient.getWithResponseAsync(indexName, requestOptions); + } + + /** + * Returns statistics for the given index, including a document count and storage + * usage. + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     documentCount: long (Required)
+     *     storageSize: long (Required)
+     *     vectorIndexSize: long (Required)
+     * }
+     * }
+     * 
+ * + * @param indexName The name of the index. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return statistics for a given index along with {@link Response} on successful completion of {@link Mono}. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono> getStatisticsWithResponse(String indexName, RequestOptions requestOptions) { + return this.serviceClient.getStatisticsWithResponseAsync(indexName, requestOptions); + } + + /** + * Shows how an analyzer breaks text into tokens. + *

Request Body Schema

+ * + *
+     * {@code
+     * {
+     *     text: String (Required)
+     *     analyzer: String(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) (Optional)
+     *     tokenizer: String(classic/edgeNGram/keyword_v2/letter/lowercase/microsoft_language_tokenizer/microsoft_language_stemming_tokenizer/nGram/path_hierarchy_v2/pattern/standard_v2/uax_url_email/whitespace) (Optional)
+     *     normalizer: String(asciifolding/elision/lowercase/standard/uppercase) (Optional)
+     *     tokenFilters (Optional): [
+     *         String(arabic_normalization/apostrophe/asciifolding/cjk_bigram/cjk_width/classic/common_grams/edgeNGram_v2/elision/german_normalization/hindi_normalization/indic_normalization/keyword_repeat/kstem/length/limit/lowercase/nGram_v2/persian_normalization/phonetic/porter_stem/reverse/scandinavian_normalization/scandinavian_folding/shingle/snowball/sorani_normalization/stemmer/stopwords/trim/truncate/unique/uppercase/word_delimiter) (Optional)
+     *     ]
+     *     charFilters (Optional): [
+     *         String(html_strip) (Optional)
+     *     ]
+     * }
+     * }
+     * 
+ * + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     tokens (Required): [
+     *          (Required){
+     *             token: String (Required)
+     *             startOffset: int (Required)
+     *             endOffset: int (Required)
+     *             position: int (Required)
+     *         }
+     *     ]
+     * }
+     * }
+     * 
+ * + * @param indexName The name of the index. + * @param request The text and analyzer or analysis components to test. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return the result of testing an analyzer on text along with {@link Response} on successful completion of + * {@link Mono}. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono> analyzeWithResponse(String indexName, BinaryData request, + RequestOptions requestOptions) { + return this.serviceClient.analyzeWithResponseAsync(indexName, request, requestOptions); + } + + /** + * Creates a new search index. + * + * @param index The definition of the index to create. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return represents a search index definition, which describes the fields and search + * behavior of an index on successful completion of {@link Mono}. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono create(SearchIndex index) { + // Generated convenience method for createWithResponse + RequestOptions requestOptions = new RequestOptions(); + return createWithResponse(BinaryData.fromObject(index), requestOptions).flatMap(FluxUtil::toMono) + .map(protocolMethodData -> protocolMethodData.toObject(SearchIndex.class)); + } + + /** + * Lists all indexes available for a search service. + * + * @param 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. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return response from a List Indexes request as paginated response with {@link PagedFlux}. + */ + @Generated + @ServiceMethod(returns = ReturnType.COLLECTION) + public PagedFlux list(String select) { + // Generated convenience method for list + RequestOptions requestOptions = new RequestOptions(); + if (select != null) { + requestOptions.addQueryParam("$select", select, false); + } + PagedFlux pagedFluxResponse = list(requestOptions); + return PagedFlux.create(() -> (continuationTokenParam, pageSizeParam) -> { + Flux> flux = (continuationTokenParam == null) + ? pagedFluxResponse.byPage().take(1) + : pagedFluxResponse.byPage(continuationTokenParam).take(1); + return flux.map(pagedResponse -> new PagedResponseBase(pagedResponse.getRequest(), + pagedResponse.getStatusCode(), pagedResponse.getHeaders(), + pagedResponse.getValue() + .stream() + .map(protocolMethodData -> protocolMethodData.toObject(SearchIndex.class)) + .collect(Collectors.toList()), + pagedResponse.getContinuationToken(), null)); + }); + } + + /** + * Lists all indexes available for a search service. + * + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return response from a List Indexes request as paginated response with {@link PagedFlux}. + */ + @Generated + @ServiceMethod(returns = ReturnType.COLLECTION) + public PagedFlux list() { + // Generated convenience method for list + RequestOptions requestOptions = new RequestOptions(); + PagedFlux pagedFluxResponse = list(requestOptions); + return PagedFlux.create(() -> (continuationTokenParam, pageSizeParam) -> { + Flux> flux = (continuationTokenParam == null) + ? pagedFluxResponse.byPage().take(1) + : pagedFluxResponse.byPage(continuationTokenParam).take(1); + return flux.map(pagedResponse -> new PagedResponseBase(pagedResponse.getRequest(), + pagedResponse.getStatusCode(), pagedResponse.getHeaders(), + pagedResponse.getValue() + .stream() + .map(protocolMethodData -> protocolMethodData.toObject(SearchIndex.class)) + .collect(Collectors.toList()), + pagedResponse.getContinuationToken(), null)); + }); + } + + /** + * Creates a new search index or updates an index if it already exists. + * + * @param indexName The name of the index. + * @param index The definition of the index to create or update. + * @param allowIndexDowntime 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. + * @param matchConditions Specifies HTTP options for conditional requests. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return represents a search index definition, which describes the fields and search + * behavior of an index on successful completion of {@link Mono}. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono createOrUpdate(String indexName, SearchIndex index, Boolean allowIndexDowntime, + MatchConditions matchConditions) { + // Generated convenience method for createOrUpdateWithResponse + RequestOptions requestOptions = new RequestOptions(); + String ifMatch = matchConditions == null ? null : matchConditions.getIfMatch(); + String ifNoneMatch = matchConditions == null ? null : matchConditions.getIfNoneMatch(); + if (allowIndexDowntime != null) { + requestOptions.addQueryParam("allowIndexDowntime", String.valueOf(allowIndexDowntime), false); + } + if (ifMatch != null) { + requestOptions.setHeader(HttpHeaderName.IF_MATCH, ifMatch); + } + if (ifNoneMatch != null) { + requestOptions.setHeader(HttpHeaderName.IF_NONE_MATCH, ifNoneMatch); + } + return createOrUpdateWithResponse(indexName, BinaryData.fromObject(index), requestOptions) + .flatMap(FluxUtil::toMono) + .map(protocolMethodData -> protocolMethodData.toObject(SearchIndex.class)); + } + + /** + * Creates a new search index or updates an index if it already exists. + * + * @param indexName The name of the index. + * @param index The definition of the index to create or update. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return represents a search index definition, which describes the fields and search + * behavior of an index on successful completion of {@link Mono}. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono createOrUpdate(String indexName, SearchIndex index) { + // Generated convenience method for createOrUpdateWithResponse + RequestOptions requestOptions = new RequestOptions(); + return createOrUpdateWithResponse(indexName, BinaryData.fromObject(index), requestOptions) + .flatMap(FluxUtil::toMono) + .map(protocolMethodData -> protocolMethodData.toObject(SearchIndex.class)); + } + + /** + * 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 indexName The name of the index. + * @param matchConditions Specifies HTTP options for conditional requests. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return A {@link Mono} that completes when a successful response is received. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono delete(String indexName, MatchConditions matchConditions) { + // Generated convenience method for deleteWithResponse + RequestOptions requestOptions = new RequestOptions(); + String ifMatch = matchConditions == null ? null : matchConditions.getIfMatch(); + String ifNoneMatch = matchConditions == null ? null : matchConditions.getIfNoneMatch(); + if (ifMatch != null) { + requestOptions.setHeader(HttpHeaderName.IF_MATCH, ifMatch); + } + if (ifNoneMatch != null) { + requestOptions.setHeader(HttpHeaderName.IF_NONE_MATCH, ifNoneMatch); + } + return deleteWithResponse(indexName, requestOptions).flatMap(FluxUtil::toMono); + } + + /** + * 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 indexName The name of the index. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return A {@link Mono} that completes when a successful response is received. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono delete(String indexName) { + // Generated convenience method for deleteWithResponse + RequestOptions requestOptions = new RequestOptions(); + return deleteWithResponse(indexName, requestOptions).flatMap(FluxUtil::toMono); + } + + /** + * Retrieves an index definition. + * + * @param indexName The name of the index. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return represents a search index definition, which describes the fields and search + * behavior of an index on successful completion of {@link Mono}. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono get(String indexName) { + // Generated convenience method for getWithResponse + RequestOptions requestOptions = new RequestOptions(); + return getWithResponse(indexName, requestOptions).flatMap(FluxUtil::toMono) + .map(protocolMethodData -> protocolMethodData.toObject(SearchIndex.class)); + } + + /** + * Returns statistics for the given index, including a document count and storage + * usage. + * + * @param indexName The name of the index. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return statistics for a given index on successful completion of {@link Mono}. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono getStatistics(String indexName) { + // Generated convenience method for getStatisticsWithResponse + RequestOptions requestOptions = new RequestOptions(); + return getStatisticsWithResponse(indexName, requestOptions).flatMap(FluxUtil::toMono) + .map(protocolMethodData -> protocolMethodData.toObject(GetIndexStatisticsResult.class)); + } + + /** + * Shows how an analyzer breaks text into tokens. + * + * @param indexName The name of the index. + * @param request The text and analyzer or analysis components to test. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the result of testing an analyzer on text on successful completion of {@link Mono}. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono analyze(String indexName, AnalyzeRequest request) { + // Generated convenience method for analyzeWithResponse + RequestOptions requestOptions = new RequestOptions(); + return analyzeWithResponse(indexName, BinaryData.fromObject(request), requestOptions).flatMap(FluxUtil::toMono) + .map(protocolMethodData -> protocolMethodData.toObject(AnalyzeResult.class)); + } +} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/IndexesClient.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/IndexesClient.java new file mode 100644 index 000000000000..2078e7d48b44 --- /dev/null +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/IndexesClient.java @@ -0,0 +1,1536 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.search.documents; + +import com.azure.core.annotation.Generated; +import com.azure.core.annotation.ReturnType; +import com.azure.core.annotation.ServiceClient; +import com.azure.core.annotation.ServiceMethod; +import com.azure.core.exception.ClientAuthenticationException; +import com.azure.core.exception.HttpResponseException; +import com.azure.core.exception.ResourceModifiedException; +import com.azure.core.exception.ResourceNotFoundException; +import com.azure.core.http.HttpHeaderName; +import com.azure.core.http.MatchConditions; +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.http.rest.RequestOptions; +import com.azure.core.http.rest.Response; +import com.azure.core.util.BinaryData; +import com.azure.search.documents.implementation.IndexesImpl; +import com.azure.search.documents.models.AnalyzeRequest; +import com.azure.search.documents.models.AnalyzeResult; +import com.azure.search.documents.models.GetIndexStatisticsResult; +import com.azure.search.documents.models.SearchIndex; + +/** + * Initializes a new instance of the synchronous SearchClient type. + */ +@ServiceClient(builder = SearchClientBuilder.class) +public final class IndexesClient { + @Generated + private final IndexesImpl serviceClient; + + /** + * Initializes an instance of IndexesClient class. + * + * @param serviceClient the service client implementation. + */ + @Generated + IndexesClient(IndexesImpl serviceClient) { + this.serviceClient = serviceClient; + } + + /** + * Creates a new search index. + *

Request Body Schema

+ * + *
+     * {@code
+     * {
+     *     name: String (Required)
+     *     fields (Required): [
+     *          (Required){
+     *             name: String (Required)
+     *             type: String(Edm.String/Edm.Int32/Edm.Int64/Edm.Double/Edm.Boolean/Edm.DateTimeOffset/Edm.GeographyPoint/Edm.ComplexType/Edm.Single/Edm.Half/Edm.Int16/Edm.SByte/Edm.Byte) (Required)
+     *             key: Boolean (Optional)
+     *             retrievable: Boolean (Optional)
+     *             stored: Boolean (Optional)
+     *             searchable: Boolean (Optional)
+     *             filterable: Boolean (Optional)
+     *             sortable: Boolean (Optional)
+     *             facetable: Boolean (Optional)
+     *             analyzer: String(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) (Optional)
+     *             searchAnalyzer: String(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) (Optional)
+     *             indexAnalyzer: String(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) (Optional)
+     *             normalizer: String(asciifolding/elision/lowercase/standard/uppercase) (Optional)
+     *             dimensions: Integer (Optional)
+     *             vectorSearchProfile: String (Optional)
+     *             vectorEncoding: String(packedBit) (Optional)
+     *             synonymMaps (Optional): [
+     *                 String (Optional)
+     *             ]
+     *             fields (Optional): [
+     *                 (recursive schema, see above)
+     *             ]
+     *         }
+     *     ]
+     *     scoringProfiles (Optional): [
+     *          (Optional){
+     *             name: String (Required)
+     *             text (Optional): {
+     *                 weights (Required): {
+     *                     String: double (Required)
+     *                 }
+     *             }
+     *             functions (Optional): [
+     *                  (Optional){
+     *                     type: String (Required)
+     *                     fieldName: String (Required)
+     *                     boost: double (Required)
+     *                     interpolation: String(linear/constant/quadratic/logarithmic) (Optional)
+     *                 }
+     *             ]
+     *             functionAggregation: String(sum/average/minimum/maximum/firstMatching) (Optional)
+     *         }
+     *     ]
+     *     defaultScoringProfile: String (Optional)
+     *     corsOptions (Optional): {
+     *         allowedOrigins (Required): [
+     *             String (Required)
+     *         ]
+     *         maxAgeInSeconds: Long (Optional)
+     *     }
+     *     suggesters (Optional): [
+     *          (Optional){
+     *             name: String (Required)
+     *             searchMode: String (Required)
+     *             sourceFields (Required): [
+     *                 String (Required)
+     *             ]
+     *         }
+     *     ]
+     *     analyzers (Optional): [
+     *          (Optional){
+     *             @odata.type: String (Required)
+     *             name: String (Required)
+     *         }
+     *     ]
+     *     tokenizers (Optional): [
+     *          (Optional){
+     *             @odata.type: String (Required)
+     *             name: String (Required)
+     *         }
+     *     ]
+     *     tokenFilters (Optional): [
+     *          (Optional){
+     *             @odata.type: String (Required)
+     *             name: String (Required)
+     *         }
+     *     ]
+     *     charFilters (Optional): [
+     *          (Optional){
+     *             @odata.type: String (Required)
+     *             name: String (Required)
+     *         }
+     *     ]
+     *     normalizers (Optional): [
+     *          (Optional){
+     *             @odata.type: String (Required)
+     *             name: String (Required)
+     *         }
+     *     ]
+     *     encryptionKey (Optional): {
+     *         keyVaultKeyName: String (Required)
+     *         keyVaultKeyVersion: String (Optional)
+     *         keyVaultUri: String (Required)
+     *         accessCredentials (Optional): {
+     *             applicationId: String (Required)
+     *             applicationSecret: String (Optional)
+     *         }
+     *         identity (Optional): {
+     *             @odata.type: String (Required)
+     *         }
+     *     }
+     *     similarity (Optional): {
+     *         @odata.type: String (Required)
+     *     }
+     *     semantic (Optional): {
+     *         defaultConfiguration: String (Optional)
+     *         configurations (Optional): [
+     *              (Optional){
+     *                 name: String (Required)
+     *                 prioritizedFields (Required): {
+     *                     titleField (Optional): {
+     *                         fieldName: String (Required)
+     *                     }
+     *                     prioritizedContentFields (Optional): [
+     *                         (recursive schema, see above)
+     *                     ]
+     *                     prioritizedKeywordsFields (Optional): [
+     *                         (recursive schema, see above)
+     *                     ]
+     *                 }
+     *                 flightingOptIn: Boolean (Optional)
+     *             }
+     *         ]
+     *     }
+     *     vectorSearch (Optional): {
+     *         profiles (Optional): [
+     *              (Optional){
+     *                 name: String (Required)
+     *                 algorithm: String (Required)
+     *                 vectorizer: String (Optional)
+     *                 compression: String (Optional)
+     *             }
+     *         ]
+     *         algorithms (Optional): [
+     *              (Optional){
+     *                 kind: String(hnsw/exhaustiveKnn) (Required)
+     *                 name: String (Required)
+     *             }
+     *         ]
+     *         vectorizers (Optional): [
+     *              (Optional){
+     *                 kind: String(azureOpenAI/customWebApi/aiServicesVision/aml) (Required)
+     *                 name: String (Required)
+     *             }
+     *         ]
+     *         compressions (Optional): [
+     *              (Optional){
+     *                 kind: String(scalarQuantization/binaryQuantization) (Required)
+     *                 name: String (Required)
+     *                 rerankWithOriginalVectors: Boolean (Optional)
+     *                 defaultOversampling: Double (Optional)
+     *                 rescoringOptions (Optional): {
+     *                     enableRescoring: Boolean (Optional)
+     *                     defaultOversampling: Double (Optional)
+     *                     rescoreStorageMethod: String(preserveOriginals/discardOriginals) (Optional)
+     *                 }
+     *                 truncationDimension: Integer (Optional)
+     *             }
+     *         ]
+     *     }
+     *     @odata.etag: String (Optional)
+     * }
+     * }
+     * 
+ * + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     name: String (Required)
+     *     fields (Required): [
+     *          (Required){
+     *             name: String (Required)
+     *             type: String(Edm.String/Edm.Int32/Edm.Int64/Edm.Double/Edm.Boolean/Edm.DateTimeOffset/Edm.GeographyPoint/Edm.ComplexType/Edm.Single/Edm.Half/Edm.Int16/Edm.SByte/Edm.Byte) (Required)
+     *             key: Boolean (Optional)
+     *             retrievable: Boolean (Optional)
+     *             stored: Boolean (Optional)
+     *             searchable: Boolean (Optional)
+     *             filterable: Boolean (Optional)
+     *             sortable: Boolean (Optional)
+     *             facetable: Boolean (Optional)
+     *             analyzer: String(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) (Optional)
+     *             searchAnalyzer: String(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) (Optional)
+     *             indexAnalyzer: String(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) (Optional)
+     *             normalizer: String(asciifolding/elision/lowercase/standard/uppercase) (Optional)
+     *             dimensions: Integer (Optional)
+     *             vectorSearchProfile: String (Optional)
+     *             vectorEncoding: String(packedBit) (Optional)
+     *             synonymMaps (Optional): [
+     *                 String (Optional)
+     *             ]
+     *             fields (Optional): [
+     *                 (recursive schema, see above)
+     *             ]
+     *         }
+     *     ]
+     *     scoringProfiles (Optional): [
+     *          (Optional){
+     *             name: String (Required)
+     *             text (Optional): {
+     *                 weights (Required): {
+     *                     String: double (Required)
+     *                 }
+     *             }
+     *             functions (Optional): [
+     *                  (Optional){
+     *                     type: String (Required)
+     *                     fieldName: String (Required)
+     *                     boost: double (Required)
+     *                     interpolation: String(linear/constant/quadratic/logarithmic) (Optional)
+     *                 }
+     *             ]
+     *             functionAggregation: String(sum/average/minimum/maximum/firstMatching) (Optional)
+     *         }
+     *     ]
+     *     defaultScoringProfile: String (Optional)
+     *     corsOptions (Optional): {
+     *         allowedOrigins (Required): [
+     *             String (Required)
+     *         ]
+     *         maxAgeInSeconds: Long (Optional)
+     *     }
+     *     suggesters (Optional): [
+     *          (Optional){
+     *             name: String (Required)
+     *             searchMode: String (Required)
+     *             sourceFields (Required): [
+     *                 String (Required)
+     *             ]
+     *         }
+     *     ]
+     *     analyzers (Optional): [
+     *          (Optional){
+     *             @odata.type: String (Required)
+     *             name: String (Required)
+     *         }
+     *     ]
+     *     tokenizers (Optional): [
+     *          (Optional){
+     *             @odata.type: String (Required)
+     *             name: String (Required)
+     *         }
+     *     ]
+     *     tokenFilters (Optional): [
+     *          (Optional){
+     *             @odata.type: String (Required)
+     *             name: String (Required)
+     *         }
+     *     ]
+     *     charFilters (Optional): [
+     *          (Optional){
+     *             @odata.type: String (Required)
+     *             name: String (Required)
+     *         }
+     *     ]
+     *     normalizers (Optional): [
+     *          (Optional){
+     *             @odata.type: String (Required)
+     *             name: String (Required)
+     *         }
+     *     ]
+     *     encryptionKey (Optional): {
+     *         keyVaultKeyName: String (Required)
+     *         keyVaultKeyVersion: String (Optional)
+     *         keyVaultUri: String (Required)
+     *         accessCredentials (Optional): {
+     *             applicationId: String (Required)
+     *             applicationSecret: String (Optional)
+     *         }
+     *         identity (Optional): {
+     *             @odata.type: String (Required)
+     *         }
+     *     }
+     *     similarity (Optional): {
+     *         @odata.type: String (Required)
+     *     }
+     *     semantic (Optional): {
+     *         defaultConfiguration: String (Optional)
+     *         configurations (Optional): [
+     *              (Optional){
+     *                 name: String (Required)
+     *                 prioritizedFields (Required): {
+     *                     titleField (Optional): {
+     *                         fieldName: String (Required)
+     *                     }
+     *                     prioritizedContentFields (Optional): [
+     *                         (recursive schema, see above)
+     *                     ]
+     *                     prioritizedKeywordsFields (Optional): [
+     *                         (recursive schema, see above)
+     *                     ]
+     *                 }
+     *                 flightingOptIn: Boolean (Optional)
+     *             }
+     *         ]
+     *     }
+     *     vectorSearch (Optional): {
+     *         profiles (Optional): [
+     *              (Optional){
+     *                 name: String (Required)
+     *                 algorithm: String (Required)
+     *                 vectorizer: String (Optional)
+     *                 compression: String (Optional)
+     *             }
+     *         ]
+     *         algorithms (Optional): [
+     *              (Optional){
+     *                 kind: String(hnsw/exhaustiveKnn) (Required)
+     *                 name: String (Required)
+     *             }
+     *         ]
+     *         vectorizers (Optional): [
+     *              (Optional){
+     *                 kind: String(azureOpenAI/customWebApi/aiServicesVision/aml) (Required)
+     *                 name: String (Required)
+     *             }
+     *         ]
+     *         compressions (Optional): [
+     *              (Optional){
+     *                 kind: String(scalarQuantization/binaryQuantization) (Required)
+     *                 name: String (Required)
+     *                 rerankWithOriginalVectors: Boolean (Optional)
+     *                 defaultOversampling: Double (Optional)
+     *                 rescoringOptions (Optional): {
+     *                     enableRescoring: Boolean (Optional)
+     *                     defaultOversampling: Double (Optional)
+     *                     rescoreStorageMethod: String(preserveOriginals/discardOriginals) (Optional)
+     *                 }
+     *                 truncationDimension: Integer (Optional)
+     *             }
+     *         ]
+     *     }
+     *     @odata.etag: String (Optional)
+     * }
+     * }
+     * 
+ * + * @param index The definition of the index to create. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return represents a search index definition, which describes the fields and search + * behavior of an index along with {@link Response}. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public Response createWithResponse(BinaryData index, RequestOptions requestOptions) { + return this.serviceClient.createWithResponse(index, requestOptions); + } + + /** + * Lists all indexes available for a search service. + *

Query Parameters

+ * + * + * + * + *
Query Parameters
NameTypeRequiredDescription
$selectStringNoSelects 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.
+ * You can add these to a request with {@link RequestOptions#addQueryParam} + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     name: String (Required)
+     *     fields (Required): [
+     *          (Required){
+     *             name: String (Required)
+     *             type: String(Edm.String/Edm.Int32/Edm.Int64/Edm.Double/Edm.Boolean/Edm.DateTimeOffset/Edm.GeographyPoint/Edm.ComplexType/Edm.Single/Edm.Half/Edm.Int16/Edm.SByte/Edm.Byte) (Required)
+     *             key: Boolean (Optional)
+     *             retrievable: Boolean (Optional)
+     *             stored: Boolean (Optional)
+     *             searchable: Boolean (Optional)
+     *             filterable: Boolean (Optional)
+     *             sortable: Boolean (Optional)
+     *             facetable: Boolean (Optional)
+     *             analyzer: String(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) (Optional)
+     *             searchAnalyzer: String(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) (Optional)
+     *             indexAnalyzer: String(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) (Optional)
+     *             normalizer: String(asciifolding/elision/lowercase/standard/uppercase) (Optional)
+     *             dimensions: Integer (Optional)
+     *             vectorSearchProfile: String (Optional)
+     *             vectorEncoding: String(packedBit) (Optional)
+     *             synonymMaps (Optional): [
+     *                 String (Optional)
+     *             ]
+     *             fields (Optional): [
+     *                 (recursive schema, see above)
+     *             ]
+     *         }
+     *     ]
+     *     scoringProfiles (Optional): [
+     *          (Optional){
+     *             name: String (Required)
+     *             text (Optional): {
+     *                 weights (Required): {
+     *                     String: double (Required)
+     *                 }
+     *             }
+     *             functions (Optional): [
+     *                  (Optional){
+     *                     type: String (Required)
+     *                     fieldName: String (Required)
+     *                     boost: double (Required)
+     *                     interpolation: String(linear/constant/quadratic/logarithmic) (Optional)
+     *                 }
+     *             ]
+     *             functionAggregation: String(sum/average/minimum/maximum/firstMatching) (Optional)
+     *         }
+     *     ]
+     *     defaultScoringProfile: String (Optional)
+     *     corsOptions (Optional): {
+     *         allowedOrigins (Required): [
+     *             String (Required)
+     *         ]
+     *         maxAgeInSeconds: Long (Optional)
+     *     }
+     *     suggesters (Optional): [
+     *          (Optional){
+     *             name: String (Required)
+     *             searchMode: String (Required)
+     *             sourceFields (Required): [
+     *                 String (Required)
+     *             ]
+     *         }
+     *     ]
+     *     analyzers (Optional): [
+     *          (Optional){
+     *             @odata.type: String (Required)
+     *             name: String (Required)
+     *         }
+     *     ]
+     *     tokenizers (Optional): [
+     *          (Optional){
+     *             @odata.type: String (Required)
+     *             name: String (Required)
+     *         }
+     *     ]
+     *     tokenFilters (Optional): [
+     *          (Optional){
+     *             @odata.type: String (Required)
+     *             name: String (Required)
+     *         }
+     *     ]
+     *     charFilters (Optional): [
+     *          (Optional){
+     *             @odata.type: String (Required)
+     *             name: String (Required)
+     *         }
+     *     ]
+     *     normalizers (Optional): [
+     *          (Optional){
+     *             @odata.type: String (Required)
+     *             name: String (Required)
+     *         }
+     *     ]
+     *     encryptionKey (Optional): {
+     *         keyVaultKeyName: String (Required)
+     *         keyVaultKeyVersion: String (Optional)
+     *         keyVaultUri: String (Required)
+     *         accessCredentials (Optional): {
+     *             applicationId: String (Required)
+     *             applicationSecret: String (Optional)
+     *         }
+     *         identity (Optional): {
+     *             @odata.type: String (Required)
+     *         }
+     *     }
+     *     similarity (Optional): {
+     *         @odata.type: String (Required)
+     *     }
+     *     semantic (Optional): {
+     *         defaultConfiguration: String (Optional)
+     *         configurations (Optional): [
+     *              (Optional){
+     *                 name: String (Required)
+     *                 prioritizedFields (Required): {
+     *                     titleField (Optional): {
+     *                         fieldName: String (Required)
+     *                     }
+     *                     prioritizedContentFields (Optional): [
+     *                         (recursive schema, see above)
+     *                     ]
+     *                     prioritizedKeywordsFields (Optional): [
+     *                         (recursive schema, see above)
+     *                     ]
+     *                 }
+     *                 flightingOptIn: Boolean (Optional)
+     *             }
+     *         ]
+     *     }
+     *     vectorSearch (Optional): {
+     *         profiles (Optional): [
+     *              (Optional){
+     *                 name: String (Required)
+     *                 algorithm: String (Required)
+     *                 vectorizer: String (Optional)
+     *                 compression: String (Optional)
+     *             }
+     *         ]
+     *         algorithms (Optional): [
+     *              (Optional){
+     *                 kind: String(hnsw/exhaustiveKnn) (Required)
+     *                 name: String (Required)
+     *             }
+     *         ]
+     *         vectorizers (Optional): [
+     *              (Optional){
+     *                 kind: String(azureOpenAI/customWebApi/aiServicesVision/aml) (Required)
+     *                 name: String (Required)
+     *             }
+     *         ]
+     *         compressions (Optional): [
+     *              (Optional){
+     *                 kind: String(scalarQuantization/binaryQuantization) (Required)
+     *                 name: String (Required)
+     *                 rerankWithOriginalVectors: Boolean (Optional)
+     *                 defaultOversampling: Double (Optional)
+     *                 rescoringOptions (Optional): {
+     *                     enableRescoring: Boolean (Optional)
+     *                     defaultOversampling: Double (Optional)
+     *                     rescoreStorageMethod: String(preserveOriginals/discardOriginals) (Optional)
+     *                 }
+     *                 truncationDimension: Integer (Optional)
+     *             }
+     *         ]
+     *     }
+     *     @odata.etag: String (Optional)
+     * }
+     * }
+     * 
+ * + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return response from a List Indexes request as paginated response with {@link PagedIterable}. + */ + @Generated + @ServiceMethod(returns = ReturnType.COLLECTION) + public PagedIterable list(RequestOptions requestOptions) { + return this.serviceClient.list(requestOptions); + } + + /** + * Creates a new search index or updates an index if it already exists. + *

Query Parameters

+ * + * + * + * + *
Query Parameters
NameTypeRequiredDescription
allowIndexDowntimeBooleanNoAllows 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.
+ * You can add these to a request with {@link RequestOptions#addQueryParam} + *

Header Parameters

+ * + * + * + * + * + *
Header Parameters
NameTypeRequiredDescription
If-MatchStringNoDefines the If-Match condition. The operation will be + * performed only if the ETag on the server matches this value.
If-None-MatchStringNoDefines the If-None-Match condition. The operation will + * be performed only if the ETag on the server does not match this value.
+ * You can add these to a request with {@link RequestOptions#addHeader} + *

Request Body Schema

+ * + *
+     * {@code
+     * {
+     *     name: String (Required)
+     *     fields (Required): [
+     *          (Required){
+     *             name: String (Required)
+     *             type: String(Edm.String/Edm.Int32/Edm.Int64/Edm.Double/Edm.Boolean/Edm.DateTimeOffset/Edm.GeographyPoint/Edm.ComplexType/Edm.Single/Edm.Half/Edm.Int16/Edm.SByte/Edm.Byte) (Required)
+     *             key: Boolean (Optional)
+     *             retrievable: Boolean (Optional)
+     *             stored: Boolean (Optional)
+     *             searchable: Boolean (Optional)
+     *             filterable: Boolean (Optional)
+     *             sortable: Boolean (Optional)
+     *             facetable: Boolean (Optional)
+     *             analyzer: String(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) (Optional)
+     *             searchAnalyzer: String(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) (Optional)
+     *             indexAnalyzer: String(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) (Optional)
+     *             normalizer: String(asciifolding/elision/lowercase/standard/uppercase) (Optional)
+     *             dimensions: Integer (Optional)
+     *             vectorSearchProfile: String (Optional)
+     *             vectorEncoding: String(packedBit) (Optional)
+     *             synonymMaps (Optional): [
+     *                 String (Optional)
+     *             ]
+     *             fields (Optional): [
+     *                 (recursive schema, see above)
+     *             ]
+     *         }
+     *     ]
+     *     scoringProfiles (Optional): [
+     *          (Optional){
+     *             name: String (Required)
+     *             text (Optional): {
+     *                 weights (Required): {
+     *                     String: double (Required)
+     *                 }
+     *             }
+     *             functions (Optional): [
+     *                  (Optional){
+     *                     type: String (Required)
+     *                     fieldName: String (Required)
+     *                     boost: double (Required)
+     *                     interpolation: String(linear/constant/quadratic/logarithmic) (Optional)
+     *                 }
+     *             ]
+     *             functionAggregation: String(sum/average/minimum/maximum/firstMatching) (Optional)
+     *         }
+     *     ]
+     *     defaultScoringProfile: String (Optional)
+     *     corsOptions (Optional): {
+     *         allowedOrigins (Required): [
+     *             String (Required)
+     *         ]
+     *         maxAgeInSeconds: Long (Optional)
+     *     }
+     *     suggesters (Optional): [
+     *          (Optional){
+     *             name: String (Required)
+     *             searchMode: String (Required)
+     *             sourceFields (Required): [
+     *                 String (Required)
+     *             ]
+     *         }
+     *     ]
+     *     analyzers (Optional): [
+     *          (Optional){
+     *             @odata.type: String (Required)
+     *             name: String (Required)
+     *         }
+     *     ]
+     *     tokenizers (Optional): [
+     *          (Optional){
+     *             @odata.type: String (Required)
+     *             name: String (Required)
+     *         }
+     *     ]
+     *     tokenFilters (Optional): [
+     *          (Optional){
+     *             @odata.type: String (Required)
+     *             name: String (Required)
+     *         }
+     *     ]
+     *     charFilters (Optional): [
+     *          (Optional){
+     *             @odata.type: String (Required)
+     *             name: String (Required)
+     *         }
+     *     ]
+     *     normalizers (Optional): [
+     *          (Optional){
+     *             @odata.type: String (Required)
+     *             name: String (Required)
+     *         }
+     *     ]
+     *     encryptionKey (Optional): {
+     *         keyVaultKeyName: String (Required)
+     *         keyVaultKeyVersion: String (Optional)
+     *         keyVaultUri: String (Required)
+     *         accessCredentials (Optional): {
+     *             applicationId: String (Required)
+     *             applicationSecret: String (Optional)
+     *         }
+     *         identity (Optional): {
+     *             @odata.type: String (Required)
+     *         }
+     *     }
+     *     similarity (Optional): {
+     *         @odata.type: String (Required)
+     *     }
+     *     semantic (Optional): {
+     *         defaultConfiguration: String (Optional)
+     *         configurations (Optional): [
+     *              (Optional){
+     *                 name: String (Required)
+     *                 prioritizedFields (Required): {
+     *                     titleField (Optional): {
+     *                         fieldName: String (Required)
+     *                     }
+     *                     prioritizedContentFields (Optional): [
+     *                         (recursive schema, see above)
+     *                     ]
+     *                     prioritizedKeywordsFields (Optional): [
+     *                         (recursive schema, see above)
+     *                     ]
+     *                 }
+     *                 flightingOptIn: Boolean (Optional)
+     *             }
+     *         ]
+     *     }
+     *     vectorSearch (Optional): {
+     *         profiles (Optional): [
+     *              (Optional){
+     *                 name: String (Required)
+     *                 algorithm: String (Required)
+     *                 vectorizer: String (Optional)
+     *                 compression: String (Optional)
+     *             }
+     *         ]
+     *         algorithms (Optional): [
+     *              (Optional){
+     *                 kind: String(hnsw/exhaustiveKnn) (Required)
+     *                 name: String (Required)
+     *             }
+     *         ]
+     *         vectorizers (Optional): [
+     *              (Optional){
+     *                 kind: String(azureOpenAI/customWebApi/aiServicesVision/aml) (Required)
+     *                 name: String (Required)
+     *             }
+     *         ]
+     *         compressions (Optional): [
+     *              (Optional){
+     *                 kind: String(scalarQuantization/binaryQuantization) (Required)
+     *                 name: String (Required)
+     *                 rerankWithOriginalVectors: Boolean (Optional)
+     *                 defaultOversampling: Double (Optional)
+     *                 rescoringOptions (Optional): {
+     *                     enableRescoring: Boolean (Optional)
+     *                     defaultOversampling: Double (Optional)
+     *                     rescoreStorageMethod: String(preserveOriginals/discardOriginals) (Optional)
+     *                 }
+     *                 truncationDimension: Integer (Optional)
+     *             }
+     *         ]
+     *     }
+     *     @odata.etag: String (Optional)
+     * }
+     * }
+     * 
+ * + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     name: String (Required)
+     *     fields (Required): [
+     *          (Required){
+     *             name: String (Required)
+     *             type: String(Edm.String/Edm.Int32/Edm.Int64/Edm.Double/Edm.Boolean/Edm.DateTimeOffset/Edm.GeographyPoint/Edm.ComplexType/Edm.Single/Edm.Half/Edm.Int16/Edm.SByte/Edm.Byte) (Required)
+     *             key: Boolean (Optional)
+     *             retrievable: Boolean (Optional)
+     *             stored: Boolean (Optional)
+     *             searchable: Boolean (Optional)
+     *             filterable: Boolean (Optional)
+     *             sortable: Boolean (Optional)
+     *             facetable: Boolean (Optional)
+     *             analyzer: String(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) (Optional)
+     *             searchAnalyzer: String(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) (Optional)
+     *             indexAnalyzer: String(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) (Optional)
+     *             normalizer: String(asciifolding/elision/lowercase/standard/uppercase) (Optional)
+     *             dimensions: Integer (Optional)
+     *             vectorSearchProfile: String (Optional)
+     *             vectorEncoding: String(packedBit) (Optional)
+     *             synonymMaps (Optional): [
+     *                 String (Optional)
+     *             ]
+     *             fields (Optional): [
+     *                 (recursive schema, see above)
+     *             ]
+     *         }
+     *     ]
+     *     scoringProfiles (Optional): [
+     *          (Optional){
+     *             name: String (Required)
+     *             text (Optional): {
+     *                 weights (Required): {
+     *                     String: double (Required)
+     *                 }
+     *             }
+     *             functions (Optional): [
+     *                  (Optional){
+     *                     type: String (Required)
+     *                     fieldName: String (Required)
+     *                     boost: double (Required)
+     *                     interpolation: String(linear/constant/quadratic/logarithmic) (Optional)
+     *                 }
+     *             ]
+     *             functionAggregation: String(sum/average/minimum/maximum/firstMatching) (Optional)
+     *         }
+     *     ]
+     *     defaultScoringProfile: String (Optional)
+     *     corsOptions (Optional): {
+     *         allowedOrigins (Required): [
+     *             String (Required)
+     *         ]
+     *         maxAgeInSeconds: Long (Optional)
+     *     }
+     *     suggesters (Optional): [
+     *          (Optional){
+     *             name: String (Required)
+     *             searchMode: String (Required)
+     *             sourceFields (Required): [
+     *                 String (Required)
+     *             ]
+     *         }
+     *     ]
+     *     analyzers (Optional): [
+     *          (Optional){
+     *             @odata.type: String (Required)
+     *             name: String (Required)
+     *         }
+     *     ]
+     *     tokenizers (Optional): [
+     *          (Optional){
+     *             @odata.type: String (Required)
+     *             name: String (Required)
+     *         }
+     *     ]
+     *     tokenFilters (Optional): [
+     *          (Optional){
+     *             @odata.type: String (Required)
+     *             name: String (Required)
+     *         }
+     *     ]
+     *     charFilters (Optional): [
+     *          (Optional){
+     *             @odata.type: String (Required)
+     *             name: String (Required)
+     *         }
+     *     ]
+     *     normalizers (Optional): [
+     *          (Optional){
+     *             @odata.type: String (Required)
+     *             name: String (Required)
+     *         }
+     *     ]
+     *     encryptionKey (Optional): {
+     *         keyVaultKeyName: String (Required)
+     *         keyVaultKeyVersion: String (Optional)
+     *         keyVaultUri: String (Required)
+     *         accessCredentials (Optional): {
+     *             applicationId: String (Required)
+     *             applicationSecret: String (Optional)
+     *         }
+     *         identity (Optional): {
+     *             @odata.type: String (Required)
+     *         }
+     *     }
+     *     similarity (Optional): {
+     *         @odata.type: String (Required)
+     *     }
+     *     semantic (Optional): {
+     *         defaultConfiguration: String (Optional)
+     *         configurations (Optional): [
+     *              (Optional){
+     *                 name: String (Required)
+     *                 prioritizedFields (Required): {
+     *                     titleField (Optional): {
+     *                         fieldName: String (Required)
+     *                     }
+     *                     prioritizedContentFields (Optional): [
+     *                         (recursive schema, see above)
+     *                     ]
+     *                     prioritizedKeywordsFields (Optional): [
+     *                         (recursive schema, see above)
+     *                     ]
+     *                 }
+     *                 flightingOptIn: Boolean (Optional)
+     *             }
+     *         ]
+     *     }
+     *     vectorSearch (Optional): {
+     *         profiles (Optional): [
+     *              (Optional){
+     *                 name: String (Required)
+     *                 algorithm: String (Required)
+     *                 vectorizer: String (Optional)
+     *                 compression: String (Optional)
+     *             }
+     *         ]
+     *         algorithms (Optional): [
+     *              (Optional){
+     *                 kind: String(hnsw/exhaustiveKnn) (Required)
+     *                 name: String (Required)
+     *             }
+     *         ]
+     *         vectorizers (Optional): [
+     *              (Optional){
+     *                 kind: String(azureOpenAI/customWebApi/aiServicesVision/aml) (Required)
+     *                 name: String (Required)
+     *             }
+     *         ]
+     *         compressions (Optional): [
+     *              (Optional){
+     *                 kind: String(scalarQuantization/binaryQuantization) (Required)
+     *                 name: String (Required)
+     *                 rerankWithOriginalVectors: Boolean (Optional)
+     *                 defaultOversampling: Double (Optional)
+     *                 rescoringOptions (Optional): {
+     *                     enableRescoring: Boolean (Optional)
+     *                     defaultOversampling: Double (Optional)
+     *                     rescoreStorageMethod: String(preserveOriginals/discardOriginals) (Optional)
+     *                 }
+     *                 truncationDimension: Integer (Optional)
+     *             }
+     *         ]
+     *     }
+     *     @odata.etag: String (Optional)
+     * }
+     * }
+     * 
+ * + * @param indexName The name of the index. + * @param index The definition of the index to create or update. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return represents a search index definition, which describes the fields and search + * behavior of an index along with {@link Response}. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public Response createOrUpdateWithResponse(String indexName, BinaryData index, + RequestOptions requestOptions) { + return this.serviceClient.createOrUpdateWithResponse(indexName, index, requestOptions); + } + + /** + * 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. + *

Header Parameters

+ * + * + * + * + * + *
Header Parameters
NameTypeRequiredDescription
If-MatchStringNoDefines the If-Match condition. The operation will be + * performed only if the ETag on the server matches this value.
If-None-MatchStringNoDefines the If-None-Match condition. The operation will + * be performed only if the ETag on the server does not match this value.
+ * You can add these to a request with {@link RequestOptions#addHeader} + * + * @param indexName The name of the index. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return the {@link Response}. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public Response deleteWithResponse(String indexName, RequestOptions requestOptions) { + return this.serviceClient.deleteWithResponse(indexName, requestOptions); + } + + /** + * Retrieves an index definition. + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     name: String (Required)
+     *     fields (Required): [
+     *          (Required){
+     *             name: String (Required)
+     *             type: String(Edm.String/Edm.Int32/Edm.Int64/Edm.Double/Edm.Boolean/Edm.DateTimeOffset/Edm.GeographyPoint/Edm.ComplexType/Edm.Single/Edm.Half/Edm.Int16/Edm.SByte/Edm.Byte) (Required)
+     *             key: Boolean (Optional)
+     *             retrievable: Boolean (Optional)
+     *             stored: Boolean (Optional)
+     *             searchable: Boolean (Optional)
+     *             filterable: Boolean (Optional)
+     *             sortable: Boolean (Optional)
+     *             facetable: Boolean (Optional)
+     *             analyzer: String(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) (Optional)
+     *             searchAnalyzer: String(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) (Optional)
+     *             indexAnalyzer: String(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) (Optional)
+     *             normalizer: String(asciifolding/elision/lowercase/standard/uppercase) (Optional)
+     *             dimensions: Integer (Optional)
+     *             vectorSearchProfile: String (Optional)
+     *             vectorEncoding: String(packedBit) (Optional)
+     *             synonymMaps (Optional): [
+     *                 String (Optional)
+     *             ]
+     *             fields (Optional): [
+     *                 (recursive schema, see above)
+     *             ]
+     *         }
+     *     ]
+     *     scoringProfiles (Optional): [
+     *          (Optional){
+     *             name: String (Required)
+     *             text (Optional): {
+     *                 weights (Required): {
+     *                     String: double (Required)
+     *                 }
+     *             }
+     *             functions (Optional): [
+     *                  (Optional){
+     *                     type: String (Required)
+     *                     fieldName: String (Required)
+     *                     boost: double (Required)
+     *                     interpolation: String(linear/constant/quadratic/logarithmic) (Optional)
+     *                 }
+     *             ]
+     *             functionAggregation: String(sum/average/minimum/maximum/firstMatching) (Optional)
+     *         }
+     *     ]
+     *     defaultScoringProfile: String (Optional)
+     *     corsOptions (Optional): {
+     *         allowedOrigins (Required): [
+     *             String (Required)
+     *         ]
+     *         maxAgeInSeconds: Long (Optional)
+     *     }
+     *     suggesters (Optional): [
+     *          (Optional){
+     *             name: String (Required)
+     *             searchMode: String (Required)
+     *             sourceFields (Required): [
+     *                 String (Required)
+     *             ]
+     *         }
+     *     ]
+     *     analyzers (Optional): [
+     *          (Optional){
+     *             @odata.type: String (Required)
+     *             name: String (Required)
+     *         }
+     *     ]
+     *     tokenizers (Optional): [
+     *          (Optional){
+     *             @odata.type: String (Required)
+     *             name: String (Required)
+     *         }
+     *     ]
+     *     tokenFilters (Optional): [
+     *          (Optional){
+     *             @odata.type: String (Required)
+     *             name: String (Required)
+     *         }
+     *     ]
+     *     charFilters (Optional): [
+     *          (Optional){
+     *             @odata.type: String (Required)
+     *             name: String (Required)
+     *         }
+     *     ]
+     *     normalizers (Optional): [
+     *          (Optional){
+     *             @odata.type: String (Required)
+     *             name: String (Required)
+     *         }
+     *     ]
+     *     encryptionKey (Optional): {
+     *         keyVaultKeyName: String (Required)
+     *         keyVaultKeyVersion: String (Optional)
+     *         keyVaultUri: String (Required)
+     *         accessCredentials (Optional): {
+     *             applicationId: String (Required)
+     *             applicationSecret: String (Optional)
+     *         }
+     *         identity (Optional): {
+     *             @odata.type: String (Required)
+     *         }
+     *     }
+     *     similarity (Optional): {
+     *         @odata.type: String (Required)
+     *     }
+     *     semantic (Optional): {
+     *         defaultConfiguration: String (Optional)
+     *         configurations (Optional): [
+     *              (Optional){
+     *                 name: String (Required)
+     *                 prioritizedFields (Required): {
+     *                     titleField (Optional): {
+     *                         fieldName: String (Required)
+     *                     }
+     *                     prioritizedContentFields (Optional): [
+     *                         (recursive schema, see above)
+     *                     ]
+     *                     prioritizedKeywordsFields (Optional): [
+     *                         (recursive schema, see above)
+     *                     ]
+     *                 }
+     *                 flightingOptIn: Boolean (Optional)
+     *             }
+     *         ]
+     *     }
+     *     vectorSearch (Optional): {
+     *         profiles (Optional): [
+     *              (Optional){
+     *                 name: String (Required)
+     *                 algorithm: String (Required)
+     *                 vectorizer: String (Optional)
+     *                 compression: String (Optional)
+     *             }
+     *         ]
+     *         algorithms (Optional): [
+     *              (Optional){
+     *                 kind: String(hnsw/exhaustiveKnn) (Required)
+     *                 name: String (Required)
+     *             }
+     *         ]
+     *         vectorizers (Optional): [
+     *              (Optional){
+     *                 kind: String(azureOpenAI/customWebApi/aiServicesVision/aml) (Required)
+     *                 name: String (Required)
+     *             }
+     *         ]
+     *         compressions (Optional): [
+     *              (Optional){
+     *                 kind: String(scalarQuantization/binaryQuantization) (Required)
+     *                 name: String (Required)
+     *                 rerankWithOriginalVectors: Boolean (Optional)
+     *                 defaultOversampling: Double (Optional)
+     *                 rescoringOptions (Optional): {
+     *                     enableRescoring: Boolean (Optional)
+     *                     defaultOversampling: Double (Optional)
+     *                     rescoreStorageMethod: String(preserveOriginals/discardOriginals) (Optional)
+     *                 }
+     *                 truncationDimension: Integer (Optional)
+     *             }
+     *         ]
+     *     }
+     *     @odata.etag: String (Optional)
+     * }
+     * }
+     * 
+ * + * @param indexName The name of the index. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return represents a search index definition, which describes the fields and search + * behavior of an index along with {@link Response}. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public Response getWithResponse(String indexName, RequestOptions requestOptions) { + return this.serviceClient.getWithResponse(indexName, requestOptions); + } + + /** + * Returns statistics for the given index, including a document count and storage + * usage. + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     documentCount: long (Required)
+     *     storageSize: long (Required)
+     *     vectorIndexSize: long (Required)
+     * }
+     * }
+     * 
+ * + * @param indexName The name of the index. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return statistics for a given index along with {@link Response}. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public Response getStatisticsWithResponse(String indexName, RequestOptions requestOptions) { + return this.serviceClient.getStatisticsWithResponse(indexName, requestOptions); + } + + /** + * Shows how an analyzer breaks text into tokens. + *

Request Body Schema

+ * + *
+     * {@code
+     * {
+     *     text: String (Required)
+     *     analyzer: String(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) (Optional)
+     *     tokenizer: String(classic/edgeNGram/keyword_v2/letter/lowercase/microsoft_language_tokenizer/microsoft_language_stemming_tokenizer/nGram/path_hierarchy_v2/pattern/standard_v2/uax_url_email/whitespace) (Optional)
+     *     normalizer: String(asciifolding/elision/lowercase/standard/uppercase) (Optional)
+     *     tokenFilters (Optional): [
+     *         String(arabic_normalization/apostrophe/asciifolding/cjk_bigram/cjk_width/classic/common_grams/edgeNGram_v2/elision/german_normalization/hindi_normalization/indic_normalization/keyword_repeat/kstem/length/limit/lowercase/nGram_v2/persian_normalization/phonetic/porter_stem/reverse/scandinavian_normalization/scandinavian_folding/shingle/snowball/sorani_normalization/stemmer/stopwords/trim/truncate/unique/uppercase/word_delimiter) (Optional)
+     *     ]
+     *     charFilters (Optional): [
+     *         String(html_strip) (Optional)
+     *     ]
+     * }
+     * }
+     * 
+ * + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     tokens (Required): [
+     *          (Required){
+     *             token: String (Required)
+     *             startOffset: int (Required)
+     *             endOffset: int (Required)
+     *             position: int (Required)
+     *         }
+     *     ]
+     * }
+     * }
+     * 
+ * + * @param indexName The name of the index. + * @param request The text and analyzer or analysis components to test. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return the result of testing an analyzer on text along with {@link Response}. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public Response analyzeWithResponse(String indexName, BinaryData request, + RequestOptions requestOptions) { + return this.serviceClient.analyzeWithResponse(indexName, request, requestOptions); + } + + /** + * Creates a new search index. + * + * @param index The definition of the index to create. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return represents a search index definition, which describes the fields and search + * behavior of an index. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public SearchIndex create(SearchIndex index) { + // Generated convenience method for createWithResponse + RequestOptions requestOptions = new RequestOptions(); + return createWithResponse(BinaryData.fromObject(index), requestOptions).getValue().toObject(SearchIndex.class); + } + + /** + * Lists all indexes available for a search service. + * + * @param 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. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return response from a List Indexes request as paginated response with {@link PagedIterable}. + */ + @Generated + @ServiceMethod(returns = ReturnType.COLLECTION) + public PagedIterable list(String select) { + // Generated convenience method for list + RequestOptions requestOptions = new RequestOptions(); + if (select != null) { + requestOptions.addQueryParam("$select", select, false); + } + return serviceClient.list(requestOptions).mapPage(bodyItemValue -> bodyItemValue.toObject(SearchIndex.class)); + } + + /** + * Lists all indexes available for a search service. + * + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return response from a List Indexes request as paginated response with {@link PagedIterable}. + */ + @Generated + @ServiceMethod(returns = ReturnType.COLLECTION) + public PagedIterable list() { + // Generated convenience method for list + RequestOptions requestOptions = new RequestOptions(); + return serviceClient.list(requestOptions).mapPage(bodyItemValue -> bodyItemValue.toObject(SearchIndex.class)); + } + + /** + * Creates a new search index or updates an index if it already exists. + * + * @param indexName The name of the index. + * @param index The definition of the index to create or update. + * @param allowIndexDowntime 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. + * @param matchConditions Specifies HTTP options for conditional requests. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return represents a search index definition, which describes the fields and search + * behavior of an index. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public SearchIndex createOrUpdate(String indexName, SearchIndex index, Boolean allowIndexDowntime, + MatchConditions matchConditions) { + // Generated convenience method for createOrUpdateWithResponse + RequestOptions requestOptions = new RequestOptions(); + String ifMatch = matchConditions == null ? null : matchConditions.getIfMatch(); + String ifNoneMatch = matchConditions == null ? null : matchConditions.getIfNoneMatch(); + if (allowIndexDowntime != null) { + requestOptions.addQueryParam("allowIndexDowntime", String.valueOf(allowIndexDowntime), false); + } + if (ifMatch != null) { + requestOptions.setHeader(HttpHeaderName.IF_MATCH, ifMatch); + } + if (ifNoneMatch != null) { + requestOptions.setHeader(HttpHeaderName.IF_NONE_MATCH, ifNoneMatch); + } + return createOrUpdateWithResponse(indexName, BinaryData.fromObject(index), requestOptions).getValue() + .toObject(SearchIndex.class); + } + + /** + * Creates a new search index or updates an index if it already exists. + * + * @param indexName The name of the index. + * @param index The definition of the index to create or update. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return represents a search index definition, which describes the fields and search + * behavior of an index. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public SearchIndex createOrUpdate(String indexName, SearchIndex index) { + // Generated convenience method for createOrUpdateWithResponse + RequestOptions requestOptions = new RequestOptions(); + return createOrUpdateWithResponse(indexName, BinaryData.fromObject(index), requestOptions).getValue() + .toObject(SearchIndex.class); + } + + /** + * 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 indexName The name of the index. + * @param matchConditions Specifies HTTP options for conditional requests. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public void delete(String indexName, MatchConditions matchConditions) { + // Generated convenience method for deleteWithResponse + RequestOptions requestOptions = new RequestOptions(); + String ifMatch = matchConditions == null ? null : matchConditions.getIfMatch(); + String ifNoneMatch = matchConditions == null ? null : matchConditions.getIfNoneMatch(); + if (ifMatch != null) { + requestOptions.setHeader(HttpHeaderName.IF_MATCH, ifMatch); + } + if (ifNoneMatch != null) { + requestOptions.setHeader(HttpHeaderName.IF_NONE_MATCH, ifNoneMatch); + } + deleteWithResponse(indexName, requestOptions).getValue(); + } + + /** + * 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 indexName The name of the index. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public void delete(String indexName) { + // Generated convenience method for deleteWithResponse + RequestOptions requestOptions = new RequestOptions(); + deleteWithResponse(indexName, requestOptions).getValue(); + } + + /** + * Retrieves an index definition. + * + * @param indexName The name of the index. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return represents a search index definition, which describes the fields and search + * behavior of an index. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public SearchIndex get(String indexName) { + // Generated convenience method for getWithResponse + RequestOptions requestOptions = new RequestOptions(); + return getWithResponse(indexName, requestOptions).getValue().toObject(SearchIndex.class); + } + + /** + * Returns statistics for the given index, including a document count and storage + * usage. + * + * @param indexName The name of the index. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return statistics for a given index. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public GetIndexStatisticsResult getStatistics(String indexName) { + // Generated convenience method for getStatisticsWithResponse + RequestOptions requestOptions = new RequestOptions(); + return getStatisticsWithResponse(indexName, requestOptions).getValue().toObject(GetIndexStatisticsResult.class); + } + + /** + * Shows how an analyzer breaks text into tokens. + * + * @param indexName The name of the index. + * @param request The text and analyzer or analysis components to test. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the result of testing an analyzer on text. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public AnalyzeResult analyze(String indexName, AnalyzeRequest request) { + // Generated convenience method for analyzeWithResponse + RequestOptions requestOptions = new RequestOptions(); + return analyzeWithResponse(indexName, BinaryData.fromObject(request), requestOptions).getValue() + .toObject(AnalyzeResult.class); + } +} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/SearchAsyncClient.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/SearchAsyncClient.java index daa7f5fb344f..78a6d68a4b46 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/SearchAsyncClient.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/SearchAsyncClient.java @@ -1,1506 +1,172 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.search.documents; +import com.azure.core.annotation.Generated; import com.azure.core.annotation.ReturnType; import com.azure.core.annotation.ServiceClient; import com.azure.core.annotation.ServiceMethod; -import com.azure.core.http.HttpPipeline; +import com.azure.core.exception.ClientAuthenticationException; +import com.azure.core.exception.HttpResponseException; +import com.azure.core.exception.ResourceModifiedException; +import com.azure.core.exception.ResourceNotFoundException; +import com.azure.core.http.rest.PagedFlux; +import com.azure.core.http.rest.PagedResponse; +import com.azure.core.http.rest.PagedResponseBase; +import com.azure.core.http.rest.RequestOptions; import com.azure.core.http.rest.Response; -import com.azure.core.http.rest.SimpleResponse; -import com.azure.core.util.Context; -import com.azure.core.util.ServiceVersion; -import com.azure.core.util.logging.ClientLogger; -import com.azure.core.util.serializer.JsonSerializer; -import com.azure.search.documents.implementation.SearchIndexClientImpl; -import com.azure.search.documents.implementation.converters.IndexActionConverter; -import com.azure.search.documents.implementation.converters.SearchResultConverter; -import com.azure.search.documents.implementation.converters.SuggestResultConverter; -import com.azure.search.documents.implementation.models.AutocompleteRequest; -import com.azure.search.documents.implementation.models.SearchContinuationToken; -import com.azure.search.documents.implementation.models.SearchDocumentsResult; -import com.azure.search.documents.implementation.models.SearchFirstPageResponseWrapper; -import com.azure.search.documents.implementation.models.SearchRequest; -import com.azure.search.documents.implementation.models.SuggestDocumentsResult; -import com.azure.search.documents.implementation.models.SuggestRequest; -import com.azure.search.documents.implementation.util.MappingUtils; -import com.azure.search.documents.implementation.util.Utility; -import com.azure.search.documents.indexes.models.IndexDocumentsBatch; -import com.azure.search.documents.models.AutocompleteOptions; -import com.azure.search.documents.models.IndexAction; -import com.azure.search.documents.models.IndexActionType; -import com.azure.search.documents.models.IndexBatchException; -import com.azure.search.documents.models.IndexDocumentsOptions; -import com.azure.search.documents.models.IndexDocumentsResult; -import com.azure.search.documents.models.QueryAnswer; -import com.azure.search.documents.models.QueryAnswerType; -import com.azure.search.documents.models.QueryCaption; -import com.azure.search.documents.models.QueryCaptionType; -import com.azure.search.documents.models.QueryRewrites; -import com.azure.search.documents.models.ScoringParameter; -import com.azure.search.documents.models.SearchOptions; -import com.azure.search.documents.models.SearchResult; -import com.azure.search.documents.models.SemanticSearchOptions; -import com.azure.search.documents.models.SuggestOptions; -import com.azure.search.documents.models.SuggestResult; -import com.azure.search.documents.models.VectorSearchOptions; -import com.azure.search.documents.util.AutocompletePagedFlux; -import com.azure.search.documents.util.AutocompletePagedResponse; -import com.azure.search.documents.util.SearchPagedFlux; -import com.azure.search.documents.util.SearchPagedResponse; -import com.azure.search.documents.util.SuggestPagedFlux; -import com.azure.search.documents.util.SuggestPagedResponse; -import reactor.core.publisher.Mono; - -import java.util.ArrayList; -import java.util.List; -import java.util.function.Function; +import com.azure.core.util.BinaryData; +import com.azure.core.util.FluxUtil; +import com.azure.search.documents.implementation.SearchClientImpl; +import com.azure.search.documents.models.IndexStatisticsSummary; +import com.azure.search.documents.models.SearchServiceStatistics; import java.util.stream.Collectors; - -import static com.azure.core.util.FluxUtil.monoError; -import static com.azure.core.util.FluxUtil.withContext; -import static com.azure.core.util.serializer.TypeReference.createInstance; +import reactor.core.publisher.Flux; +import reactor.core.publisher.Mono; /** - * This class provides a client that contains the operations for querying an index and uploading, merging, or deleting - * documents in an Azure AI Search service. - * - *

- * Overview - *

- * - *

- * Conceptually, a document is an entity in your index. Mapping this concept to more familiar database equivalents: - * a search index equates to a table, and documents are roughly equivalent to rows in a table. Documents exist only - * in an index, and are retrieved only through queries that target the documents collection (/docs) of an index. All - * operations performed on the collection such as uploading, merging, deleting, or querying documents take place in - * the context of a single index, so the URL format document operations will always include /indexes/[index name]/docs - * for a given index name. - *

- * - *

- * This client provides an asynchronous API for accessing and performing operations on indexed documents. This client - * assists with searching your indexed documents, autocompleting partially typed search terms based on documents within the index, - * suggesting the most likely matching text in documents as a user types. The client provides operations for adding, updating, and deleting - * documents from an index. - *

- * - *

- * Getting Started - *

- * - *

- * Authenticating and building instances of this client are handled by {@link SearchClientBuilder}. This sample shows - * you how to authenticate and create an instance of the client: - *

- * - * - *
- * SearchAsyncClient searchAsyncClient = new SearchClientBuilder()
- *     .credential(new AzureKeyCredential("{key}"))
- *     .endpoint("{endpoint}")
- *     .indexName("{indexName}")
- *     .buildAsyncClient();
- * 
- * - * - *

- * For more information on authentication and building, see the {@link SearchClientBuilder} documentation. - *

- * - *
- * - *

- * Examples - *

- * - *

- * The following examples all use a simple Hotel - * data set that you can - * import into your own index from the Azure portal. - * These are just a few of the basics - please check out our Samples for much more. - *

- * - *

- * Upload a Document - *

- * - *

- * The following sample uploads a new document to an index. - *

- * - * - *
- * List<Hotel> hotels = new ArrayList<>();
- * hotels.add(new Hotel().setHotelId("100"));
- * hotels.add(new Hotel().setHotelId("200"));
- * hotels.add(new Hotel().setHotelId("300"));
- * searchAsyncClient.uploadDocuments(hotels).block();
- * 
- * - * - * - * For a synchronous sample see {@link SearchClient#uploadDocuments(Iterable)}. - * - * - *

- * Merge a Document - *

- * - *

- * The following sample merges documents in an index. - *

- * - * - *
- * List<Hotel> hotels = new ArrayList<>();
- * hotels.add(new Hotel().setHotelId("100"));
- * hotels.add(new Hotel().setHotelId("200"));
- * searchAsyncClient.mergeDocuments(hotels).block();
- * 
- * - * - * - * For a synchronous sample see {@link SearchClient#mergeDocuments(Iterable)}. - * - * - *

- * Delete a Document - *

- * - *

- * The following sample deletes a document from an index. - *

- * - * - *
- * SearchDocument documentId = new SearchDocument();
- * documentId.put("hotelId", "100");
- * searchAsyncClient.deleteDocuments(Collections.singletonList(documentId));
- * 
- * - * - * - * For a synchronous sample see {@link SearchClient#deleteDocuments(Iterable)}. - * - * - *

- * Get a Document - *

- * - *

- * The following sample gets a document from an index. - *

- * - * - *
- * Hotel hotel = searchAsyncClient.getDocument("100", Hotel.class).block();
- * if (hotel != null) {
- *     System.out.printf("Retrieved Hotel %s%n", hotel.getHotelId());
- * }
- * 
- * - * - * - * For a synchronous sample see {@link SearchClient#getDocument(String, Class)}. - * - * - *

- * Search Documents - *

- * - *

- * The following sample searches for documents within an index. - *

- * - * - *
- * SearchDocument searchDocument = new SearchDocument();
- * searchDocument.put("hotelId", "8");
- * searchDocument.put("description", "budget");
- * searchDocument.put("descriptionFr", "motel");
- *
- * SearchDocument searchDocument1 = new SearchDocument();
- * searchDocument1.put("hotelId", "9");
- * searchDocument1.put("description", "budget");
- * searchDocument1.put("descriptionFr", "motel");
- *
- * List<SearchDocument> searchDocuments = new ArrayList<>();
- * searchDocuments.add(searchDocument);
- * searchDocuments.add(searchDocument1);
- * searchAsyncClient.uploadDocuments(searchDocuments);
- *
- * SearchPagedFlux results = searchAsyncClient.search("SearchText");
- * results.getTotalCount().subscribe(total -> System.out.printf("There are %s results", total));
- * 
- * - * - * - * For a synchronous sample see {@link SearchClient#search(String)}. - * - * - *

- * Make a Suggestion - *

- * - *

- * The following sample suggests the most likely matching text in documents. - *

- * - * - *
- * SuggestPagedFlux results = searchAsyncClient.suggest("searchText", "sg");
- * results.subscribe(item -> {
- *     System.out.printf("The text '%s' was found.%n", item.getText());
- * });
- * 
- * - * - * - * For a synchronous sample see {@link SearchClient#suggest(String, String)}. - * - * - *

- * Provide an Autocompletion - *

- * - *

- * The following sample provides autocompletion for a partially typed query. - *

- * - * - *
- * AutocompletePagedFlux results = searchAsyncClient.autocomplete("searchText", "sg");
- * results.subscribe(item -> {
- *     System.out.printf("The text '%s' was found.%n", item.getText());
- * });
- * 
- * - * - * - * For a synchronous sample see {@link SearchClient#autocomplete(String, String)}. - * - * - * @see SearchClient - * @see SearchClientBuilder - * @see com.azure.search.documents + * Initializes a new instance of the asynchronous SearchClient type. */ @ServiceClient(builder = SearchClientBuilder.class, isAsync = true) public final class SearchAsyncClient { - private static final ClientLogger LOGGER = new ClientLogger(SearchAsyncClient.class); - - /** - * Search REST API Version - */ - private final SearchServiceVersion serviceVersion; - - /** - * The endpoint for the Azure AI Search service. - */ - private final String endpoint; - - /** - * The name of the Azure AI Search index. - */ - private final String indexName; - - /** - * The underlying AutoRest client used to interact with the Azure AI Search service - */ - private final SearchIndexClientImpl restClient; - - /** - * The pipeline that powers this client. - */ - private final HttpPipeline httpPipeline; - - final JsonSerializer serializer; - - /** - * Package private constructor to be used by {@link SearchClientBuilder} - */ - SearchAsyncClient(String endpoint, String indexName, SearchServiceVersion serviceVersion, HttpPipeline httpPipeline, - JsonSerializer serializer, SearchIndexClientImpl restClient) { - this.endpoint = endpoint; - this.indexName = indexName; - this.serviceVersion = serviceVersion; - this.httpPipeline = httpPipeline; - this.serializer = serializer; - this.restClient = restClient; - } - - /** - * Gets the name of the Azure AI Search index. - * - * @return the indexName value. - */ - public String getIndexName() { - return this.indexName; - } - - /** - * Gets the {@link HttpPipeline} powering this client. - * - * @return the pipeline. - */ - HttpPipeline getHttpPipeline() { - return this.httpPipeline; - } - - /** - * Gets the endpoint for the Azure AI Search service. - * - * @return the endpoint value. - */ - public String getEndpoint() { - return this.endpoint; - } - - /** - * Uploads a collection of documents to the target index. - * - *

Code Sample

- * - *

Upload dynamic SearchDocument.

- * - * - *
-     * SearchDocument searchDocument = new SearchDocument();
-     * searchDocument.put("hotelId", "1");
-     * searchDocument.put("hotelName", "test");
-     * SEARCH_ASYNC_CLIENT.uploadDocuments(Collections.singletonList(searchDocument))
-     *     .subscribe(result -> {
-     *         for (IndexingResult indexingResult : result.getResults()) {
-     *             System.out.printf("Does document with key %s upload successfully? %b%n",
-     *                 indexingResult.getKey(), indexingResult.isSucceeded());
-     *         }
-     *     });
-     * 
- * - * - * @param documents collection of documents to upload to the target Index. - * @return The result of the document indexing actions. - * @throws IndexBatchException If an indexing action fails but other actions succeed and modify the state of the - * index. This can happen when the Search Service is under heavy indexing load. It is important to explicitly catch - * this exception and check the return value {@link IndexBatchException#getIndexingResults()}. The indexing result - * reports the status of each indexing action in the batch, making it possible to determine the state of the index - * after a partial failure. - * @see Add, update, or - * delete documents - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono uploadDocuments(Iterable documents) { - return uploadDocumentsWithResponse(documents, null).map(Response::getValue); - } - - /** - * Uploads a collection of documents to the target index. - * - *

Code Sample

- * - *

Upload dynamic SearchDocument.

- * - * - *
-     * SearchDocument searchDocument = new SearchDocument();
-     * searchDocument.put("hotelId", "1");
-     * searchDocument.put("hotelName", "test");
-     * searchAsyncClient.uploadDocumentsWithResponse(Collections.singletonList(searchDocument), null)
-     *     .subscribe(resultResponse -> {
-     *         System.out.println("The status code of the response is " + resultResponse.getStatusCode());
-     *         for (IndexingResult indexingResult : resultResponse.getValue().getResults()) {
-     *             System.out.printf("Does document with key %s upload successfully? %b%n", indexingResult.getKey(),
-     *                 indexingResult.isSucceeded());
-     *         }
-     *     });
-     * 
- * - * - * @param documents collection of documents to upload to the target Index. - * @param options Options that allow specifying document indexing behavior. - * @return A response containing the result of the document indexing actions. - * @throws IndexBatchException If an indexing action fails but other actions succeed and modify the state of the - * index. This can happen when the Search Service is under heavy indexing load. It is important to explicitly catch - * this exception and check the return value {@link IndexBatchException#getIndexingResults()}. The indexing result - * reports the status of each indexing action in the batch, making it possible to determine the state of the index - * after a partial failure. - * @see Add, update, or - * delete documents - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> uploadDocumentsWithResponse(Iterable documents, - IndexDocumentsOptions options) { - return withContext(context -> uploadDocumentsWithResponse(documents, options, context)); - } - - Mono> uploadDocumentsWithResponse(Iterable documents, - IndexDocumentsOptions options, Context context) { - return indexDocumentsWithResponse(buildIndexBatch(documents, IndexActionType.UPLOAD), options, context); - } - - /** - * Merges a collection of documents with existing documents in the target index. - *

- * If the type of the document contains non-nullable primitive-typed properties, these properties may not merge - * correctly. If you do not set such a property, it will automatically take its default value (for example, - * {@code 0} for {@code int} or false for {@code boolean}), which will override the value of the property currently - * stored in the index, even if this was not your intent. For this reason, it is strongly recommended that you - * always declare primitive-typed properties with their class equivalents (for example, an integer property should - * be of type {@code Integer} instead of {@code int}). - * - *

Code Sample

- * - *

Merge dynamic SearchDocument.

- * - * - *
-     * SearchDocument searchDocument = new SearchDocument();
-     * searchDocument.put("hotelName", "merge");
-     * SEARCH_ASYNC_CLIENT.mergeDocuments(Collections.singletonList(searchDocument))
-     *     .subscribe(result -> {
-     *         for (IndexingResult indexingResult : result.getResults()) {
-     *             System.out.printf("Does document with key %s merge successfully? %b%n", indexingResult.getKey(),
-     *                 indexingResult.isSucceeded());
-     *         }
-     *     });
-     * 
- * - * - * @param documents collection of documents to be merged - * @return document index result - * @throws IndexBatchException If an indexing action fails but other actions succeed and modify the state of the - * index. This can happen when the Search Service is under heavy indexing load. It is important to explicitly catch - * this exception and check the return value {@link IndexBatchException#getIndexingResults()}. The indexing result - * reports the status of each indexing action in the batch, making it possible to determine the state of the index - * after a partial failure. - * @see Add, update, or - * delete documents - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono mergeDocuments(Iterable documents) { - return mergeDocumentsWithResponse(documents, null).map(Response::getValue); - } - - /** - * Merges a collection of documents with existing documents in the target index. - *

- * If the type of the document contains non-nullable primitive-typed properties, these properties may not merge - * correctly. If you do not set such a property, it will automatically take its default value (for example, - * {@code 0} for {@code int} or false for {@code boolean}), which will override the value of the property currently - * stored in the index, even if this was not your intent. For this reason, it is strongly recommended that you - * always declare primitive-typed properties with their class equivalents (for example, an integer property should - * be of type {@code Integer} instead of {@code int}). - * - *

Code Sample

- * - *

Merge dynamic SearchDocument.

- * - * - *
-     * SearchDocument searchDocument = new SearchDocument();
-     * searchDocument.put("hotelName", "test");
-     * searchAsyncClient.mergeDocumentsWithResponse(Collections.singletonList(searchDocument), null)
-     *     .subscribe(resultResponse -> {
-     *         System.out.println("The status code of the response is " + resultResponse.getStatusCode());
-     *         for (IndexingResult indexingResult : resultResponse.getValue().getResults()) {
-     *             System.out.printf("Does document with key %s merge successfully? %b%n", indexingResult.getKey(),
-     *                 indexingResult.isSucceeded());
-     *         }
-     *     });
-     * 
- * - * - * @param documents collection of documents to be merged - * @param options Options that allow specifying document indexing behavior. - * @return response containing the document index result. - * @throws IndexBatchException If an indexing action fails but other actions succeed and modify the state of the - * index. This can happen when the Search Service is under heavy indexing load. It is important to explicitly catch - * this exception and check the return value {@link IndexBatchException#getIndexingResults()}. The indexing result - * reports the status of each indexing action in the batch, making it possible to determine the state of the index - * after a partial failure. - * @see Add, update, or - * delete documents - */ + @Generated + private final SearchClientImpl serviceClient; + + /** + * Initializes an instance of SearchAsyncClient class. + * + * @param serviceClient the service client implementation. + */ + @Generated + SearchAsyncClient(SearchClientImpl serviceClient) { + this.serviceClient = serviceClient; + } + + /** + * Gets service level statistics for a search service. + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     counters (Required): {
+     *         aliasesCount (Required): {
+     *             usage: long (Required)
+     *             quota: Long (Optional)
+     *         }
+     *         documentCount (Required): (recursive schema, see documentCount above)
+     *         indexesCount (Required): (recursive schema, see indexesCount above)
+     *         indexersCount (Required): (recursive schema, see indexersCount above)
+     *         dataSourcesCount (Required): (recursive schema, see dataSourcesCount above)
+     *         storageSize (Required): (recursive schema, see storageSize above)
+     *         synonymMaps (Required): (recursive schema, see synonymMaps above)
+     *         skillsetCount (Required): (recursive schema, see skillsetCount above)
+     *         vectorIndexSize (Required): (recursive schema, see vectorIndexSize above)
+     *     }
+     *     limits (Required): {
+     *         maxFieldsPerIndex: Integer (Optional)
+     *         maxFieldNestingDepthPerIndex: Integer (Optional)
+     *         maxComplexCollectionFieldsPerIndex: Integer (Optional)
+     *         maxComplexObjectsInCollectionsPerDocument: Integer (Optional)
+     *         maxStoragePerIndex: Long (Optional)
+     *     }
+     * }
+     * }
+     * 
+ * + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return service level statistics for a search service along with {@link Response} on successful completion of + * {@link Mono}. + */ + @Generated @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> mergeDocumentsWithResponse(Iterable documents, - IndexDocumentsOptions options) { - return withContext(context -> mergeDocumentsWithResponse(documents, options, context)); - } - - Mono> mergeDocumentsWithResponse(Iterable documents, - IndexDocumentsOptions options, Context context) { - return indexDocumentsWithResponse(buildIndexBatch(documents, IndexActionType.MERGE), options, context); - } - - /** - * This action behaves like merge if a document with the given key already exists in the index. If the document does - * not exist, it behaves like upload with a new document. - *

- * If the type of the document contains non-nullable primitive-typed properties, these properties may not merge - * correctly. If you do not set such a property, it will automatically take its default value (for example, - * {@code 0} for {@code int} or false for {@code boolean}), which will override the value of the property currently - * stored in the index, even if this was not your intent. For this reason, it is strongly recommended that you - * always declare primitive-typed properties with their class equivalents (for example, an integer property should - * be of type {@code Integer} instead of {@code int}). - * - *

Code Sample

- * - *

Merge or upload dynamic SearchDocument.

- * - * - *
-     * SearchDocument searchDocument = new SearchDocument();
-     * searchDocument.put("hotelId", "1");
-     * searchDocument.put("hotelName", "test");
-     * SEARCH_ASYNC_CLIENT.mergeOrUploadDocuments(Collections.singletonList(searchDocument))
-     *     .subscribe(result -> {
-     *         for (IndexingResult indexingResult : result.getResults()) {
-     *             System.out.printf("Does document with key %s mergeOrUpload successfully? %b%n",
-     *                 indexingResult.getKey(), indexingResult.isSucceeded());
-     *         }
-     *     });
-     * 
- * - * - * @param documents collection of documents to be merged, if exists, otherwise uploaded - * @return document index result - * @throws IndexBatchException If an indexing action fails but other actions succeed and modify the state of the - * index. This can happen when the Search Service is under heavy indexing load. It is important to explicitly catch - * this exception and check the return value {@link IndexBatchException#getIndexingResults()}. The indexing result - * reports the status of each indexing action in the batch, making it possible to determine the state of the index - * after a partial failure. - * @see Add, update, or - * delete documents - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono mergeOrUploadDocuments(Iterable documents) { - return mergeOrUploadDocumentsWithResponse(documents, null).map(Response::getValue); - } - - /** - * This action behaves like merge if a document with the given key already exists in the index. If the document does - * not exist, it behaves like upload with a new document. - *

- * If the type of the document contains non-nullable primitive-typed properties, these properties may not merge - * correctly. If you do not set such a property, it will automatically take its default value (for example, - * {@code 0} for {@code int} or false for {@code boolean}), which will override the value of the property currently - * stored in the index, even if this was not your intent. For this reason, it is strongly recommended that you - * always declare primitive-typed properties with their class equivalents (for example, an integer property should - * be of type {@code Integer} instead of {@code int}). - * - *

Code Sample

- * - *

Merge or upload dynamic SearchDocument.

- * - * - *
-     * SearchDocument searchDocument = new SearchDocument();
-     * searchDocument.put("hotelId", "1");
-     * searchDocument.put("hotelName", "test");
-     * searchAsyncClient.mergeOrUploadDocumentsWithResponse(Collections.singletonList(searchDocument), null)
-     *     .subscribe(resultResponse -> {
-     *         System.out.println("The status code of the response is " + resultResponse.getStatusCode());
-     *         for (IndexingResult indexingResult : resultResponse.getValue().getResults()) {
-     *             System.out.printf("Does document with key %s mergeOrUpload successfully? %b%n",
-     *                 indexingResult.getKey(), indexingResult.isSucceeded());
-     *         }
-     *     });
-     * 
- * - * - * @param documents collection of documents to be merged, if exists, otherwise uploaded - * @param options Options that allow specifying document indexing behavior. - * @return document index result - * @throws IndexBatchException If an indexing action fails but other actions succeed and modify the state of the - * index. This can happen when the Search Service is under heavy indexing load. It is important to explicitly catch - * this exception and check the return value {@link IndexBatchException#getIndexingResults()}. The indexing result - * reports the status of each indexing action in the batch, making it possible to determine the state of the index - * after a partial failure. - * @see Add, update, or - * delete documents - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> mergeOrUploadDocumentsWithResponse(Iterable documents, - IndexDocumentsOptions options) { - return withContext(context -> mergeOrUploadDocumentsWithResponse(documents, options, context)); - } - - Mono> mergeOrUploadDocumentsWithResponse(Iterable documents, - IndexDocumentsOptions options, Context context) { - return indexDocumentsWithResponse(buildIndexBatch(documents, IndexActionType.MERGE_OR_UPLOAD), options, - context); - } - - /** - * Deletes a collection of documents from the target index. - * - *

Code Sample

- * - *

Delete dynamic SearchDocument.

- * - * - *
-     * SearchDocument searchDocument = new SearchDocument();
-     * searchDocument.put("hotelId", "1");
-     * searchDocument.put("hotelName", "test");
-     * SEARCH_ASYNC_CLIENT.deleteDocuments(Collections.singletonList(searchDocument))
-     *     .subscribe(result -> {
-     *         for (IndexingResult indexingResult : result.getResults()) {
-     *             System.out.printf("Does document with key %s delete successfully? %b%n", indexingResult.getKey(),
-     *                 indexingResult.isSucceeded());
-     *         }
-     *     });
-     * 
- * - * - * @param documents collection of documents to delete from the target Index. Fields other than the key are ignored. - * @return document index result. - * @throws IndexBatchException If an indexing action fails but other actions succeed and modify the state of the - * index. This can happen when the Search Service is under heavy indexing load. It is important to explicitly catch - * this exception and check the return value {@link IndexBatchException#getIndexingResults()}. The indexing result - * reports the status of each indexing action in the batch, making it possible to determine the state of the index - * after a partial failure. - * @see Add, update, or - * delete documents - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono deleteDocuments(Iterable documents) { - return deleteDocumentsWithResponse(documents, null).map(Response::getValue); - } - - /** - * Deletes a collection of documents from the target index. - * - *

Code Sample

- * - *

Delete dynamic SearchDocument.

- * - * - *
-     * SearchDocument searchDocument = new SearchDocument();
-     * searchDocument.put("hotelId", "1");
-     * searchDocument.put("hotelName", "test");
-     * searchAsyncClient.deleteDocumentsWithResponse(Collections.singletonList(searchDocument), null)
-     *     .subscribe(resultResponse -> {
-     *         System.out.println("The status code of the response is " + resultResponse.getStatusCode());
-     *         for (IndexingResult indexingResult : resultResponse.getValue().getResults()) {
-     *             System.out.printf("Does document with key %s delete successfully? %b%n", indexingResult.getKey(),
-     *                 indexingResult.isSucceeded());
-     *         }
-     *     });
-     * 
- * - * - * @param documents collection of documents to delete from the target Index. Fields other than the key are ignored. - * @param options Options that allow specifying document indexing behavior. - * @return response containing the document index result. - * @throws IndexBatchException If an indexing action fails but other actions succeed and modify the state of the - * index. This can happen when the Search Service is under heavy indexing load. It is important to explicitly catch - * this exception and check the return value {@link IndexBatchException#getIndexingResults()}. The indexing result - * reports the status of each indexing action in the batch, making it possible to determine the state of the index - * after a partial failure. - * @see Add, update, or - * delete documents - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> deleteDocumentsWithResponse(Iterable documents, - IndexDocumentsOptions options) { - return withContext(context -> deleteDocumentsWithResponse(documents, options, context)); - } - - Mono> deleteDocumentsWithResponse(Iterable documents, - IndexDocumentsOptions options, Context context) { - return indexDocumentsWithResponse(buildIndexBatch(documents, IndexActionType.DELETE), options, context); - } - - /** - * Sends a batch of upload, merge, and/or delete actions to the search index. - * - *

Code Sample

- * - *

Index batch operation on dynamic SearchDocument.

- * - * - *
-     * SearchDocument searchDocument1 = new SearchDocument();
-     * searchDocument1.put("hotelId", "1");
-     * searchDocument1.put("hotelName", "test1");
-     * SearchDocument searchDocument2 = new SearchDocument();
-     * searchDocument2.put("hotelId", "2");
-     * searchDocument2.put("hotelName", "test2");
-     * IndexDocumentsBatch<SearchDocument> indexDocumentsBatch = new IndexDocumentsBatch<>();
-     * indexDocumentsBatch.addUploadActions(Collections.singletonList(searchDocument1));
-     * indexDocumentsBatch.addDeleteActions(Collections.singletonList(searchDocument2));
-     * SEARCH_ASYNC_CLIENT.indexDocuments(indexDocumentsBatch)
-     *     .subscribe(result -> {
-     *         for (IndexingResult indexingResult : result.getResults()) {
-     *             System.out.printf("Does document with key %s finish successfully? %b%n", indexingResult.getKey(),
-     *                 indexingResult.isSucceeded());
-     *         }
-     *     });
-     * 
- * - * - * @param batch The batch of index actions - * @return Response containing the status of operations for all actions in the batch. - * @throws IndexBatchException If an indexing action fails but other actions succeed and modify the state of the - * index. This can happen when the Search Service is under heavy indexing load. It is important to explicitly catch - * this exception and check the return value {@link IndexBatchException#getIndexingResults()}. The indexing result - * reports the status of each indexing action in the batch, making it possible to determine the state of the index - * after a partial failure. - * @see Add, update, or - * delete documents - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono indexDocuments(IndexDocumentsBatch batch) { - return indexDocumentsWithResponse(batch, null).map(Response::getValue); - } - - /** - * Sends a batch of upload, merge, and/or delete actions to the search index. - * - *

Code Sample

- * - *

Index batch operation on dynamic SearchDocument.

- * - * - *
-     * SearchDocument searchDocument1 = new SearchDocument();
-     * searchDocument1.put("hotelId", "1");
-     * searchDocument1.put("hotelName", "test1");
-     * SearchDocument searchDocument2 = new SearchDocument();
-     * searchDocument2.put("hotelId", "2");
-     * searchDocument2.put("hotelName", "test2");
-     * IndexDocumentsBatch<SearchDocument> indexDocumentsBatch = new IndexDocumentsBatch<>();
-     * indexDocumentsBatch.addUploadActions(Collections.singletonList(searchDocument1));
-     * indexDocumentsBatch.addDeleteActions(Collections.singletonList(searchDocument2));
-     * searchAsyncClient.indexDocumentsWithResponse(indexDocumentsBatch, null)
-     *     .subscribe(resultResponse -> {
-     *         System.out.println("The status code of the response is " + resultResponse.getStatusCode());
-     *         for (IndexingResult indexingResult : resultResponse.getValue().getResults()) {
-     *             System.out.printf("Does document with key %s finish successfully? %b%n", indexingResult.getKey(),
-     *                 indexingResult.isSucceeded());
-     *         }
-     *     });
-     * 
- * - * - * @param batch The batch of index actions - * @param options Options that allow specifying document indexing behavior. - * @return Response containing the status of operations for all actions in the batch - * @throws IndexBatchException If an indexing action fails but other actions succeed and modify the state of the - * index. This can happen when the Search Service is under heavy indexing load. It is important to explicitly catch - * this exception and check the return value {@link IndexBatchException#getIndexingResults()}. The indexing result - * reports the status of each indexing action in the batch, making it possible to determine the state of the index - * after a partial failure. - * @see Add, update, or - * delete documents - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> indexDocumentsWithResponse(IndexDocumentsBatch batch, - IndexDocumentsOptions options) { - return withContext(context -> indexDocumentsWithResponse(batch, options, context)); - } - - Mono> indexDocumentsWithResponse(IndexDocumentsBatch batch, - IndexDocumentsOptions options, Context context) { - List indexActions = batch.getActions() - .stream() - .map(document -> IndexActionConverter.map(document, serializer)) - .collect(Collectors.toList()); - - boolean throwOnAnyError = options == null || options.throwOnAnyError(); - return Utility.indexDocumentsWithResponseAsync(restClient, indexActions, throwOnAnyError, context, LOGGER); - } - - /** - * Retrieves a document from the Azure AI Search index. - *

- * View naming rules for guidelines on - * constructing valid document keys. - * - *

Code Sample

- * - *

Get dynamic SearchDocument.

- * - * - *
-     * SEARCH_ASYNC_CLIENT.getDocument("hotelId", SearchDocument.class)
-     *     .subscribe(result -> {
-     *         for (Map.Entry<String, Object> keyValuePair : result.entrySet()) {
-     *             System.out.printf("Document key %s, Document value %s", keyValuePair.getKey(),
-     *                 keyValuePair.getValue());
-     *         }
-     *     });
-     * 
- * - * - * @param key The key of the document to retrieve. - * @param modelClass The model class converts to. - * @param Convert document to the generic type. - * @return the document object - * @see Lookup document - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono getDocument(String key, Class modelClass) { - return getDocumentWithResponse(key, modelClass, null).map(Response::getValue); - } - - /** - * Retrieves a document from the Azure AI Search index. - *

- * View naming rules for guidelines on - * constructing valid document keys. - * - *

Code Sample

- * - *

Get dynamic SearchDocument.

- * - * - *
-     * SEARCH_ASYNC_CLIENT.getDocumentWithResponse("hotelId", SearchDocument.class, null)
-     *     .subscribe(resultResponse -> {
-     *         System.out.println("The status code of the response is " + resultResponse.getStatusCode());
-     *         for (Map.Entry<String, Object> keyValuePair : resultResponse.getValue().entrySet()) {
-     *             System.out.printf("Document key %s, Document value %s", keyValuePair.getKey(),
-     *                 keyValuePair.getValue());
-     *         }
-     *     });
-     * 
- * - * - * @param Convert document to the generic type. - * @param key The key of the document to retrieve. - * @param modelClass The model class converts to. - * @param selectedFields List of field names to retrieve for the document; Any field not retrieved will have null or - * default as its corresponding property value in the returned object. - * @return a response containing the document object - * @see Lookup document - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> getDocumentWithResponse(String key, Class modelClass, List selectedFields) { - return withContext(context -> getDocumentWithResponse(key, modelClass, selectedFields, context)); - } - - Mono> getDocumentWithResponse(String key, Class modelClass, List selectedFields, - Context context) { - try { - return restClient.getDocuments() - .getWithResponseAsync(key, selectedFields, null, context) - .onErrorMap(Utility::exceptionMapper) - .map(res -> new SimpleResponse<>(res, serializer - .deserializeFromBytes(serializer.serializeToBytes(res.getValue()), createInstance(modelClass)))); - } catch (RuntimeException ex) { - return monoError(LOGGER, ex); - } - } - - /** - * Queries the number of documents in the search index. - * - *

Code Sample

- * - *

Get document count.

- * - * - *
-     * SEARCH_ASYNC_CLIENT.getDocumentCount()
-     *     .subscribe(count -> System.out.printf("There are %d documents in service.", count));
-     * 
- * - * - * @return the number of documents. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono getDocumentCount() { - return this.getDocumentCountWithResponse().map(Response::getValue); - } - - /** - * Queries the number of documents in the search index. - * - *

Code Sample

- * - *

Get document count.

- * - * - *
-     * SEARCH_ASYNC_CLIENT.getDocumentCountWithResponse()
-     *     .subscribe(countResponse -> {
-     *         System.out.println("The status code of the response is " + countResponse.getStatusCode());
-     *         System.out.printf("There are %d documents in service.", countResponse.getValue());
-     *     });
-     * 
- * - * - * @return response containing the number of documents. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> getDocumentCountWithResponse() { - return withContext(this::getDocumentCountWithResponse); - } - - Mono> getDocumentCountWithResponse(Context context) { - try { - return restClient.getDocuments() - .countWithResponseAsync(null, context) - .onErrorMap(MappingUtils::exceptionMapper) - .map(Function.identity()); - } catch (RuntimeException ex) { - return monoError(LOGGER, ex); - } - } - - /** - * Searches for documents in the Azure AI Search index. - *

- * If {@code searchText} is set to null or {@code "*"} all documents will be matched, see - * simple query - * syntax in Azure AI Search for more information about search query syntax. - *

- * The {@link SearchPagedFlux} will iterate through search result pages until all search results are returned. - * Each page is determined by the {@code $skip} and {@code $top} values and the Search service has a limit on the - * number of documents that can be skipped, more information about the {@code $skip} limit can be found at - * Search Documents REST API and - * reading the {@code $skip} description. If the total number of results exceeds the {@code $skip} limit the - * {@link SearchPagedFlux} won't prevent you from exceeding the {@code $skip} limit. To prevent exceeding the limit - * you can track the number of documents returned and stop requesting new pages when the limit is reached. - * - *

Code Sample

- * - *

Search text from documents in service.

- * - * - *
-     * SearchPagedFlux searchPagedFlux = SEARCH_ASYNC_CLIENT.search("searchText");
-     * searchPagedFlux.getTotalCount().subscribe(
-     *     count -> System.out.printf("There are around %d results.", count));
-     *
-     * AtomicLong numberOfDocumentsReturned = new AtomicLong();
-     * searchPagedFlux.byPage()
-     *     .takeUntil(page -> {
-     *         if (numberOfDocumentsReturned.addAndGet(page.getValue().size()) >= SEARCH_SKIP_LIMIT) {
-     *             // Reached the $skip limit, stop requesting more documents.
-     *             return true;
-     *         }
-     *
-     *         return false;
-     *     })
-     *     .subscribe(resultResponse -> {
-     *         for (SearchResult result: resultResponse.getValue()) {
-     *             SearchDocument searchDocument = result.getDocument(SearchDocument.class);
-     *             for (Map.Entry<String, Object> keyValuePair: searchDocument.entrySet()) {
-     *                 System.out.printf("Document key %s, document value %s", keyValuePair.getKey(), keyValuePair.getValue());
-     *             }
-     *         }
-     *     });
-     * 
- * - * - * @param searchText A full-text search query expression. - * @return A {@link SearchPagedFlux} that iterates over {@link SearchResult} objects and provides access to the - * {@link SearchPagedResponse} object for each page containing HTTP response and count, facet, and coverage - * information. - * @see Search documents - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - public SearchPagedFlux search(String searchText) { - return this.search(searchText, null); - } - - /** - * Searches for documents in the Azure AI Search index. - *

- * If {@code searchText} is set to null or {@code "*"} all documents will be matched, see - * simple query - * syntax in Azure AI Search for more information about search query syntax. - *

- * The {@link SearchPagedFlux} will iterate through search result pages until all search results are returned. - * Each page is determined by the {@code $skip} and {@code $top} values and the Search service has a limit on the - * number of documents that can be skipped, more information about the {@code $skip} limit can be found at - * Search Documents REST API and - * reading the {@code $skip} description. If the total number of results exceeds the {@code $skip} limit the - * {@link SearchPagedFlux} won't prevent you from exceeding the {@code $skip} limit. To prevent exceeding the limit - * you can track the number of documents returned and stop requesting new pages when the limit is reached. - * - *

Code Sample

- * - *

Search text from documents in service with option.

- * - * - *
-     * SearchPagedFlux pagedFlux = SEARCH_ASYNC_CLIENT.search("searchText",
-     *     new SearchOptions().setOrderBy("hotelId desc"));
-     *
-     * pagedFlux.getTotalCount().subscribe(count -> System.out.printf("There are around %d results.", count));
-     *
-     * AtomicLong numberOfDocumentsReturned = new AtomicLong();
-     * pagedFlux.byPage()
-     *     .takeUntil(page -> {
-     *         if (numberOfDocumentsReturned.addAndGet(page.getValue().size()) >= SEARCH_SKIP_LIMIT) {
-     *             // Reached the $skip limit, stop requesting more documents.
-     *             return true;
-     *         }
-     *
-     *         return false;
-     *     })
-     *     .subscribe(searchResultResponse -> searchResultResponse.getValue().forEach(searchDocument -> {
-     *         for (Map.Entry<String, Object> keyValuePair
-     *             : searchDocument.getDocument(SearchDocument.class).entrySet()) {
-     *             System.out.printf("Document key %s, document value %s", keyValuePair.getKey(),
-     *                 keyValuePair.getValue());
-     *         }
-     *     }));
-     * 
- * - * - * @param searchText A full-text search query expression. - * @param searchOptions Parameters to further refine the search query - * @return A {@link SearchPagedFlux} that iterates over {@link SearchResult} objects and provides access to the - * {@link SearchPagedResponse} object for each page containing HTTP response and count, facet, and coverage - * information. - * @see Search documents - */ + public Mono> getServiceStatisticsWithResponse(RequestOptions requestOptions) { + return this.serviceClient.getServiceStatisticsWithResponseAsync(requestOptions); + } + + /** + * Retrieves a summary of statistics for all indexes in the search service. + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     name: String (Required)
+     *     documentCount: long (Required)
+     *     storageSize: long (Required)
+     *     vectorIndexSize: Long (Optional)
+     * }
+     * }
+     * 
+ * + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return response from a request to retrieve stats summary of all indexes as paginated response with + * {@link PagedFlux}. + */ + @Generated @ServiceMethod(returns = ReturnType.COLLECTION) - public SearchPagedFlux search(String searchText, SearchOptions searchOptions) { - SearchRequest request = createSearchRequest(searchText, searchOptions); - // The firstPageResponse shared among all functional calls below. - // Do not initial new instance directly in func call. - final SearchFirstPageResponseWrapper firstPageResponse = new SearchFirstPageResponseWrapper(); - Function> func = continuationToken -> withContext( - context -> search(request, continuationToken, firstPageResponse, context)); - return new SearchPagedFlux(() -> func.apply(null), func); - } - - SearchPagedFlux search(String searchText, SearchOptions searchOptions, Context context) { - SearchRequest request = createSearchRequest(searchText, searchOptions); - // The firstPageResponse shared among all functional calls below. - // Do not initial new instance directly in func call. - final SearchFirstPageResponseWrapper firstPageResponseWrapper = new SearchFirstPageResponseWrapper(); - Function> func - = continuationToken -> search(request, continuationToken, firstPageResponseWrapper, context); - return new SearchPagedFlux(() -> func.apply(null), func); - } - - private Mono search(SearchRequest request, String continuationToken, - SearchFirstPageResponseWrapper firstPageResponseWrapper, Context context) { - if (continuationToken == null && firstPageResponseWrapper.getFirstPageResponse() != null) { - return Mono.just(firstPageResponseWrapper.getFirstPageResponse()); - } - SearchRequest requestToUse = (continuationToken == null) - ? request - : SearchContinuationToken.deserializeToken(serviceVersion.getVersion(), continuationToken); - - return restClient.getDocuments() - .searchPostWithResponseAsync(requestToUse, null, context) - .onErrorMap(MappingUtils::exceptionMapper) - .map(response -> { - SearchDocumentsResult result = response.getValue(); - - SearchPagedResponse page - = new SearchPagedResponse(new SimpleResponse<>(response, getSearchResults(result, serializer)), - createContinuationToken(result, serviceVersion), result.getFacets(), result.getCount(), - result.getCoverage(), result.getAnswers(), result.getSemanticPartialResponseReason(), - result.getSemanticPartialResponseType()); - if (continuationToken == null) { - firstPageResponseWrapper.setFirstPageResponse(page); - } - return page; - }); - } - - static List getSearchResults(SearchDocumentsResult result, JsonSerializer jsonSerializer) { - return result.getResults() - .stream() - .map(searchResult -> SearchResultConverter.map(searchResult, jsonSerializer)) - .collect(Collectors.toList()); - } - - static String createContinuationToken(SearchDocumentsResult result, ServiceVersion serviceVersion) { - return SearchContinuationToken.serializeToken(serviceVersion.getVersion(), result.getNextLink(), - result.getNextPageParameters()); - } - - /** - * Suggests documents in the index that match the given partial query. - * - *

Code Sample

- * - *

Suggest text from documents in service.

- * - * - *
-     * SEARCH_ASYNC_CLIENT.suggest("searchText", "sg")
-     *     .subscribe(results -> {
-     *         for (Map.Entry<String, Object> keyValuePair: results.getDocument(SearchDocument.class).entrySet()) {
-     *             System.out.printf("Document key %s, document value %s", keyValuePair.getKey(),
-     *                 keyValuePair.getValue());
-     *         }
-     *     });
-     * 
- * - * - * @param searchText The search text. - * @param suggesterName The name of the suggester. - * @return A {@link SuggestPagedFlux} that iterates over {@link SuggestResult} objects and provides access to the - * {@link SuggestPagedResponse} object for each page containing HTTP response and coverage information. - * @see Suggestions - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - public SuggestPagedFlux suggest(String searchText, String suggesterName) { - return suggest(searchText, suggesterName, null); + public PagedFlux getIndexStatsSummary(RequestOptions requestOptions) { + return this.serviceClient.getIndexStatsSummaryAsync(requestOptions); } /** - * Suggests documents in the index that match the given partial query. - * - *

Code Sample

- * - *

Suggest text from documents in service with option.

- * - * - *
-     * SEARCH_ASYNC_CLIENT.suggest("searchText", "sg",
-     *     new SuggestOptions().setOrderBy("hotelId desc"))
-     *     .subscribe(results -> {
-     *         for (Map.Entry<String, Object> keyValuePair: results.getDocument(SearchDocument.class).entrySet()) {
-     *             System.out.printf("Document key %s, document value %s", keyValuePair.getKey(),
-     *                 keyValuePair.getValue());
-     *         }
-     *     });
-     * 
- * - * - * @param searchText The search text. - * @param suggesterName The name of the suggester. - * @param suggestOptions Parameters to further refine the suggestion query. - * @return A {@link SuggestPagedFlux} that iterates over {@link SuggestResult} objects and provides access to the - * {@link SuggestPagedResponse} object for each page containing HTTP response and coverage information. - * @see Suggestions + * Gets service level statistics for a search service. + * + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return service level statistics for a search service on successful completion of {@link Mono}. */ - @ServiceMethod(returns = ReturnType.COLLECTION) - public SuggestPagedFlux suggest(String searchText, String suggesterName, SuggestOptions suggestOptions) { - SuggestRequest suggestRequest - = createSuggestRequest(searchText, suggesterName, Utility.ensureSuggestOptions(suggestOptions)); - - return new SuggestPagedFlux(() -> withContext(context -> suggest(suggestRequest, context))); - } - - private Mono suggest(SuggestRequest suggestRequest, Context context) { - return restClient.getDocuments() - .suggestPostWithResponseAsync(suggestRequest, null, context) - .onErrorMap(MappingUtils::exceptionMapper) - .map(response -> { - SuggestDocumentsResult result = response.getValue(); - - return new SuggestPagedResponse(new SimpleResponse<>(response, getSuggestResults(result, serializer)), - result.getCoverage()); - }); - } - - static List getSuggestResults(SuggestDocumentsResult result, JsonSerializer serializer) { - return result.getResults() - .stream() - .map(suggestResult -> SuggestResultConverter.map(suggestResult, serializer)) - .collect(Collectors.toList()); + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono getServiceStatistics() { + // Generated convenience method for getServiceStatisticsWithResponse + RequestOptions requestOptions = new RequestOptions(); + return getServiceStatisticsWithResponse(requestOptions).flatMap(FluxUtil::toMono) + .map(protocolMethodData -> protocolMethodData.toObject(SearchServiceStatistics.class)); } /** - * Autocompletes incomplete query terms based on input text and matching terms in the index. - * - *

Code Sample

- * - *

Autocomplete text from documents in service.

- * - * - *
-     * SEARCH_ASYNC_CLIENT.autocomplete("searchText", "sg")
-     *     .subscribe(result -> System.out.printf("The complete term is %s", result.getText()));
-     * 
- * - * - * @param searchText search text - * @param suggesterName suggester name - * @return auto complete result. + * Retrieves a summary of statistics for all indexes in the search service. + * + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return response from a request to retrieve stats summary of all indexes as paginated response with + * {@link PagedFlux}. */ + @Generated @ServiceMethod(returns = ReturnType.COLLECTION) - public AutocompletePagedFlux autocomplete(String searchText, String suggesterName) { - return autocomplete(searchText, suggesterName, null); + public PagedFlux getIndexStatsSummary() { + // Generated convenience method for getIndexStatsSummary + RequestOptions requestOptions = new RequestOptions(); + PagedFlux pagedFluxResponse = getIndexStatsSummary(requestOptions); + return PagedFlux.create(() -> (continuationTokenParam, pageSizeParam) -> { + Flux> flux = (continuationTokenParam == null) + ? pagedFluxResponse.byPage().take(1) + : pagedFluxResponse.byPage(continuationTokenParam).take(1); + return flux + .map(pagedResponse -> new PagedResponseBase(pagedResponse.getRequest(), + pagedResponse.getStatusCode(), pagedResponse.getHeaders(), + pagedResponse.getValue() + .stream() + .map(protocolMethodData -> protocolMethodData.toObject(IndexStatisticsSummary.class)) + .collect(Collectors.toList()), + pagedResponse.getContinuationToken(), null)); + }); } - - /** - * Autocompletes incomplete query terms based on input text and matching terms in the index. - * - *

Code Sample

- * - *

Autocomplete text from documents in service with option.

- * - * - *
-     * SEARCH_ASYNC_CLIENT.autocomplete("searchText", "sg",
-     *     new AutocompleteOptions().setAutocompleteMode(AutocompleteMode.ONE_TERM_WITH_CONTEXT))
-     *     .subscribe(result ->
-     *         System.out.printf("The complete term is %s", result.getText())
-     *     );
-     * 
- * - * - * @param searchText search text - * @param suggesterName suggester name - * @param autocompleteOptions autocomplete options - * @return auto complete result. - */ - public AutocompletePagedFlux autocomplete(String searchText, String suggesterName, - AutocompleteOptions autocompleteOptions) { - AutocompleteRequest request = createAutoCompleteRequest(searchText, suggesterName, autocompleteOptions); - - return new AutocompletePagedFlux(() -> withContext(context -> autocomplete(request, context))); - } - - AutocompletePagedFlux autocomplete(String searchText, String suggesterName, AutocompleteOptions autocompleteOptions, - Context context) { - AutocompleteRequest request = createAutoCompleteRequest(searchText, suggesterName, autocompleteOptions); - - return new AutocompletePagedFlux(() -> autocomplete(request, context)); - } - - private Mono autocomplete(AutocompleteRequest request, Context context) { - return restClient.getDocuments() - .autocompletePostWithResponseAsync(request, null, context) - .onErrorMap(MappingUtils::exceptionMapper) - .map(response -> new AutocompletePagedResponse(new SimpleResponse<>(response, response.getValue()))); - } - - /** - * Create search request from search text and parameters - * - * @param searchText search text - * @param options search options - * @return SearchRequest - */ - static SearchRequest createSearchRequest(String searchText, SearchOptions options) { - SearchRequest request = new SearchRequest().setSearchText(searchText); - - if (options == null) { - return request; - } - - List scoringParameters = options.getScoringParameters() == null - ? null - : options.getScoringParameters().stream().map(ScoringParameter::toString).collect(Collectors.toList()); - - request.setQueryType(options.getQueryType()) - .setIncludeTotalResultCount(options.isTotalCountIncluded()) - .setFacets(options.getFacets()) - .setFilter(options.getFilter()) - .setHighlightFields(nullSafeStringJoin(options.getHighlightFields())) - .setHighlightPostTag(options.getHighlightPostTag()) - .setHighlightPreTag(options.getHighlightPreTag()) - .setMinimumCoverage(options.getMinimumCoverage()) - .setOrderBy(nullSafeStringJoin(options.getOrderBy())) - .setScoringParameters(scoringParameters) - .setScoringProfile(options.getScoringProfile()) - .setSearchFields(nullSafeStringJoin(options.getSearchFields())) - .setSearchMode(options.getSearchMode()) - .setScoringStatistics(options.getScoringStatistics()) - .setSessionId(options.getSessionId()) - .setSelect(nullSafeStringJoin(options.getSelect())) - .setSkip(options.getSkip()) - .setTop(options.getTop()) - .setQueryLanguage(options.getQueryLanguage()) - .setSpeller(options.getSpeller()) - .setDebug(options.getDebug()); - - SemanticSearchOptions semanticSearchOptions = options.getSemanticSearchOptions(); - if (semanticSearchOptions != null) { - Integer waitInMillis = semanticSearchOptions.getMaxWaitDuration() == null - ? null - : (int) semanticSearchOptions.getMaxWaitDuration().toMillis(); - request.setSemanticConfiguration(semanticSearchOptions.getSemanticConfigurationName()) - .setSemanticErrorHandling(semanticSearchOptions.getErrorMode()) - .setSemanticMaxWaitInMilliseconds(waitInMillis) - .setAnswers(createSearchRequestAnswers(semanticSearchOptions.getQueryAnswer())) - .setCaptions(createSearchRequestCaptions(semanticSearchOptions.getQueryCaption())) - .setSemanticQuery(semanticSearchOptions.getSemanticQuery()) - .setQueryRewrites(createQueryRewrites(semanticSearchOptions.getQueryRewrites())); - } - - VectorSearchOptions vectorSearchOptions = options.getVectorSearchOptions(); - if (vectorSearchOptions != null) { - request.setVectorFilterMode(vectorSearchOptions.getFilterMode()) - .setVectorQueries(vectorSearchOptions.getQueries()); - } - - return request; - } - - static String createSearchRequestAnswers(QueryAnswer queryAnswer) { - if (queryAnswer == null) { - return null; - } - - QueryAnswerType queryAnswerType = queryAnswer.getAnswerType(); - Integer answersCount = queryAnswer.getCount(); - Double answerThreshold = queryAnswer.getThreshold(); - Integer maxCharLength = queryAnswer.getMaxCharLength(); - - // No answer has been defined. - if (queryAnswerType == null) { - return null; - } - - String answerType = queryAnswerType.toString(); - - if (queryAnswerType == QueryAnswerType.NONE - || (answersCount == null && answerThreshold == null && maxCharLength == null)) { - return answerType; - } - - StringBuilder answerStringBuilder = new StringBuilder(answerType).append('|'); - - if (answersCount != null) { - answerStringBuilder.append("count-").append(answersCount).append(","); - } - - if (answerThreshold != null) { - answerStringBuilder.append("threshold-").append(answerThreshold).append(","); - } - - if (maxCharLength != null) { - answerStringBuilder.append("maxCharLength-").append(maxCharLength).append(","); - } - - if (answerStringBuilder.charAt(answerStringBuilder.length() - 1) == ',') { - answerStringBuilder.deleteCharAt(answerStringBuilder.length() - 1); - } - - return answerStringBuilder.toString(); - } - - static String createSearchRequestCaptions(QueryCaption queryCaption) { - if (queryCaption == null) { - return null; - } - - QueryCaptionType queryCaptionType = queryCaption.getCaptionType(); - Boolean highlightEnabled = queryCaption.isHighlightEnabled(); - Integer maxCharLength = queryCaption.getMaxCharLength(); - - // No caption has been defined. - if (queryCaptionType == null) { - return null; - } - - String queryCaptionTypeString = queryCaptionType.toString(); - - if (queryCaptionType == QueryCaptionType.NONE || (highlightEnabled == null && maxCharLength == null)) { - return queryCaptionTypeString; - } - - StringBuilder captionStringBuilder = new StringBuilder(queryCaptionTypeString).append('|'); - - if (highlightEnabled != null) { - captionStringBuilder.append("highlight-").append(highlightEnabled).append(","); - } - - if (maxCharLength != null) { - captionStringBuilder.append("maxCharLength-").append(maxCharLength).append(","); - } - - if (captionStringBuilder.charAt(captionStringBuilder.length() - 1) == ',') { - captionStringBuilder.deleteCharAt(captionStringBuilder.length() - 1); - } - - return captionStringBuilder.toString(); - } - - static String createQueryRewrites(QueryRewrites queryRewrites) { - if (queryRewrites == null) { - return null; - } - return queryRewrites.toString(); - } - - /** - * Create suggest request from search text, suggester name, and parameters - * - * @param searchText search text - * @param suggesterName search text - * @param options suggest options - * @return SuggestRequest - */ - static SuggestRequest createSuggestRequest(String searchText, String suggesterName, SuggestOptions options) { - SuggestRequest request = new SuggestRequest(searchText, suggesterName); - - if (options == null) { - return request; - } - - return request.setFilter(options.getFilter()) - .setUseFuzzyMatching(options.useFuzzyMatching()) - .setHighlightPostTag(options.getHighlightPostTag()) - .setHighlightPreTag(options.getHighlightPreTag()) - .setMinimumCoverage(options.getMinimumCoverage()) - .setOrderBy(nullSafeStringJoin(options.getOrderBy())) - .setSearchFields(nullSafeStringJoin(options.getSearchFields())) - .setSelect(nullSafeStringJoin(options.getSelect())) - .setTop(options.getTop()); - } - - /** - * Create Autocomplete request from search text, suggester name, and parameters - * - * @param searchText search text - * @param suggesterName search text - * @param options autocomplete options - * @return AutocompleteRequest - */ - static AutocompleteRequest createAutoCompleteRequest(String searchText, String suggesterName, - AutocompleteOptions options) { - AutocompleteRequest request = new AutocompleteRequest(searchText, suggesterName); - - if (options == null) { - return request; - } - - return request.setAutocompleteMode(options.getAutocompleteMode()) - .setFilter(options.getFilter()) - .setUseFuzzyMatching(options.useFuzzyMatching()) - .setHighlightPostTag(options.getHighlightPostTag()) - .setHighlightPreTag(options.getHighlightPreTag()) - .setMinimumCoverage(options.getMinimumCoverage()) - .setSearchFields(nullSafeStringJoin(options.getSearchFields())) - .setTop(options.getTop()); - } - - private static String nullSafeStringJoin(Iterable elements) { - if (elements == null) { - return null; - } - - return String.join(",", elements); - } - - static IndexDocumentsBatch buildIndexBatch(Iterable documents, IndexActionType actionType) { - List> actions = new ArrayList<>(); - documents.forEach(d -> actions.add(new IndexAction().setActionType(actionType).setDocument(d))); - - return new IndexDocumentsBatch().addActions(actions); - } - } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/SearchClient.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/SearchClient.java index 545b440f9e13..306af3dfb4ac 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/SearchClient.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/SearchClient.java @@ -1,1181 +1,152 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.search.documents; +import com.azure.core.annotation.Generated; import com.azure.core.annotation.ReturnType; import com.azure.core.annotation.ServiceClient; import com.azure.core.annotation.ServiceMethod; -import com.azure.core.http.HttpPipeline; +import com.azure.core.exception.ClientAuthenticationException; +import com.azure.core.exception.HttpResponseException; +import com.azure.core.exception.ResourceModifiedException; +import com.azure.core.exception.ResourceNotFoundException; +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.http.rest.RequestOptions; import com.azure.core.http.rest.Response; -import com.azure.core.http.rest.SimpleResponse; -import com.azure.core.util.Context; -import com.azure.core.util.logging.ClientLogger; -import com.azure.core.util.serializer.JsonSerializer; -import com.azure.search.documents.implementation.SearchIndexClientImpl; -import com.azure.search.documents.implementation.converters.IndexActionConverter; -import com.azure.search.documents.implementation.models.AutocompleteRequest; -import com.azure.search.documents.implementation.models.ErrorResponseException; -import com.azure.search.documents.implementation.models.SearchContinuationToken; -import com.azure.search.documents.implementation.models.SearchDocumentsResult; -import com.azure.search.documents.implementation.models.SearchFirstPageResponseWrapper; -import com.azure.search.documents.implementation.models.SearchRequest; -import com.azure.search.documents.implementation.models.SuggestDocumentsResult; -import com.azure.search.documents.implementation.models.SuggestRequest; -import com.azure.search.documents.implementation.util.Utility; -import com.azure.search.documents.indexes.models.IndexDocumentsBatch; -import com.azure.search.documents.models.AutocompleteOptions; -import com.azure.search.documents.models.AutocompleteResult; -import com.azure.search.documents.models.IndexActionType; -import com.azure.search.documents.models.IndexBatchException; -import com.azure.search.documents.models.IndexDocumentsOptions; -import com.azure.search.documents.models.IndexDocumentsResult; -import com.azure.search.documents.models.SearchOptions; -import com.azure.search.documents.models.SearchResult; -import com.azure.search.documents.models.SuggestOptions; -import com.azure.search.documents.models.SuggestResult; -import com.azure.search.documents.util.AutocompletePagedIterable; -import com.azure.search.documents.util.AutocompletePagedResponse; -import com.azure.search.documents.util.SearchPagedIterable; -import com.azure.search.documents.util.SearchPagedResponse; -import com.azure.search.documents.util.SuggestPagedIterable; -import com.azure.search.documents.util.SuggestPagedResponse; - -import java.util.List; -import java.util.Map; -import java.util.function.Function; -import java.util.stream.Collectors; - -import static com.azure.core.util.serializer.TypeReference.createInstance; -import static com.azure.search.documents.SearchAsyncClient.buildIndexBatch; -import static com.azure.search.documents.SearchAsyncClient.createAutoCompleteRequest; -import static com.azure.search.documents.SearchAsyncClient.createContinuationToken; -import static com.azure.search.documents.SearchAsyncClient.createSearchRequest; -import static com.azure.search.documents.SearchAsyncClient.createSuggestRequest; -import static com.azure.search.documents.SearchAsyncClient.getSearchResults; -import static com.azure.search.documents.SearchAsyncClient.getSuggestResults; +import com.azure.core.util.BinaryData; +import com.azure.search.documents.implementation.SearchClientImpl; +import com.azure.search.documents.models.IndexStatisticsSummary; +import com.azure.search.documents.models.SearchServiceStatistics; /** - * This class provides a client that contains the operations for querying an index and uploading, merging, or deleting - * documents in an Azure AI Search service. - * - *

- * Overview - *

- * - *

- * Conceptually, a document is an entity in your index. Mapping this concept to more familiar database equivalents: - * a search index equates to a table, and documents are roughly equivalent to rows in a table. Documents exist only - * in an index, and are retrieved only through queries that target the documents collection (/docs) of an index. All - * operations performed on the collection such as uploading, merging, deleting, or querying documents take place in - * the context of a single index, so the URL format document operations will always include /indexes/[index name]/docs - * for a given index name. - *

- * - *

- * This client provides a synchronous API for accessing and performing operations on indexed documents. This client - * assists with searching your indexed documents, autocompleting partially typed search terms based on documents within the index, - * suggesting the most likely matching text in documents as a user types. The client provides operations for adding, updating, and deleting - * documents from an index. - *

- * - *

- * Getting Started - *

- * - *

- * Authenticating and building instances of this client are handled by {@link SearchClientBuilder}. This sample shows - * you how to authenticate and create an instance of the client: - *

- * - * - *
- * SearchClient searchClient = new SearchClientBuilder()
- *     .credential(new AzureKeyCredential("{key}"))
- *     .endpoint("{endpoint}")
- *     .indexName("{indexName}")
- *     .buildClient();
- * 
- * - * - *

- * For more information on authentication and building, see the {@link SearchClientBuilder} documentation. - *

- * - *
- * - *

- * Examples - *

- * - *

- * The following examples all use a simple Hotel - * data set that you can - * import into your own index from the Azure portal. - * These are just a few of the basics - please check out our Samples for much more. - *

- * - *

- * Upload a Document - *

- * - *

- * The following sample uploads a new document to an index. - *

- * - * - *
- * List<Hotel> hotels = new ArrayList<>();
- * hotels.add(new Hotel().setHotelId("100"));
- * hotels.add(new Hotel().setHotelId("200"));
- * hotels.add(new Hotel().setHotelId("300"));
- * searchClient.uploadDocuments(hotels);
- * 
- * - * - * - * For an asynchronous sample see {@link SearchAsyncClient#uploadDocuments(Iterable)}. - * - * - *

- * Merge a Document - *

- * - *

- * The following sample merges documents in an index. - *

- * - * - *
- * List<Hotel> hotels = new ArrayList<>();
- * hotels.add(new Hotel().setHotelId("100"));
- * hotels.add(new Hotel().setHotelId("200"));
- * searchClient.mergeDocuments(hotels);
- * 
- * - * - * - * For an asynchronous sample see {@link SearchAsyncClient#mergeDocuments(Iterable)}. - * - * - *

- * Delete a Document - *

- * - *

- * The following sample deletes a document from an index. - *

- * - * - *
- * SearchDocument documentId = new SearchDocument();
- * documentId.put("hotelId", "100");
- * searchClient.deleteDocuments(Collections.singletonList(documentId));
- * 
- * - * - * - * For an asynchronous sample see {@link SearchAsyncClient#deleteDocuments(Iterable)}. - * - * - *

- * Get a Document - *

- * - *

- * The following sample gets a document from an index. - *

- * - * - *
- * Hotel hotel = searchClient.getDocument("100", Hotel.class);
- * System.out.printf("Retrieved Hotel %s%n", hotel.getHotelId());
- * 
- * - * - * - * For an asynchronous sample see {@link SearchAsyncClient#getDocument(String, Class)}. - * - * - *

- * Search Documents - *

- * - *

- * The following sample searches for documents within an index. - *

- * - * - *
- * SearchDocument searchDocument = new SearchDocument();
- * searchDocument.put("hotelId", "8");
- * searchDocument.put("description", "budget");
- * searchDocument.put("descriptionFr", "motel");
- *
- * SearchDocument searchDocument1 = new SearchDocument();
- * searchDocument1.put("hotelId", "9");
- * searchDocument1.put("description", "budget");
- * searchDocument1.put("descriptionFr", "motel");
- *
- * List<SearchDocument> searchDocuments = new ArrayList<>();
- * searchDocuments.add(searchDocument);
- * searchDocuments.add(searchDocument1);
- * searchClient.uploadDocuments(searchDocuments);
- *
- * SearchPagedIterable results = searchClient.search("SearchText");
- * System.out.printf("There are %s results.%n", results.getTotalCount());
- * 
- * - * - * For an asynchronous sample see {@link SearchAsyncClient#search(String)}. - * - * - *

- * Make a Suggestion - *

- * - *

- * The following sample suggests the most likely matching text in documents. - *

- * - * - *
- * SuggestPagedIterable suggestPagedIterable = searchClient.suggest("searchText", "sg");
- * for (SuggestResult result: suggestPagedIterable) {
- *     System.out.printf("The suggested text is %s", result.getText());
- * }
- * 
- * - * - * - * For an asynchronous sample see {@link SearchAsyncClient#suggest(String, String)}. - * - * - *

- * Provide an Autocompletion - *

- * - *

- * The following sample provides autocompletion for a partially typed query. - *

- * - * - *
- * AutocompletePagedIterable autocompletePagedIterable = searchClient.autocomplete("searchText", "sg");
- * for (AutocompleteItem result: autocompletePagedIterable) {
- *     System.out.printf("The complete term is %s", result.getText());
- * }
- * 
- * - * - * - * For an asynchronous sample see {@link SearchAsyncClient#autocomplete(String, String)}. - * - * - * @see SearchAsyncClient - * @see SearchClientBuilder - * @see com.azure.search.documents + * Initializes a new instance of the synchronous SearchClient type. */ @ServiceClient(builder = SearchClientBuilder.class) public final class SearchClient { - private static final ClientLogger LOGGER = new ClientLogger(SearchClient.class); - - /** - * Search REST API Version - */ - private final SearchServiceVersion serviceVersion; - - /** - * The endpoint for the Azure AI Search service. - */ - private final String endpoint; - - /** - * The name of the Azure AI Search index. - */ - private final String indexName; - - /** - * The underlying AutoRest client used to interact with the Azure AI Search service - */ - private final SearchIndexClientImpl restClient; - - /** - * The pipeline that powers this client. - */ - private final HttpPipeline httpPipeline; - - final JsonSerializer serializer; - - /** - * Package private constructor to be used by {@link SearchClientBuilder} - */ - SearchClient(String endpoint, String indexName, SearchServiceVersion serviceVersion, HttpPipeline httpPipeline, - JsonSerializer serializer, SearchIndexClientImpl restClient) { - this.endpoint = endpoint; - this.indexName = indexName; - this.serviceVersion = serviceVersion; - this.httpPipeline = httpPipeline; - this.serializer = serializer; - this.restClient = restClient; - } - - /** - * Gets the name of the Azure AI Search index. - * - * @return the indexName value. - */ - public String getIndexName() { - return this.indexName; - } - - /** - * Gets the {@link HttpPipeline} powering this client. - * - * @return the pipeline. - */ - HttpPipeline getHttpPipeline() { - return this.httpPipeline; - } - - /** - * Gets the endpoint for the Azure AI Search service. - * - * @return the endpoint value. - */ - public String getEndpoint() { - return this.endpoint; - } - - /** - * Uploads a collection of documents to the target index. - * - *

Code Sample

- * - *

Upload dynamic SearchDocument.

- * - * - *
-     * SearchDocument searchDocument = new SearchDocument();
-     * searchDocument.put("hotelId", "1");
-     * searchDocument.put("hotelName", "test");
-     * IndexDocumentsResult result = SEARCH_CLIENT.uploadDocuments(Collections.singletonList(searchDocument));
-     * for (IndexingResult indexingResult : result.getResults()) {
-     *     System.out.printf("Does document with key %s upload successfully? %b%n", indexingResult.getKey(),
-     *         indexingResult.isSucceeded());
-     * }
-     * 
- * - * - * @param documents collection of documents to upload to the target Index. - * @return document index result. - * @throws IndexBatchException If some of the indexing actions fail but other actions succeed and modify the state - * of the index. This can happen when the Search Service is under heavy indexing load. It is important to explicitly - * catch this exception and check the return value {@link IndexBatchException#getIndexingResults()}. The indexing - * result reports the status of each indexing action in the batch, making it possible to determine the state of the - * index after a partial failure. - * @see Add, update, or - * delete documents - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public IndexDocumentsResult uploadDocuments(Iterable documents) { - return uploadDocumentsWithResponse(documents, null, Context.NONE).getValue(); - } - - /** - * Uploads a collection of documents to the target index. - * - *

Code Sample

- * - *

Upload dynamic SearchDocument.

- * - * - *
-     * SearchDocument searchDocument = new SearchDocument();
-     * searchDocument.put("hotelId", "1");
-     * searchDocument.put("hotelName", "test");
-     * Response<IndexDocumentsResult> resultResponse = SEARCH_CLIENT.uploadDocumentsWithResponse(
-     *     Collections.singletonList(searchDocument), null, new Context(KEY_1, VALUE_1));
-     * System.out.println("The status code of the response is " + resultResponse.getStatusCode());
-     * for (IndexingResult indexingResult : resultResponse.getValue().getResults()) {
-     *     System.out.printf("Does document with key %s upload successfully? %b%n", indexingResult.getKey(),
-     *         indexingResult.isSucceeded());
-     * }
-     * 
- * - * - * @param documents collection of documents to upload to the target Index. - * @param options Options that allow specifying document indexing behavior. - * @param context additional context that is passed through the Http pipeline during the service call - * @return response containing the document index result. - * @throws IndexBatchException If some of the indexing actions fail but other actions succeed and modify the state - * of the index. This can happen when the Search Service is under heavy indexing load. It is important to explicitly - * catch this exception and check the return value {@link IndexBatchException#getIndexingResults()}. The indexing - * result reports the status of each indexing action in the batch, making it possible to determine the state of the - * index after a partial failure. - * @see Add, update, or - * delete documents - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Response uploadDocumentsWithResponse(Iterable documents, - IndexDocumentsOptions options, Context context) { - return indexDocumentsWithResponse(buildIndexBatch(documents, IndexActionType.UPLOAD), options, context); - } - - /** - * Merges a collection of documents with existing documents in the target index. - *

- * If the type of the document contains non-nullable primitive-typed properties, these properties may not merge - * correctly. If you do not set such a property, it will automatically take its default value (for example, {@code - * 0} for {@code int} or false for {@code boolean}), which will override the value of the property currently stored - * in the index, even if this was not your intent. For this reason, it is strongly recommended that you always - * declare primitive-typed properties with their class equivalents (for example, an integer property should be of - * type {@code Integer} instead of {@code int}). - * - *

Code Sample

- * - *

Merge dynamic SearchDocument.

- * - * - *
-     * SearchDocument searchDocument = new SearchDocument();
-     * searchDocument.put("hotelName", "merge");
-     * IndexDocumentsResult result = SEARCH_CLIENT.mergeDocuments(Collections.singletonList(searchDocument));
-     * for (IndexingResult indexingResult : result.getResults()) {
-     *     System.out.printf("Does document with key %s merge successfully? %b%n", indexingResult.getKey(),
-     *         indexingResult.isSucceeded());
-     * }
-     * 
- * - * - * @param documents collection of documents to be merged - * @return document index result - * @throws IndexBatchException If some of the indexing actions fail but other actions succeed and modify the state - * of the index. This can happen when the Search Service is under heavy indexing load. It is important to explicitly - * catch this exception and check the return value {@link IndexBatchException#getIndexingResults()}. The indexing - * result reports the status of each indexing action in the batch, making it possible to determine the state of the - * index after a partial failure. - * @see Add, update, or - * delete documents - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public IndexDocumentsResult mergeDocuments(Iterable documents) { - return mergeDocumentsWithResponse(documents, null, Context.NONE).getValue(); - } - - /** - * Merges a collection of documents with existing documents in the target index. - *

- * If the type of the document contains non-nullable primitive-typed properties, these properties may not merge - * correctly. If you do not set such a property, it will automatically take its default value (for example, {@code - * 0} for {@code int} or false for {@code boolean}), which will override the value of the property currently stored - * in the index, even if this was not your intent. For this reason, it is strongly recommended that you always - * declare primitive-typed properties with their class equivalents (for example, an integer property should be of - * type {@code Integer} instead of {@code int}). - * - *

Code Sample

- * - *

Merge dynamic SearchDocument.

- * - * - *
-     * SearchDocument searchDocument = new SearchDocument();
-     * searchDocument.put("hotelName", "test");
-     * Response<IndexDocumentsResult> resultResponse = SEARCH_CLIENT.mergeDocumentsWithResponse(
-     *     Collections.singletonList(searchDocument), null, new Context(KEY_1, VALUE_1));
-     * System.out.println("The status code of the response is " + resultResponse.getStatusCode());
-     * for (IndexingResult indexingResult : resultResponse.getValue().getResults()) {
-     *     System.out.printf("Does document with key %s merge successfully? %b%n", indexingResult.getKey(),
-     *         indexingResult.isSucceeded());
-     * }
-     * 
- * - * - * @param documents collection of documents to be merged. - * @param options Options that allow specifying document indexing behavior. - * @param context additional context that is passed through the Http pipeline during the service call - * @return response containing the document index result. - * @throws IndexBatchException If some of the indexing actions fail but other actions succeed and modify the state - * of the index. This can happen when the Search Service is under heavy indexing load. It is important to explicitly - * catch this exception and check the return value {@link IndexBatchException#getIndexingResults()}. The indexing - * result reports the status of each indexing action in the batch, making it possible to determine the state of the - * index after a partial failure. - * @see Add, update, or - * delete documents - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Response mergeDocumentsWithResponse(Iterable documents, - IndexDocumentsOptions options, Context context) { - return indexDocumentsWithResponse(buildIndexBatch(documents, IndexActionType.MERGE), options, context); - } - - /** - * This action behaves like merge if a document with the given key already exists in the index. If the document does - * not exist, it behaves like upload with a new document. - *

- * If the type of the document contains non-nullable primitive-typed properties, these properties may not merge - * correctly. If you do not set such a property, it will automatically take its default value (for example, {@code - * 0} for {@code int} or false for {@code boolean}), which will override the value of the property currently stored - * in the index, even if this was not your intent. For this reason, it is strongly recommended that you always - * declare primitive-typed properties with their class equivalents (for example, an integer property should be of - * type {@code Integer} instead of {@code int}). - * - *

Code Sample

- * - *

Merge or upload dynamic SearchDocument.

- * - * - *
-     * SearchDocument searchDocument = new SearchDocument();
-     * searchDocument.put("hotelId", "1");
-     * searchDocument.put("hotelName", "test");
-     * IndexDocumentsResult result = SEARCH_CLIENT.mergeOrUploadDocuments(Collections.singletonList(searchDocument));
-     * for (IndexingResult indexingResult : result.getResults()) {
-     *     System.out.printf("Does document with key %s mergeOrUpload successfully? %b%n", indexingResult.getKey(),
-     *         indexingResult.isSucceeded());
-     * }
-     * 
- * - * - * @param documents collection of documents to be merged, if exists, otherwise uploaded - * @return document index result - * @throws IndexBatchException If some of the indexing actions fail but other actions succeed and modify the state - * of the index. This can happen when the Search Service is under heavy indexing load. It is important to explicitly - * catch this exception and check the return value {@link IndexBatchException#getIndexingResults()}. The indexing - * result reports the status of each indexing action in the batch, making it possible to determine the state of the - * index after a partial failure. - * @see Add, update, or - * delete documents - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public IndexDocumentsResult mergeOrUploadDocuments(Iterable documents) { - return mergeOrUploadDocumentsWithResponse(documents, null, Context.NONE).getValue(); - } - - /** - * This action behaves like merge if a document with the given key already exists in the index. If the document does - * not exist, it behaves like upload with a new document. - *

- * If the type of the document contains non-nullable primitive-typed properties, these properties may not merge - * correctly. If you do not set such a property, it will automatically take its default value (for example, {@code - * 0} for {@code int} or false for {@code boolean}), which will override the value of the property currently stored - * in the index, even if this was not your intent. For this reason, it is strongly recommended that you always - * declare primitive-typed properties with their class equivalents (for example, an integer property should be of - * type {@code Integer} instead of {@code int}). - * - *

Code Sample

- * - *

Merge or upload dynamic SearchDocument.

- * - * - *
-     * SearchDocument searchDocument = new SearchDocument();
-     * searchDocument.put("hotelId", "1");
-     * searchDocument.put("hotelName", "test");
-     * Response<IndexDocumentsResult> resultResponse = SEARCH_CLIENT.mergeOrUploadDocumentsWithResponse(
-     *     Collections.singletonList(searchDocument), null, new Context(KEY_1, VALUE_1));
-     * System.out.println("The status code of the response is " + resultResponse.getStatusCode());
-     * for (IndexingResult indexingResult : resultResponse.getValue().getResults()) {
-     *     System.out.printf("Does document with key %s mergeOrUpload successfully? %b%n", indexingResult.getKey(),
-     *         indexingResult.isSucceeded());
-     * }
-     * 
- * - * - * @param documents collection of documents to be merged, if exists, otherwise uploaded - * @param options Options that allow specifying document indexing behavior. - * @param context additional context that is passed through the Http pipeline during the service call - * @return response containing a document index result - * @throws IndexBatchException If some of the indexing actions fail but other actions succeed and modify the state - * of the index. This can happen when the Search Service is under heavy indexing load. It is important to explicitly - * catch this exception and check the return value {@link IndexBatchException#getIndexingResults()}. The indexing - * result reports the status of each indexing action in the batch, making it possible to determine the state of the - * index after a partial failure. - * @see Add, update, or - * delete documents - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Response mergeOrUploadDocumentsWithResponse(Iterable documents, - IndexDocumentsOptions options, Context context) { - return indexDocumentsWithResponse(buildIndexBatch(documents, IndexActionType.MERGE_OR_UPLOAD), options, - context); - } - - /** - * Deletes a collection of documents from the target index. - * - *

Code Sample

- * - *

Delete dynamic SearchDocument.

- * - * - *
-     * SearchDocument searchDocument = new SearchDocument();
-     * searchDocument.put("hotelId", "1");
-     * searchDocument.put("hotelName", "test");
-     * IndexDocumentsResult result = SEARCH_CLIENT.deleteDocuments(Collections.singletonList(searchDocument));
-     * for (IndexingResult indexingResult : result.getResults()) {
-     *     System.out.printf("Does document with key %s delete successfully? %b%n", indexingResult.getKey(),
-     *         indexingResult.isSucceeded());
-     * }
-     * 
- * - * - * @param documents collection of documents to delete from the target Index. Fields other than the key are ignored. - * @return document index result. - * @throws IndexBatchException If some of the indexing actions fail but other actions succeed and modify the state - * of the index. This can happen when the Search Service is under heavy indexing load. It is important to explicitly - * catch this exception and check the return value {@link IndexBatchException#getIndexingResults()}. The indexing - * result reports the status of each indexing action in the batch, making it possible to determine the state of the - * index after a partial failure. - * @see Add, update, or - * delete documents - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public IndexDocumentsResult deleteDocuments(Iterable documents) { - return deleteDocumentsWithResponse(documents, null, Context.NONE).getValue(); - } - - /** - * Deletes a collection of documents from the target index. - * - *

Code Sample

- * - *

Delete dynamic SearchDocument.

- * - * - *
-     * SearchDocument searchDocument = new SearchDocument();
-     * searchDocument.put("hotelId", "1");
-     * searchDocument.put("hotelName", "test");
-     * Response<IndexDocumentsResult> resultResponse = SEARCH_CLIENT.deleteDocumentsWithResponse(
-     *     Collections.singletonList(searchDocument), null, new Context(KEY_1, VALUE_1));
-     * System.out.println("The status code of the response is " + resultResponse.getStatusCode());
-     * for (IndexingResult indexingResult : resultResponse.getValue().getResults()) {
-     *     System.out.printf("Does document with key %s delete successfully? %b%n", indexingResult.getKey(),
-     *         indexingResult.isSucceeded());
-     * }
-     * 
- * - * - * @param documents collection of documents to delete from the target Index. Fields other than the key are ignored. - * @param options Options that allow specifying document indexing behavior. - * @param context additional context that is passed through the Http pipeline during the service call - * @return response containing a document index result. - * @throws IndexBatchException If some of the indexing actions fail but other actions succeed and modify the state - * of the index. This can happen when the Search Service is under heavy indexing load. It is important to explicitly - * catch this exception and check the return value {@link IndexBatchException#getIndexingResults()}. The indexing - * result reports the status of each indexing action in the batch, making it possible to determine the state of the - * index after a partial failure. - * @see Add, update, or - * delete documents - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Response deleteDocumentsWithResponse(Iterable documents, - IndexDocumentsOptions options, Context context) { - return indexDocumentsWithResponse(buildIndexBatch(documents, IndexActionType.DELETE), options, context); - } - - /** - * Sends a batch of upload, merge, and/or delete actions to the search index. - * - *

Code Sample

- * - *

Index batch operation on dynamic SearchDocument.

- * - * - *
-     * SearchDocument searchDocument1 = new SearchDocument();
-     * searchDocument1.put("hotelId", "1");
-     * searchDocument1.put("hotelName", "test1");
-     * SearchDocument searchDocument2 = new SearchDocument();
-     * searchDocument2.put("hotelId", "2");
-     * searchDocument2.put("hotelName", "test2");
-     * IndexDocumentsBatch<SearchDocument> indexDocumentsBatch = new IndexDocumentsBatch<>();
-     * indexDocumentsBatch.addUploadActions(Collections.singletonList(searchDocument1));
-     * indexDocumentsBatch.addDeleteActions(Collections.singletonList(searchDocument2));
-     * IndexDocumentsResult result = SEARCH_CLIENT.indexDocuments(indexDocumentsBatch);
-     * for (IndexingResult indexingResult : result.getResults()) {
-     *     System.out.printf("Does document with key %s finish successfully? %b%n", indexingResult.getKey(),
-     *         indexingResult.isSucceeded());
-     * }
-     * 
- * - * - * @param batch The batch of index actions - * @return Response containing the status of operations for all actions in the batch - * @throws IndexBatchException If some of the indexing actions fail but other actions succeed and modify the state - * of the index. This can happen when the Search Service is under heavy indexing load. It is important to explicitly - * catch this exception and check the return value {@link IndexBatchException#getIndexingResults()}. The indexing - * result reports the status of each indexing action in the batch, making it possible to determine the state of the - * index after a partial failure. - * @see Add, update, or - * delete documents - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public IndexDocumentsResult indexDocuments(IndexDocumentsBatch batch) { - return indexDocumentsWithResponse(batch, null, Context.NONE).getValue(); - } - - /** - * Sends a batch of upload, merge, and/or delete actions to the search index. - * - *

Code Sample

- * - *

Index batch operation on dynamic SearchDocument.

- * - * - *
-     * SearchDocument searchDocument1 = new SearchDocument();
-     * searchDocument1.put("hotelId", "1");
-     * searchDocument1.put("hotelName", "test1");
-     * SearchDocument searchDocument2 = new SearchDocument();
-     * searchDocument2.put("hotelId", "2");
-     * searchDocument2.put("hotelName", "test2");
-     * IndexDocumentsBatch<SearchDocument> indexDocumentsBatch = new IndexDocumentsBatch<>();
-     * indexDocumentsBatch.addUploadActions(Collections.singletonList(searchDocument1));
-     * indexDocumentsBatch.addDeleteActions(Collections.singletonList(searchDocument2));
-     * Response<IndexDocumentsResult> resultResponse = SEARCH_CLIENT.indexDocumentsWithResponse(indexDocumentsBatch,
-     *     null, new Context(KEY_1, VALUE_1));
-     * System.out.println("The status code of the response is " + resultResponse.getStatusCode());
-     * for (IndexingResult indexingResult : resultResponse.getValue().getResults()) {
-     *     System.out.printf("Does document with key %s finish successfully? %b%n", indexingResult.getKey(),
-     *         indexingResult.isSucceeded());
-     * }
-     * 
- * - * - * @param batch The batch of index actions - * @param options Options that allow specifying document indexing behavior. - * @param context additional context that is passed through the Http pipeline during the service call - * @return Response containing the status of operations for all actions in the batch - * @throws IndexBatchException If some of the indexing actions fail but other actions succeed and modify the state - * of the index. This can happen when the Search Service is under heavy indexing load. It is important to explicitly - * catch this exception and check the return value {@link IndexBatchException#getIndexingResults()}. The indexing - * result reports the status of each indexing action in the batch, making it possible to determine the state of the - * index after a partial failure. - * @see Add, update, or - * delete documents - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Response indexDocumentsWithResponse(IndexDocumentsBatch batch, - IndexDocumentsOptions options, Context context) { - List indexActions = batch.getActions() - .stream() - .map(document -> IndexActionConverter.map(document, serializer)) - .collect(Collectors.toList()); - - boolean throwOnAnyError = options == null || options.throwOnAnyError(); - return Utility.indexDocumentsWithResponse(restClient, indexActions, throwOnAnyError, context, LOGGER); - } - - /** - * Retrieves a document from the Azure AI Search index. - *

- * View naming rules for guidelines on - * constructing valid document keys. - * - *

Code Sample

- * - *

Get dynamic SearchDocument.

- * - * - *
-     * SearchDocument result = SEARCH_CLIENT.getDocument("hotelId", SearchDocument.class);
-     * for (Map.Entry<String, Object> keyValuePair : result.entrySet()) {
-     *     System.out.printf("Document key %s, Document value %s", keyValuePair.getKey(), keyValuePair.getValue());
-     * }
-     * 
- * - * - * @param key The key of the document to retrieve. - * @param modelClass The model class converts to. - * @param Convert document to the generic type. - * @return document object - * @see Lookup document - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public T getDocument(String key, Class modelClass) { - return getDocumentWithResponse(key, modelClass, null, Context.NONE).getValue(); - } - - /** - * Retrieves a document from the Azure AI Search index. - *

- * View naming rules for guidelines on - * constructing valid document keys. - * - *

Code Sample

- * - *

Get dynamic SearchDocument.

- * - * - *
-     * Response<SearchDocument> resultResponse = SEARCH_CLIENT.getDocumentWithResponse("hotelId",
-     *     SearchDocument.class, null, new Context(KEY_1, VALUE_1));
-     * System.out.println("The status code of the response is " + resultResponse.getStatusCode());
-     * for (Map.Entry<String, Object> keyValuePair : resultResponse.getValue().entrySet()) {
-     *     System.out.printf("Document key %s, Document value %s", keyValuePair.getKey(), keyValuePair.getValue());
-     * }
-     * 
- * - * - * @param Convert document to the generic type. - * @param key The key of the document to retrieve. - * @param modelClass The model class converts to. - * @param selectedFields List of field names to retrieve for the document; Any field not retrieved will have null or - * default as its corresponding property value in the returned object. - * @param context additional context that is passed through the Http pipeline during the service call - * @return response containing a document object - * @see Lookup document - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Response getDocumentWithResponse(String key, Class modelClass, List selectedFields, - Context context) { - - try { - Response> response - = restClient.getDocuments().getWithResponse(key, selectedFields, null, context); - - return new SimpleResponse<>(response, serializer - .deserializeFromBytes(serializer.serializeToBytes(response.getValue()), createInstance(modelClass))); - } catch (ErrorResponseException ex) { - throw LOGGER.logExceptionAsError(Utility.mapErrorResponseException(ex)); - } catch (RuntimeException ex) { - throw LOGGER.logExceptionAsError(ex); - } - } - - /** - * Queries the number of documents in the search index. - * - *

Code Sample

- * - *

Get document count.

- * - * - *
-     * long count = SEARCH_CLIENT.getDocumentCount();
-     * System.out.printf("There are %d documents in service.", count);
-     * 
- * - * - * @return the number of documents. - */ + @Generated + private final SearchClientImpl serviceClient; + + /** + * Initializes an instance of SearchClient class. + * + * @param serviceClient the service client implementation. + */ + @Generated + SearchClient(SearchClientImpl serviceClient) { + this.serviceClient = serviceClient; + } + + /** + * Gets service level statistics for a search service. + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     counters (Required): {
+     *         aliasesCount (Required): {
+     *             usage: long (Required)
+     *             quota: Long (Optional)
+     *         }
+     *         documentCount (Required): (recursive schema, see documentCount above)
+     *         indexesCount (Required): (recursive schema, see indexesCount above)
+     *         indexersCount (Required): (recursive schema, see indexersCount above)
+     *         dataSourcesCount (Required): (recursive schema, see dataSourcesCount above)
+     *         storageSize (Required): (recursive schema, see storageSize above)
+     *         synonymMaps (Required): (recursive schema, see synonymMaps above)
+     *         skillsetCount (Required): (recursive schema, see skillsetCount above)
+     *         vectorIndexSize (Required): (recursive schema, see vectorIndexSize above)
+     *     }
+     *     limits (Required): {
+     *         maxFieldsPerIndex: Integer (Optional)
+     *         maxFieldNestingDepthPerIndex: Integer (Optional)
+     *         maxComplexCollectionFieldsPerIndex: Integer (Optional)
+     *         maxComplexObjectsInCollectionsPerDocument: Integer (Optional)
+     *         maxStoragePerIndex: Long (Optional)
+     *     }
+     * }
+     * }
+     * 
+ * + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return service level statistics for a search service along with {@link Response}. + */ + @Generated @ServiceMethod(returns = ReturnType.SINGLE) - public long getDocumentCount() { - return getDocumentCountWithResponse(Context.NONE).getValue(); - } - - /** - * Queries the number of documents in the search index. - * - *

Code Sample

- * - *

Get document count.

- * - * - *
-     * Response<Long> countResponse = SEARCH_CLIENT.getDocumentCountWithResponse(new Context(KEY_1, VALUE_1));
-     * System.out.println("The status code of the response is " + countResponse.getStatusCode());
-     * System.out.printf("There are %d documents in service.", countResponse.getValue());
-     * 
- * - * - * @param context additional context that is passed through the Http pipeline during the service call - * @return response containing the number of documents. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Response getDocumentCountWithResponse(Context context) { - return Utility.executeRestCallWithExceptionHandling( - () -> restClient.getDocuments().countWithResponse(null, context), LOGGER); - } - - /** - * Searches for documents in the Azure AI Search index. - *

- * If {@code searchText} is set to null or {@code "*"} all documents will be matched, see - * simple query - * syntax in Azure AI Search for more information about search query syntax. - *

- * The {@link SearchPagedIterable} will iterate through search result pages until all search results are returned. - * Each page is determined by the {@code $skip} and {@code $top} values and the Search service has a limit on the - * number of documents that can be skipped, more information about the {@code $skip} limit can be found at - * Search Documents REST API and - * reading the {@code $skip} description. If the total number of results exceeds the {@code $skip} limit the - * {@link SearchPagedIterable} won't prevent you from exceeding the {@code $skip} limit. To prevent exceeding the - * limit you can track the number of documents returned and stop requesting new pages when the limit is reached. - * - *

Code Sample

- * - *

Search text from documents in service.

- * - * - *
-     * SearchPagedIterable searchPagedIterable = SEARCH_CLIENT.search("searchText");
-     * System.out.printf("There are around %d results.", searchPagedIterable.getTotalCount());
-     *
-     * long numberOfDocumentsReturned = 0;
-     * for (SearchPagedResponse resultResponse: searchPagedIterable.iterableByPage()) {
-     *     System.out.println("The status code of the response is " + resultResponse.getStatusCode());
-     *     numberOfDocumentsReturned += resultResponse.getValue().size();
-     *     resultResponse.getValue().forEach(searchResult -> {
-     *         for (Map.Entry<String, Object> keyValuePair: searchResult
-     *             .getDocument(SearchDocument.class).entrySet()) {
-     *             System.out.printf("Document key %s, document value %s", keyValuePair.getKey(),
-     *                 keyValuePair.getValue());
-     *         }
-     *     });
-     *
-     *     if (numberOfDocumentsReturned >= SEARCH_SKIP_LIMIT) {
-     *         // Reached the $skip limit, stop requesting more documents.
-     *         break;
-     *     }
-     * }
-     * 
- * - * - * @param searchText A full-text search query expression. - * @return A {@link SearchPagedIterable} that iterates over {@link SearchResult} objects and provides access to the - * {@link SearchPagedResponse} object for each page containing HTTP response and count, facet, and coverage - * information. - * @see Search documents - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - public SearchPagedIterable search(String searchText) { - return search(searchText, null, Context.NONE); - } - - /** - * Searches for documents in the Azure AI Search index. - *

- * If {@code searchText} is set to null or {@code "*"} all documents will be matched, see - * simple query - * syntax in Azure AI Search for more information about search query syntax. - *

- * The {@link SearchPagedIterable} will iterate through search result pages until all search results are returned. - * Each page is determined by the {@code $skip} and {@code $top} values and the Search service has a limit on the - * number of documents that can be skipped, more information about the {@code $skip} limit can be found at - * Search Documents REST API and - * reading the {@code $skip} description. If the total number of results exceeds the {@code $skip} limit the - * {@link SearchPagedIterable} won't prevent you from exceeding the {@code $skip} limit. To prevent exceeding the - * limit you can track the number of documents returned and stop requesting new pages when the limit is reached. - * - *

Code Sample

- * - *

Search text from documents in service with option.

- * - * - *
-     * SearchPagedIterable searchPagedIterable = SEARCH_CLIENT.search("searchText",
-     *     new SearchOptions().setOrderBy("hotelId desc"), new Context(KEY_1, VALUE_1));
-     * System.out.printf("There are around %d results.", searchPagedIterable.getTotalCount());
-     *
-     * long numberOfDocumentsReturned = 0;
-     * for (SearchPagedResponse resultResponse: searchPagedIterable.iterableByPage()) {
-     *     System.out.println("The status code of the response is " + resultResponse.getStatusCode());
-     *     numberOfDocumentsReturned += resultResponse.getValue().size();
-     *     resultResponse.getValue().forEach(searchResult -> {
-     *         for (Map.Entry<String, Object> keyValuePair: searchResult
-     *             .getDocument(SearchDocument.class).entrySet()) {
-     *             System.out.printf("Document key %s, document value %s", keyValuePair.getKey(),
-     *                 keyValuePair.getValue());
-     *         }
-     *     });
-     *
-     *     if (numberOfDocumentsReturned >= SEARCH_SKIP_LIMIT) {
-     *         // Reached the $skip limit, stop requesting more documents.
-     *         break;
-     *     }
-     * }
-     * 
- * - * - * @param searchText A full-text search query expression. - * @param searchOptions Parameters to further refine the search query - * @param context additional context that is passed through the Http pipeline during the service call - * @return A {@link SearchPagedIterable} that iterates over {@link SearchResult} objects and provides access to the - * {@link SearchPagedResponse} object for each page containing HTTP response and count, facet, and coverage - * information. - * @see Search documents - */ + public Response getServiceStatisticsWithResponse(RequestOptions requestOptions) { + return this.serviceClient.getServiceStatisticsWithResponse(requestOptions); + } + + /** + * Retrieves a summary of statistics for all indexes in the search service. + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     name: String (Required)
+     *     documentCount: long (Required)
+     *     storageSize: long (Required)
+     *     vectorIndexSize: Long (Optional)
+     * }
+     * }
+     * 
+ * + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return response from a request to retrieve stats summary of all indexes as paginated response with + * {@link PagedIterable}. + */ + @Generated @ServiceMethod(returns = ReturnType.COLLECTION) - public SearchPagedIterable search(String searchText, SearchOptions searchOptions, Context context) { - SearchRequest request = createSearchRequest(searchText, searchOptions); - // The firstPageResponse shared among all functional calls below. - // Do not initial new instance directly in func call. - final SearchFirstPageResponseWrapper firstPageResponseWrapper = new SearchFirstPageResponseWrapper(); - Function func - = continuationToken -> search(request, continuationToken, firstPageResponseWrapper, context); - return new SearchPagedIterable(() -> func.apply(null), func); - } - - private SearchPagedResponse search(SearchRequest request, String continuationToken, - SearchFirstPageResponseWrapper firstPageResponseWrapper, Context context) { - if (continuationToken == null && firstPageResponseWrapper.getFirstPageResponse() != null) { - return firstPageResponseWrapper.getFirstPageResponse(); - } - SearchRequest requestToUse = (continuationToken == null) - ? request - : SearchContinuationToken.deserializeToken(serviceVersion.getVersion(), continuationToken); - - return Utility.executeRestCallWithExceptionHandling(() -> { - Response response - = restClient.getDocuments().searchPostWithResponse(requestToUse, null, context); - SearchDocumentsResult result = response.getValue(); - SearchPagedResponse page - = new SearchPagedResponse(new SimpleResponse<>(response, getSearchResults(result, serializer)), - createContinuationToken(result, serviceVersion), result.getFacets(), result.getCount(), - result.getCoverage(), result.getAnswers(), result.getSemanticPartialResponseReason(), - result.getSemanticPartialResponseType(), result.getDebugInfo(), - result.getSemanticQueryRewritesResultType()); - if (continuationToken == null) { - firstPageResponseWrapper.setFirstPageResponse(page); - } - return page; - }, LOGGER); + public PagedIterable getIndexStatsSummary(RequestOptions requestOptions) { + return this.serviceClient.getIndexStatsSummary(requestOptions); } /** - * Suggests documents in the index that match the given partial query. - * - *

Code Sample

- * - *

Suggest text from documents in service.

- * - * - *
-     * SuggestPagedIterable suggestPagedIterable = SEARCH_CLIENT.suggest("searchText", "sg");
-     * for (SuggestResult result: suggestPagedIterable) {
-     *     SearchDocument searchDocument = result.getDocument(SearchDocument.class);
-     *     for (Map.Entry<String, Object> keyValuePair: searchDocument.entrySet()) {
-     *         System.out.printf("Document key %s, document value %s", keyValuePair.getKey(), keyValuePair.getValue());
-     *     }
-     * }
-     * 
- * - * - * @param searchText The search text on which to base suggestions - * @param suggesterName The name of the suggester as specified in the suggesters collection that's part of the index - * definition - * @return A {@link SuggestPagedIterable} that iterates over {@link SuggestResult} objects and provides access to - * the {@link SuggestPagedResponse} object for each page containing HTTP response and coverage information. - * @see Suggestions + * Gets service level statistics for a search service. + * + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return service level statistics for a search service. */ - @ServiceMethod(returns = ReturnType.COLLECTION) - public SuggestPagedIterable suggest(String searchText, String suggesterName) { - return suggest(searchText, suggesterName, null, Context.NONE); - } - - /** - * Suggests documents in the index that match the given partial query. - * - *

Code Sample

- * - *

Suggest text from documents in service with option.

- * - * - *
-     * SuggestPagedIterable suggestPagedIterable = SEARCH_CLIENT.suggest("searchText", "sg",
-     *     new SuggestOptions().setOrderBy("hotelId desc"), new Context(KEY_1, VALUE_1));
-     * for (SuggestResult result: suggestPagedIterable) {
-     *     SearchDocument searchDocument = result.getDocument(SearchDocument.class);
-     *     for (Map.Entry<String, Object> keyValuePair: searchDocument.entrySet()) {
-     *         System.out.printf("Document key %s, document value %s", keyValuePair.getKey(), keyValuePair.getValue());
-     *     }
-     * }
-     * 
- * - * - * @param searchText The search text on which to base suggestions - * @param suggesterName The name of the suggester as specified in the suggesters collection that's part of the index - * definition - * @param suggestOptions Parameters to further refine the suggestion query. - * @param context additional context that is passed through the Http pipeline during the service call - * @return A {@link SuggestPagedIterable} that iterates over {@link SuggestResult} objects and provides access to - * the {@link SuggestPagedResponse} object for each page containing HTTP response and coverage information. - * @see Suggestions - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - public SuggestPagedIterable suggest(String searchText, String suggesterName, SuggestOptions suggestOptions, - Context context) { - SuggestRequest suggestRequest - = createSuggestRequest(searchText, suggesterName, Utility.ensureSuggestOptions(suggestOptions)); - return new SuggestPagedIterable(() -> suggest(suggestRequest, context)); - } - - private SuggestPagedResponse suggest(SuggestRequest suggestRequest, Context context) { - return Utility.executeRestCallWithExceptionHandling(() -> { - Response response - = restClient.getDocuments().suggestPostWithResponse(suggestRequest, null, context); - SuggestDocumentsResult result = response.getValue(); - return new SuggestPagedResponse(new SimpleResponse<>(response, getSuggestResults(result, serializer)), - result.getCoverage()); - }, LOGGER); - } - - /** - * Autocompletes incomplete query terms based on input text and matching terms in the index. - * - *

Code Sample

- * - *

Autocomplete text from documents in service.

- * - * - *
-     * AutocompletePagedIterable autocompletePagedIterable = SEARCH_CLIENT.autocomplete("searchText", "sg");
-     * for (AutocompleteItem result: autocompletePagedIterable) {
-     *     System.out.printf("The complete term is %s", result.getText());
-     * }
-     * 
- * - * - * @param searchText search text - * @param suggesterName suggester name - * @return auto complete result. - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - public AutocompletePagedIterable autocomplete(String searchText, String suggesterName) { - return autocomplete(searchText, suggesterName, null, Context.NONE); + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public SearchServiceStatistics getServiceStatistics() { + // Generated convenience method for getServiceStatisticsWithResponse + RequestOptions requestOptions = new RequestOptions(); + return getServiceStatisticsWithResponse(requestOptions).getValue().toObject(SearchServiceStatistics.class); } /** - * Autocompletes incomplete query terms based on input text and matching terms in the index. - * - *

Code Sample

- * - *

Autocomplete text from documents in service with option.

- * - * - *
-     * AutocompletePagedIterable autocompletePagedIterable = SEARCH_CLIENT.autocomplete("searchText", "sg",
-     *     new AutocompleteOptions().setAutocompleteMode(AutocompleteMode.ONE_TERM_WITH_CONTEXT),
-     *     new Context(KEY_1, VALUE_1));
-     * for (AutocompleteItem result: autocompletePagedIterable) {
-     *     System.out.printf("The complete term is %s", result.getText());
-     * }
-     * 
- * - * - * @param searchText search text - * @param suggesterName suggester name - * @param autocompleteOptions autocomplete options - * @param context additional context that is passed through the HTTP pipeline during the service call - * @return auto complete result. + * Retrieves a summary of statistics for all indexes in the search service. + * + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return response from a request to retrieve stats summary of all indexes as paginated response with + * {@link PagedIterable}. */ + @Generated @ServiceMethod(returns = ReturnType.COLLECTION) - public AutocompletePagedIterable autocomplete(String searchText, String suggesterName, - AutocompleteOptions autocompleteOptions, Context context) { - AutocompleteRequest request = createAutoCompleteRequest(searchText, suggesterName, autocompleteOptions); - - return new AutocompletePagedIterable(() -> autocomplete(request, context)); - } - - private AutocompletePagedResponse autocomplete(AutocompleteRequest request, Context context) { - return Utility.executeRestCallWithExceptionHandling(() -> { - Response response - = restClient.getDocuments().autocompletePostWithResponse(request, null, context); - return new AutocompletePagedResponse(new SimpleResponse<>(response, response.getValue())); - }, LOGGER); + public PagedIterable getIndexStatsSummary() { + // Generated convenience method for getIndexStatsSummary + RequestOptions requestOptions = new RequestOptions(); + return serviceClient.getIndexStatsSummary(requestOptions) + .mapPage(bodyItemValue -> bodyItemValue.toObject(IndexStatisticsSummary.class)); } } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/SearchClientBuilder.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/SearchClientBuilder.java index e9c7192ddfbd..e904c22e5ec6 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/SearchClientBuilder.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/SearchClientBuilder.java @@ -1,903 +1,512 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.search.documents; +import com.azure.core.annotation.Generated; import com.azure.core.annotation.ServiceClientBuilder; -import com.azure.core.client.traits.AzureKeyCredentialTrait; import com.azure.core.client.traits.ConfigurationTrait; import com.azure.core.client.traits.EndpointTrait; import com.azure.core.client.traits.HttpTrait; +import com.azure.core.client.traits.KeyCredentialTrait; import com.azure.core.client.traits.TokenCredentialTrait; -import com.azure.core.credential.AzureKeyCredential; +import com.azure.core.credential.KeyCredential; import com.azure.core.credential.TokenCredential; import com.azure.core.http.HttpClient; +import com.azure.core.http.HttpHeaders; import com.azure.core.http.HttpPipeline; +import com.azure.core.http.HttpPipelineBuilder; import com.azure.core.http.HttpPipelinePosition; -import com.azure.core.http.policy.HttpLogDetailLevel; +import com.azure.core.http.policy.AddDatePolicy; +import com.azure.core.http.policy.AddHeadersFromContextPolicy; +import com.azure.core.http.policy.AddHeadersPolicy; +import com.azure.core.http.policy.BearerTokenAuthenticationPolicy; import com.azure.core.http.policy.HttpLogOptions; +import com.azure.core.http.policy.HttpLoggingPolicy; import com.azure.core.http.policy.HttpPipelinePolicy; +import com.azure.core.http.policy.HttpPolicyProviders; +import com.azure.core.http.policy.KeyCredentialPolicy; +import com.azure.core.http.policy.RequestIdPolicy; import com.azure.core.http.policy.RetryOptions; import com.azure.core.http.policy.RetryPolicy; +import com.azure.core.http.policy.UserAgentPolicy; import com.azure.core.util.ClientOptions; import com.azure.core.util.Configuration; import com.azure.core.util.CoreUtils; -import com.azure.core.util.HttpClientOptions; +import com.azure.core.util.builder.ClientBuilderUtil; import com.azure.core.util.logging.ClientLogger; -import com.azure.core.util.serializer.JsonSerializer; -import com.azure.core.util.serializer.JsonSerializerProviders; -import com.azure.core.util.serializer.TypeReference; -import com.azure.search.documents.implementation.util.Constants; -import com.azure.search.documents.implementation.util.Utility; -import com.azure.search.documents.models.IndexAction; -import com.azure.search.documents.models.SearchAudience; -import com.azure.search.documents.options.OnActionAddedOptions; -import com.azure.search.documents.options.OnActionErrorOptions; -import com.azure.search.documents.options.OnActionSentOptions; -import com.azure.search.documents.options.OnActionSucceededOptions; - -import java.net.MalformedURLException; -import java.net.URL; -import java.time.Duration; +import com.azure.core.util.serializer.JacksonAdapter; +import com.azure.search.documents.implementation.SearchClientImpl; import java.util.ArrayList; import java.util.List; +import java.util.Map; import java.util.Objects; -import java.util.function.Consumer; -import java.util.function.Function; - -import static com.azure.search.documents.implementation.util.Utility.buildRestClient; /** - * This class provides a fluent builder API to help aid the configuration and instantiation of {@link SearchClient - * SearchClients} and {@link SearchAsyncClient SearchAsyncClients}. - * - *

- * Overview - *

- * - *

- * This client allows you to create instances of {@link SearchClient} and {@link SearchAsyncClient} to - * utilize synchronous and asynchronous APIs respectively to interact with Azure AI Search. - *

- * - *

- * Getting Started - *

- * - *

- * Authentication - *

- * - *

- * Azure AI Search supports - * Microsoft Entra ID (role-based) authentication and API keys for authentication. - *

- * - *

- * For more information about the scopes of authorization, see the Azure AI Search Security Overview documentation. - *

- * - *

- * Building and Authenticating a {@link SearchClient} or {@link SearchAsyncClient} using API keys - *

- * - *

- * To build an instance of {@link SearchClient} or {@link SearchAsyncClient} using API keys, call - * {@link #buildClient() buildClient} and {@link #buildAsyncClient() buildAsyncClient} respectively from the - * {@link SearchClientBuilder}. - *

- * - *

- * The following must be provided to construct a client instance. - *

- * - *
    - *
  • - * The Azure AI Search service URL. - *
  • - *
  • - * An {@link AzureKeyCredential API Key} that grants access to the Azure AI Search service. - *
  • - *
- * - *

Instantiating a synchronous Search Client

- * - * - *
- * SearchClient searchClient = new SearchClientBuilder()
- *     .credential(new AzureKeyCredential("{key}"))
- *     .endpoint("{endpoint}")
- *     .indexName("{indexName}")
- *     .buildClient();
- * 
- * - * - *

Instantiating an asynchronous Search Client

- * - * - *
- * SearchAsyncClient searchAsyncClient = new SearchClientBuilder()
- *     .credential(new AzureKeyCredential("{key}"))
- *     .endpoint("{endpoint}")
- *     .indexName("{indexName}")
- *     .buildAsyncClient();
- * 
- * - * - *

- * Building and Authenticating a {@link SearchClient} or {@link SearchAsyncClient} using Microsoft Entra ID - *

- * - *

- * You can also create a {@link SearchClient} or {@link SearchAsyncClient} using Microsoft Entra ID - * authentication. Your user or service principal must be assigned the "Search Index Data Reader" role. Using the - * DefaultAzureCredential you can authenticate a service using Managed Identity or a service principal, authenticate - * as a developer working on an application, and more all without changing code. Please refer the documentation for - * instructions on how to connect to Azure AI Search using Azure role-based access control (Azure RBAC). - *

- * - *

- * Before you can use the `DefaultAzureCredential`, or any credential type from Azure.Identity, you'll first need to install the Azure.Identity package. - *

- * - *

- * To use DefaultAzureCredential with a client ID and secret, you'll need to set the `AZURE_TENANT_ID`, `AZURE_CLIENT_ID`, - * and `AZURE_CLIENT_SECRET` environment variables; alternatively, you can pass those values to the - * `ClientSecretCredential` also in azure-identity. - *

- * - *

- * Make sure you use the right namespace for DefaultAzureCredential at the top of your source file: - *

- * - * - *
- * import com.azure.identity.DefaultAzureCredential;
- * import com.azure.identity.DefaultAzureCredentialBuilder;
- * 
- * - * - *

- * Then you can create an instance of DefaultAzureCredential and pass it to a new instance of your client: - *

- * - *

The following sample builds a SearchClient using DefaultAzureCredential.

- * - *

Instantiating a synchronous Search Client

- * - * - *
- * DefaultAzureCredential credential = new DefaultAzureCredentialBuilder().build();
- *
- * SearchClient searchClient = new SearchClientBuilder()
- *     .credential(credential)
- *     .endpoint("{endpoint}")
- *     .indexName("{indexName}")
- *     .buildClient();
- * 
- * - * - *

Instantiating an asynchronous Search Client

- * - * - *
- * DefaultAzureCredential credential = new DefaultAzureCredentialBuilder().build();
- *
- * SearchAsyncClient searchAsyncClient = new SearchClientBuilder()
- *     .credential(credential)
- *     .endpoint("{endpoint}")
- *     .indexName("{indexName}")
- *     .buildAsyncClient();
- * 
- * - * - * @see SearchClient - * @see SearchAsyncClient - * @see com.azure.search.documents + * A builder for creating a new instance of the SearchClient type. */ -@ServiceClientBuilder(serviceClients = { SearchClient.class, SearchAsyncClient.class }) -public final class SearchClientBuilder - implements AzureKeyCredentialTrait, ConfigurationTrait, - EndpointTrait, HttpTrait, TokenCredentialTrait { - private static final boolean DEFAULT_AUTO_FLUSH = true; - private static final int DEFAULT_INITIAL_BATCH_ACTION_COUNT = 512; - private static final Duration DEFAULT_FLUSH_INTERVAL = Duration.ofSeconds(60); - private static final int DEFAULT_MAX_RETRIES_PER_ACTION = 3; - private static final Duration DEFAULT_THROTTLING_DELAY = Duration.ofMillis(800); - private static final Duration DEFAULT_MAX_THROTTLING_DELAY = Duration.ofMinutes(1); - // Retaining this commented out code as it may be added back in a future release. - // private static final Function DEFAULT_SCALE_DOWN_FUNCTION = oldBatchCount -> { - // if (oldBatchCount == 1) { - // return 1; - // } else { - // return Math.max(1, oldBatchCount / 2); - // } - // }; - - private static final ClientLogger LOGGER = new ClientLogger(SearchClientBuilder.class); - - private final List perCallPolicies = new ArrayList<>(); - private final List perRetryPolicies = new ArrayList<>(); - - private AzureKeyCredential azureKeyCredential; - private TokenCredential tokenCredential; - private SearchAudience audience; - - private SearchServiceVersion serviceVersion; - private String endpoint; - private HttpClient httpClient; - private HttpPipeline httpPipeline; - private ClientOptions clientOptions; - private HttpLogOptions httpLogOptions; - private Configuration configuration; - private String indexName; - private RetryPolicy retryPolicy; - private RetryOptions retryOptions; - private JsonSerializer jsonSerializer; +@ServiceClientBuilder( + serviceClients = { + SearchClient.class, + DataSourcesClient.class, + IndexersClient.class, + SkillsetsClient.class, + SynonymMapsClient.class, + IndexesClient.class, + AliasesClient.class, + DocumentsClient.class, + SearchAsyncClient.class, + DataSourcesAsyncClient.class, + IndexersAsyncClient.class, + SkillsetsAsyncClient.class, + SynonymMapsAsyncClient.class, + IndexesAsyncClient.class, + AliasesAsyncClient.class, + DocumentsAsyncClient.class }) +public final class SearchClientBuilder implements HttpTrait, + ConfigurationTrait, TokenCredentialTrait, + KeyCredentialTrait, EndpointTrait { + @Generated + private static final String SDK_NAME = "name"; + + @Generated + private static final String SDK_VERSION = "version"; + + @Generated + private static final String[] DEFAULT_SCOPES = new String[] { "https://search.azure.com/.default" }; + + @Generated + private static final Map PROPERTIES = CoreUtils.getProperties("azure-search-documents.properties"); + + @Generated + private final List pipelinePolicies; /** - * Creates a builder instance that is able to configure and construct {@link SearchClient SearchClients} and {@link - * SearchAsyncClient SearchAsyncClients}. + * Create an instance of the SearchClientBuilder. */ + @Generated public SearchClientBuilder() { + this.pipelinePolicies = new ArrayList<>(); } - /** - * Creates a {@link SearchClient} based on options set in the builder. Every time {@code buildClient()} is called a - * new instance of {@link SearchClient} is created. - *

- * If {@link #pipeline(HttpPipeline) pipeline} is set, then only the {@code pipeline}, {@link #endpoint(String) - * endpoint}, and {@link #indexName(String) indexName} are used to create the {@link SearchClient client}. All other - * builder settings are ignored. - * - * @return A SearchClient with the options set from the builder. - * @throws NullPointerException If {@code indexName} or {@code endpoint} are null. - * @throws IllegalStateException If both {@link #retryOptions(RetryOptions)} - * and {@link #retryPolicy(RetryPolicy)} have been set. + /* + * The HTTP pipeline to send requests through. */ - public SearchClient buildClient() { - validateIndexNameAndEndpoint(); - SearchServiceVersion buildVersion - = (serviceVersion == null) ? SearchServiceVersion.getLatest() : serviceVersion; - - HttpPipeline pipeline = getHttpPipeline(); - JsonSerializer serializer - = (jsonSerializer == null) ? JsonSerializerProviders.createInstance(true) : jsonSerializer; - return new SearchClient(endpoint, indexName, buildVersion, pipeline, serializer, - Utility.buildRestClient(buildVersion, endpoint, indexName, pipeline)); - } + @Generated + private HttpPipeline pipeline; /** - * Creates a {@link SearchAsyncClient} based on options set in the builder. Every time {@code buildAsyncClient()} is - * called a new instance of {@link SearchAsyncClient} is created. - *

- * If {@link #pipeline(HttpPipeline) pipeline} is set, then only the {@code pipeline}, {@link #endpoint(String) - * endpoint}, and {@link #indexName(String) indexName} are used to create the {@link SearchAsyncClient client}. All - * other builder settings are ignored. - * - * @return A SearchClient with the options set from the builder. - * @throws NullPointerException If {@code indexName} or {@code endpoint} are null. - * @throws IllegalStateException If both {@link #retryOptions(RetryOptions)} - * and {@link #retryPolicy(RetryPolicy)} have been set. + * {@inheritDoc}. */ - public SearchAsyncClient buildAsyncClient() { - validateIndexNameAndEndpoint(); - SearchServiceVersion buildVersion - = (serviceVersion == null) ? SearchServiceVersion.getLatest() : serviceVersion; - - HttpPipeline pipeline = getHttpPipeline(); - JsonSerializer serializer - = (jsonSerializer == null) ? JsonSerializerProviders.createInstance(true) : jsonSerializer; - return new SearchAsyncClient(endpoint, indexName, buildVersion, pipeline, serializer, - Utility.buildRestClient(buildVersion, endpoint, indexName, pipeline)); + @Generated + @Override + public SearchClientBuilder pipeline(HttpPipeline pipeline) { + if (this.pipeline != null && pipeline == null) { + LOGGER.atInfo().log("HttpPipeline is being set to 'null' when it was previously configured."); + } + this.pipeline = pipeline; + return this; } - /** - * Create a new instance of {@link SearchIndexingBufferedSenderBuilder} used to configure {@link - * SearchIndexingBufferedSender SearchIndexingBufferedSenders} and {@link SearchIndexingBufferedAsyncSender - * SearchIndexingBufferedAsyncSenders}. - * - * @param documentType The {@link TypeReference} representing the document type associated with the sender. - * @param The type of the document that the buffered sender will use. - * @return A new instance of {@link SearchIndexingBufferedSenderBuilder}. + /* + * The HTTP client used to send the request. */ - public SearchIndexingBufferedSenderBuilder bufferedSender(TypeReference documentType) { - return new SearchIndexingBufferedSenderBuilder<>(); - } + @Generated + private HttpClient httpClient; - private void validateIndexNameAndEndpoint() { - Objects.requireNonNull(indexName, "'indexName' cannot be null."); - Objects.requireNonNull(endpoint, "'endpoint' cannot be null."); + /** + * {@inheritDoc}. + */ + @Generated + @Override + public SearchClientBuilder httpClient(HttpClient httpClient) { + this.httpClient = httpClient; + return this; } - private HttpPipeline getHttpPipeline() { - if (httpPipeline != null) { - return httpPipeline; - } - - return Utility.buildHttpPipeline(clientOptions, httpLogOptions, configuration, retryPolicy, retryOptions, - azureKeyCredential, tokenCredential, audience, perCallPolicies, perRetryPolicies, httpClient, LOGGER); - } + /* + * The logging configuration for HTTP requests and responses. + */ + @Generated + private HttpLogOptions httpLogOptions; /** - * Sets the service endpoint for the Azure AI Search instance. - * - * @param endpoint The URL of the Azure AI Search instance. - * @return The updated SearchClientBuilder object.0ed into a valid URL. + * {@inheritDoc}. */ + @Generated @Override - public SearchClientBuilder endpoint(String endpoint) { - try { - new URL(endpoint); - } catch (MalformedURLException ex) { - throw LOGGER.logExceptionAsWarning(new IllegalArgumentException("'endpoint' must be a valid URL", ex)); - } - this.endpoint = endpoint; + public SearchClientBuilder httpLogOptions(HttpLogOptions httpLogOptions) { + this.httpLogOptions = httpLogOptions; return this; } + /* + * The client options such as application ID and custom headers to set on a request. + */ + @Generated + private ClientOptions clientOptions; + /** - * Sets the {@link AzureKeyCredential} used to authenticate HTTP requests. - * - * @param credential The {@link AzureKeyCredential} used to authenticate HTTP requests. - * @return The updated SearchClientBuilder object. + * {@inheritDoc}. */ + @Generated @Override - public SearchClientBuilder credential(AzureKeyCredential credential) { - this.azureKeyCredential = credential; + public SearchClientBuilder clientOptions(ClientOptions clientOptions) { + this.clientOptions = clientOptions; return this; } + /* + * The retry options to configure retry policy for failed requests. + */ + @Generated + private RetryOptions retryOptions; + /** - * Sets the {@link TokenCredential} used to authorize requests sent to the service. Refer to the Azure SDK for Java - * identity and authentication - * documentation for more details on proper usage of the {@link TokenCredential} type. - * - * @param credential {@link TokenCredential} used to authorize requests sent to the service. - * @return The updated SearchClientBuilder object. + * {@inheritDoc}. */ + @Generated @Override - public SearchClientBuilder credential(TokenCredential credential) { - this.tokenCredential = credential; + public SearchClientBuilder retryOptions(RetryOptions retryOptions) { + this.retryOptions = retryOptions; return this; } /** - * Sets the Audience to use for authentication with Microsoft Entra ID. - *

- * The audience is not considered when using a {@link #credential(AzureKeyCredential) shared key}. - *

- * If {@code audience} is null the public cloud audience will be assumed. - * - * @param audience The Audience to use for authentication with Microsoft Entra ID. - * @return The updated SearchClientBuilder object. - */ - public SearchClientBuilder audience(SearchAudience audience) { - this.audience = audience; + * {@inheritDoc}. + */ + @Generated + @Override + public SearchClientBuilder addPolicy(HttpPipelinePolicy customPolicy) { + Objects.requireNonNull(customPolicy, "'customPolicy' cannot be null."); + pipelinePolicies.add(customPolicy); return this; } + /* + * The configuration store that is used during construction of the service client. + */ + @Generated + private Configuration configuration; + /** - * Sets the name of the index. - * - * @param indexName Name of the index. - * @return The updated SearchClientBuilder object. - * @throws IllegalArgumentException If {@code indexName} is null or empty. - */ - public SearchClientBuilder indexName(String indexName) { - if (CoreUtils.isNullOrEmpty(indexName)) { - throw LOGGER.logExceptionAsError(new IllegalArgumentException("'indexName' cannot be null or empty.")); - } - this.indexName = indexName; + * {@inheritDoc}. + */ + @Generated + @Override + public SearchClientBuilder configuration(Configuration configuration) { + this.configuration = configuration; return this; } + /* + * The TokenCredential used for authentication. + */ + @Generated + private TokenCredential tokenCredential; + /** - * Sets the {@link HttpLogOptions logging configuration} to use when sending and receiving requests to and from - * the service. If a {@code logLevel} is not provided, default value of {@link HttpLogDetailLevel#NONE} is set. - * - *

Note: It is important to understand the precedence order of the HttpTrait APIs. In - * particular, if a {@link HttpPipeline} is specified, this takes precedence over all other APIs in the trait, and - * they will be ignored. If no {@link HttpPipeline} is specified, a HTTP pipeline will be constructed internally - * based on the settings provided to this trait. Additionally, there may be other APIs in types that implement this - * trait that are also ignored if an {@link HttpPipeline} is specified, so please be sure to refer to the - * documentation of types that implement this trait to understand the full set of implications.

- * - * @param logOptions The {@link HttpLogOptions logging configuration} to use when sending and receiving requests to - * and from the service. - * @return The updated SearchClientBuilder object. + * {@inheritDoc}. */ + @Generated @Override - public SearchClientBuilder httpLogOptions(HttpLogOptions logOptions) { - httpLogOptions = logOptions; + public SearchClientBuilder credential(TokenCredential tokenCredential) { + this.tokenCredential = tokenCredential; return this; } - /** - * Gets the default Azure Search headers and query parameters allow list. - * - * @return The default {@link HttpLogOptions} allow list. + /* + * The KeyCredential used for authentication. */ - public static HttpLogOptions getDefaultLogOptions() { - return Constants.DEFAULT_LOG_OPTIONS_SUPPLIER.get(); - } + @Generated + private KeyCredential keyCredential; /** - * Allows for setting common properties such as application ID, headers, proxy configuration, etc. Note that it is - * recommended that this method be called with an instance of the {@link HttpClientOptions} - * class (a subclass of the {@link ClientOptions} base class). The HttpClientOptions subclass provides more - * configuration options suitable for HTTP clients, which is applicable for any class that implements this HttpTrait - * interface. - * - *

Note: It is important to understand the precedence order of the HttpTrait APIs. In - * particular, if a {@link HttpPipeline} is specified, this takes precedence over all other APIs in the trait, and - * they will be ignored. If no {@link HttpPipeline} is specified, a HTTP pipeline will be constructed internally - * based on the settings provided to this trait. Additionally, there may be other APIs in types that implement this - * trait that are also ignored if an {@link HttpPipeline} is specified, so please be sure to refer to the - * documentation of types that implement this trait to understand the full set of implications.

- * - * @param clientOptions A configured instance of {@link HttpClientOptions}. - * @return The updated SearchClientBuilder object. - * @see HttpClientOptions + * {@inheritDoc}. */ + @Generated @Override - public SearchClientBuilder clientOptions(ClientOptions clientOptions) { - this.clientOptions = clientOptions; + public SearchClientBuilder credential(KeyCredential keyCredential) { + this.keyCredential = keyCredential; return this; } + /* + * The service endpoint + */ + @Generated + private String endpoint; + /** - * Adds a {@link HttpPipelinePolicy pipeline policy} to apply on each request sent. - * - *

Note: It is important to understand the precedence order of the HttpTrait APIs. In - * particular, if a {@link HttpPipeline} is specified, this takes precedence over all other APIs in the trait, and - * they will be ignored. If no {@link HttpPipeline} is specified, a HTTP pipeline will be constructed internally - * based on the settings provided to this trait. Additionally, there may be other APIs in types that implement this - * trait that are also ignored if an {@link HttpPipeline} is specified, so please be sure to refer to the - * documentation of types that implement this trait to understand the full set of implications.

- * - * @param policy A {@link HttpPipelinePolicy pipeline policy}. - * @return The updated SearchClientBuilder object. - * @throws NullPointerException If {@code policy} is null. + * {@inheritDoc}. */ + @Generated @Override - public SearchClientBuilder addPolicy(HttpPipelinePolicy policy) { - Objects.requireNonNull(policy, "'policy' cannot be null."); - - if (policy.getPipelinePosition() == HttpPipelinePosition.PER_CALL) { - perCallPolicies.add(policy); - } else { - perRetryPolicies.add(policy); - } - + public SearchClientBuilder endpoint(String endpoint) { + this.endpoint = endpoint; return this; } + /* + * Service version + */ + @Generated + private SearchServiceVersion serviceVersion; + /** - * Custom JSON serializer that is used to handle model types that are not contained in the Azure Search Documents - * library. - * - * @param jsonSerializer The serializer to serialize user defined models. - * @return The updated SearchClientBuilder object. - */ - public SearchClientBuilder serializer(JsonSerializer jsonSerializer) { - this.jsonSerializer = jsonSerializer; + * Sets Service version. + * + * @param serviceVersion the serviceVersion value. + * @return the SearchClientBuilder. + */ + @Generated + public SearchClientBuilder serviceVersion(SearchServiceVersion serviceVersion) { + this.serviceVersion = serviceVersion; return this; } - /** - * Sets the {@link HttpClient} to use for sending and receiving requests to and from the service. - * - *

Note: It is important to understand the precedence order of the HttpTrait APIs. In - * particular, if a {@link HttpPipeline} is specified, this takes precedence over all other APIs in the trait, and - * they will be ignored. If no {@link HttpPipeline} is specified, a HTTP pipeline will be constructed internally - * based on the settings provided to this trait. Additionally, there may be other APIs in types that implement this - * trait that are also ignored if an {@link HttpPipeline} is specified, so please be sure to refer to the - * documentation of types that implement this trait to understand the full set of implications.

- * - * @param client The {@link HttpClient} to use for requests. - * @return The updated SearchClientBuilder object. + /* + * The retry policy that will attempt to retry failed requests, if applicable. */ - @Override - public SearchClientBuilder httpClient(HttpClient client) { - if (this.httpClient != null && client == null) { - LOGGER.info("HttpClient is being set to 'null' when it was previously configured."); - } + @Generated + private RetryPolicy retryPolicy; - this.httpClient = client; + /** + * Sets The retry policy that will attempt to retry failed requests, if applicable. + * + * @param retryPolicy the retryPolicy value. + * @return the SearchClientBuilder. + */ + @Generated + public SearchClientBuilder retryPolicy(RetryPolicy retryPolicy) { + this.retryPolicy = retryPolicy; return this; } /** - * Sets the {@link HttpPipeline} to use for the service client. - * - *

Note: It is important to understand the precedence order of the HttpTrait APIs. In - * particular, if a {@link HttpPipeline} is specified, this takes precedence over all other APIs in the trait, and - * they will be ignored. If no {@link HttpPipeline} is specified, a HTTP pipeline will be constructed internally - * based on the settings provided to this trait. Additionally, there may be other APIs in types that implement this - * trait that are also ignored if an {@link HttpPipeline} is specified, so please be sure to refer to the - * documentation of types that implement this trait to understand the full set of implications.

- *

- * If {@code pipeline} is set, all other settings are ignored, aside from {@link #endpoint(String) endpoint} and - * {@link #indexName(String) index} when building a {@link SearchClient} or {@link SearchAsyncClient}. - * - * @param httpPipeline {@link HttpPipeline} to use for sending service requests and receiving responses. - * @return The updated SearchClientBuilder object. + * Builds an instance of SearchClientImpl with the provided parameters. + * + * @return an instance of SearchClientImpl. */ - @Override - public SearchClientBuilder pipeline(HttpPipeline httpPipeline) { - if (this.httpPipeline != null && httpPipeline == null) { - LOGGER.info("HttpPipeline is being set to 'null' when it was previously configured."); - } + @Generated + private SearchClientImpl buildInnerClient() { + this.validateClient(); + HttpPipeline localPipeline = (pipeline != null) ? pipeline : createHttpPipeline(); + SearchServiceVersion localServiceVersion + = (serviceVersion != null) ? serviceVersion : SearchServiceVersion.getLatest(); + SearchClientImpl client = new SearchClientImpl(localPipeline, JacksonAdapter.createDefaultSerializerAdapter(), + this.endpoint, localServiceVersion); + return client; + } - this.httpPipeline = httpPipeline; - return this; + @Generated + private void validateClient() { + // This method is invoked from 'buildInnerClient'/'buildClient' method. + // Developer can customize this method, to validate that the necessary conditions are met for the new client. + Objects.requireNonNull(endpoint, "'endpoint' cannot be null."); + } + + @Generated + private HttpPipeline createHttpPipeline() { + Configuration buildConfiguration + = (configuration == null) ? Configuration.getGlobalConfiguration() : configuration; + HttpLogOptions localHttpLogOptions = this.httpLogOptions == null ? new HttpLogOptions() : this.httpLogOptions; + ClientOptions localClientOptions = this.clientOptions == null ? new ClientOptions() : this.clientOptions; + List policies = new ArrayList<>(); + String clientName = PROPERTIES.getOrDefault(SDK_NAME, "UnknownName"); + String clientVersion = PROPERTIES.getOrDefault(SDK_VERSION, "UnknownVersion"); + String applicationId = CoreUtils.getApplicationId(localClientOptions, localHttpLogOptions); + policies.add(new UserAgentPolicy(applicationId, clientName, clientVersion, buildConfiguration)); + policies.add(new RequestIdPolicy()); + policies.add(new AddHeadersFromContextPolicy()); + HttpHeaders headers = CoreUtils.createHttpHeadersFromClientOptions(localClientOptions); + if (headers != null) { + policies.add(new AddHeadersPolicy(headers)); + } + this.pipelinePolicies.stream() + .filter(p -> p.getPipelinePosition() == HttpPipelinePosition.PER_CALL) + .forEach(p -> policies.add(p)); + HttpPolicyProviders.addBeforeRetryPolicies(policies); + policies.add(ClientBuilderUtil.validateAndGetRetryPolicy(retryPolicy, retryOptions, new RetryPolicy())); + policies.add(new AddDatePolicy()); + if (keyCredential != null) { + policies.add(new KeyCredentialPolicy("api-key", keyCredential)); + } + if (tokenCredential != null) { + policies.add(new BearerTokenAuthenticationPolicy(tokenCredential, DEFAULT_SCOPES)); + } + this.pipelinePolicies.stream() + .filter(p -> p.getPipelinePosition() == HttpPipelinePosition.PER_RETRY) + .forEach(p -> policies.add(p)); + HttpPolicyProviders.addAfterRetryPolicies(policies); + policies.add(new HttpLoggingPolicy(localHttpLogOptions)); + HttpPipeline httpPipeline = new HttpPipelineBuilder().policies(policies.toArray(new HttpPipelinePolicy[0])) + .httpClient(httpClient) + .clientOptions(localClientOptions) + .build(); + return httpPipeline; } /** - * Sets the configuration store that is used during construction of the service client. - *

- * The default configuration store is a clone of the {@link Configuration#getGlobalConfiguration() global - * configuration store}, use {@link Configuration#NONE} to bypass using configuration settings during construction. - * - * @param configuration The configuration store that will be used. - * @return The updated SearchClientBuilder object. + * Builds an instance of SearchAsyncClient class. + * + * @return an instance of SearchAsyncClient. */ - @Override - public SearchClientBuilder configuration(Configuration configuration) { - this.configuration = configuration; - return this; + @Generated + public SearchAsyncClient buildAsyncClient() { + return new SearchAsyncClient(buildInnerClient()); } /** - * Sets the {@link HttpPipelinePolicy} that will attempt to retry requests when needed. - *

- * A default retry policy will be supplied if one isn't provided. - *

- * Setting this is mutually exclusive with using {@link #retryOptions(RetryOptions)}. - * - * @param retryPolicy The {@link RetryPolicy} that will attempt to retry requests when needed. - * @return The updated SearchClientBuilder object. + * Builds an instance of DataSourcesAsyncClient class. + * + * @return an instance of DataSourcesAsyncClient. */ - public SearchClientBuilder retryPolicy(RetryPolicy retryPolicy) { - this.retryPolicy = retryPolicy; - return this; + @Generated + public DataSourcesAsyncClient buildDataSourcesAsyncClient() { + return new DataSourcesAsyncClient(buildInnerClient().getDataSources()); } /** - * Sets the {@link RetryOptions} for all the requests made through the client. - * - *

Note: It is important to understand the precedence order of the HttpTrait APIs. In - * particular, if a {@link HttpPipeline} is specified, this takes precedence over all other APIs in the trait, and - * they will be ignored. If no {@link HttpPipeline} is specified, a HTTP pipeline will be constructed internally - * based on the settings provided to this trait. Additionally, there may be other APIs in types that implement this - * trait that are also ignored if an {@link HttpPipeline} is specified, so please be sure to refer to the - * documentation of types that implement this trait to understand the full set of implications.

- *

- * Setting this is mutually exclusive with using {@link #retryPolicy(RetryPolicy)}. - * - * @param retryOptions The {@link RetryOptions} to use for all the requests made through the client. - * @return The updated SearchClientBuilder object. + * Builds an instance of IndexersAsyncClient class. + * + * @return an instance of IndexersAsyncClient. */ - @Override - public SearchClientBuilder retryOptions(RetryOptions retryOptions) { - this.retryOptions = retryOptions; - return this; + @Generated + public IndexersAsyncClient buildIndexersAsyncClient() { + return new IndexersAsyncClient(buildInnerClient().getIndexers()); } /** - * Sets the {@link SearchServiceVersion} that is used when making API requests. - *

- * If a service version is not provided, {@link SearchServiceVersion#getLatest()} will be used as a default. When - * the default is used, updating to a newer client library may implicitly use a newer version of the service. - * - * @param serviceVersion The version of the service to be used when making requests. - * @return The updated SearchClientBuilder object. + * Builds an instance of SkillsetsAsyncClient class. + * + * @return an instance of SkillsetsAsyncClient. */ - public SearchClientBuilder serviceVersion(SearchServiceVersion serviceVersion) { - this.serviceVersion = serviceVersion; - return this; + @Generated + public SkillsetsAsyncClient buildSkillsetsAsyncClient() { + return new SkillsetsAsyncClient(buildInnerClient().getSkillsets()); } /** - * This class provides a fluent builder API to help aid the configuration and instantiation of {@link - * SearchIndexingBufferedSender SearchIndexingBufferedSenders} and {@link SearchIndexingBufferedAsyncSender - * SearchIndexingBufferedAsyncSenders}. Call {@link #buildSender()} and {@link #buildAsyncSender()} respectively to - * construct an instance of the desired sender. - * - * @param The type of the document that the buffered sender will use. - * @see SearchIndexingBufferedSender - * @see SearchIndexingBufferedAsyncSender - */ - @ServiceClientBuilder( - serviceClients = { SearchIndexingBufferedSender.class, SearchIndexingBufferedAsyncSender.class }) - public final class SearchIndexingBufferedSenderBuilder { - private final ClientLogger logger = new ClientLogger(SearchIndexingBufferedSenderBuilder.class); - - private Function documentKeyRetriever; - - private boolean autoFlush = DEFAULT_AUTO_FLUSH; - private Duration autoFlushInterval = DEFAULT_FLUSH_INTERVAL; - private int initialBatchActionCount = DEFAULT_INITIAL_BATCH_ACTION_COUNT; - // private Function scaleDownFunction = DEFAULT_SCALE_DOWN_FUNCTION; - private int maxRetriesPerAction = DEFAULT_MAX_RETRIES_PER_ACTION; - private Duration throttlingDelay = DEFAULT_THROTTLING_DELAY; - private Duration maxThrottlingDelay = DEFAULT_MAX_THROTTLING_DELAY; - - private Consumer> onActionAddedConsumer; - private Consumer> onActionSucceededConsumer; - private Consumer> onActionErrorConsumer; - private Consumer> onActionSentConsumer; - - private SearchIndexingBufferedSenderBuilder() { - } - - /** - * Creates a {@link SearchIndexingBufferedSender} based on options set in the builder. Every time this is called - * a new instance of {@link SearchIndexingBufferedSender} is created. - * - * @return A SearchIndexingBufferedSender with the options set from the builder. - * @throws NullPointerException If {@code indexName}, {@code endpoint}, or {@code documentKeyRetriever} are - * null. - * @throws IllegalStateException If both {@link #retryOptions(RetryOptions)} - * and {@link #retryPolicy(RetryPolicy)} have been set. - */ - public SearchIndexingBufferedSender buildSender() { - validateIndexNameAndEndpoint(); - Objects.requireNonNull(documentKeyRetriever, "'documentKeyRetriever' cannot be null"); - - SearchServiceVersion buildVersion - = (serviceVersion == null) ? SearchServiceVersion.getLatest() : serviceVersion; - - JsonSerializer serializer - = (jsonSerializer == null) ? JsonSerializerProviders.createInstance(true) : jsonSerializer; - return new SearchIndexingBufferedSender<>( - buildRestClient(buildVersion, endpoint, indexName, getHttpPipeline()), serializer, documentKeyRetriever, - autoFlush, autoFlushInterval, initialBatchActionCount, maxRetriesPerAction, throttlingDelay, - maxThrottlingDelay, onActionAddedConsumer, onActionSucceededConsumer, onActionErrorConsumer, - onActionSentConsumer); - } - - /** - * Creates a {@link SearchIndexingBufferedAsyncSender} based on options set in the builder. Every time this is - * called a new instance of {@link SearchIndexingBufferedAsyncSender} is created. - * - * @return A SearchIndexingBufferedAsyncSender with the options set from the builder. - * @throws NullPointerException If {@code indexName}, {@code endpoint}, or {@code documentKeyRetriever} are - * null. - * @throws IllegalStateException If both {@link #retryOptions(RetryOptions)} - * and {@link #retryPolicy(RetryPolicy)} have been set. - */ - public SearchIndexingBufferedAsyncSender buildAsyncSender() { - validateIndexNameAndEndpoint(); - Objects.requireNonNull(documentKeyRetriever, "'documentKeyRetriever' cannot be null"); - - SearchServiceVersion buildVersion - = (serviceVersion == null) ? SearchServiceVersion.getLatest() : serviceVersion; - - JsonSerializer serializer - = (jsonSerializer == null) ? JsonSerializerProviders.createInstance(true) : jsonSerializer; - return new SearchIndexingBufferedAsyncSender<>( - buildRestClient(buildVersion, endpoint, indexName, getHttpPipeline()), serializer, documentKeyRetriever, - autoFlush, autoFlushInterval, initialBatchActionCount, maxRetriesPerAction, throttlingDelay, - maxThrottlingDelay, onActionAddedConsumer, onActionSucceededConsumer, onActionErrorConsumer, - onActionSentConsumer); - } + * Builds an instance of SynonymMapsAsyncClient class. + * + * @return an instance of SynonymMapsAsyncClient. + */ + @Generated + public SynonymMapsAsyncClient buildSynonymMapsAsyncClient() { + return new SynonymMapsAsyncClient(buildInnerClient().getSynonymMaps()); + } - /** - * Sets the flag determining whether a buffered sender will automatically flush its document batch based on the - * configurations of {@link #autoFlushInterval(Duration)} and {@link #initialBatchActionCount(int)}. - * - * @param autoFlush Flag determining whether a buffered sender will automatically flush. - * @return The updated SearchIndexingBufferedSenderBuilder object. - */ - public SearchIndexingBufferedSenderBuilder autoFlush(boolean autoFlush) { - this.autoFlush = autoFlush; - return this; - } + /** + * Builds an instance of IndexesAsyncClient class. + * + * @return an instance of IndexesAsyncClient. + */ + @Generated + public IndexesAsyncClient buildIndexesAsyncClient() { + return new IndexesAsyncClient(buildInnerClient().getIndexes()); + } - /** - * Sets the duration between a buffered sender sending documents to be indexed. - *

- * The buffered sender will reset the duration when documents are sent for indexing, either by reaching {@link - * #initialBatchActionCount(int)} or by a manual trigger. - *

- * If {@code autoFlushInterval} is negative or zero and {@link #autoFlush(boolean)} is enabled the buffered - * sender will only flush when {@link #initialBatchActionCount(int)} is met. - * - * @param autoFlushInterval Duration between document batches being sent for indexing. - * @return The updated SearchIndexingBufferedSenderBuilder object. - * @throws NullPointerException If {@code autoFlushInterval} is null. - */ - public SearchIndexingBufferedSenderBuilder autoFlushInterval(Duration autoFlushInterval) { - Objects.requireNonNull(autoFlushInterval, "'autoFlushInterval' cannot be null."); - - this.autoFlushInterval = autoFlushInterval; - return this; - } + /** + * Builds an instance of AliasesAsyncClient class. + * + * @return an instance of AliasesAsyncClient. + */ + @Generated + public AliasesAsyncClient buildAliasesAsyncClient() { + return new AliasesAsyncClient(buildInnerClient().getAliases()); + } - /** - * Sets the number of documents before a buffered sender will send the batch to be indexed. - *

- * This will only trigger a batch to be sent automatically if {@link #autoFlushInterval} is configured. Default - * value is {@code 512}. - * - * @param initialBatchActionCount The number of documents in a batch that will trigger it to be indexed. - * @return The updated SearchIndexingBufferedSenderBuilder object. - * @throws IllegalArgumentException If {@code batchSize} is less than one. - */ - public SearchIndexingBufferedSenderBuilder initialBatchActionCount(int initialBatchActionCount) { - if (initialBatchActionCount < 1) { - throw logger.logExceptionAsError(new IllegalArgumentException("'batchSize' cannot be less than one.")); - } - - this.initialBatchActionCount = initialBatchActionCount; - return this; - } + /** + * Builds an instance of DocumentsAsyncClient class. + * + * @return an instance of DocumentsAsyncClient. + */ + @Generated + public DocumentsAsyncClient buildDocumentsAsyncClient() { + return new DocumentsAsyncClient(buildInnerClient().getDocuments()); + } - // Retaining this commented out code as it may be added back in a future release. - // /** - // * Sets the function that handles scaling down the batch size when a 413 (Payload too large) response is returned - // * by the service. - // *

- // * By default the batch size will halve when a 413 is returned with a minimum allowed value of one. - // * - // * @param scaleDownFunction The batch size scale down function. - // * @return The updated SearchIndexingBufferedSenderOptions object. - // * @throws NullPointerException If {@code scaleDownFunction} is null. - // */ - // public SearchIndexingBufferedSenderOptions setPayloadTooLargeScaleDown( - // Function scaleDownFunction) { - // this.scaleDownFunction = Objects.requireNonNull(scaleDownFunction, "'scaleDownFunction' cannot be null."); - // return this; - // } - - // Retaining this commented out code as it may be added back in a future release. - // /** - // * Gets the function that handles scaling down the batch size when a 413 (Payload too large) response is returned - // * by the service. - // *

- // * By default the batch size will halve when a 413 is returned with a minimum allowed value of one. - // * - // * @return The batch size scale down function. - // */ - // public Function getPayloadTooLargeScaleDown() { - // return scaleDownFunction; - // } - - /** - * Sets the number of times an action will retry indexing before it is considered failed. - *

- * Documents are only retried on retryable status codes. - *

- * Default value is {@code 3}. - * - * @param maxRetriesPerAction The number of times a document will retry indexing before it is considered - * failed. - * @return The updated SearchIndexingBufferedSenderBuilder object. - * @throws IllegalArgumentException If {@code maxRetriesPerAction} is less than one. - */ - public SearchIndexingBufferedSenderBuilder maxRetriesPerAction(int maxRetriesPerAction) { - if (maxRetriesPerAction < 1) { - throw logger.logExceptionAsError(new IllegalArgumentException("'maxRetries' cannot be less than one.")); - } - - this.maxRetriesPerAction = maxRetriesPerAction; - return this; - } + /** + * Builds an instance of SearchClient class. + * + * @return an instance of SearchClient. + */ + @Generated + public SearchClient buildClient() { + return new SearchClient(buildInnerClient()); + } - /** - * Sets the initial duration that requests will be delayed when the service is throttling. - *

- * Default value is {@code Duration.ofMillis(800)}. - * - * @param throttlingDelay The initial duration requests will delay when the service is throttling. - * @return The updated SearchIndexingBufferedSenderBuilder object. - * @throws IllegalArgumentException If {@code throttlingDelay.isNegative()} or {@code throttlingDelay.isZero()} - * is true. - * @throws NullPointerException If {@code throttlingDelay} is null. - */ - public SearchIndexingBufferedSenderBuilder throttlingDelay(Duration throttlingDelay) { - Objects.requireNonNull(throttlingDelay, "'throttlingDelay' cannot be null."); - - if (throttlingDelay.isNegative() || throttlingDelay.isZero()) { - throw logger - .logExceptionAsError(new IllegalArgumentException("'throttlingDelay' cannot be negative or zero.")); - } - - this.throttlingDelay = throttlingDelay; - return this; - } + /** + * Builds an instance of DataSourcesClient class. + * + * @return an instance of DataSourcesClient. + */ + @Generated + public DataSourcesClient buildDataSourcesClient() { + return new DataSourcesClient(buildInnerClient().getDataSources()); + } - /** - * Sets the maximum duration that requests will be delayed when the service is throttling. - *

- * If {@code maxThrottlingDelay} is less than {@link #throttlingDelay(Duration)} then {@link - * #throttlingDelay(Duration)} will be used as the maximum delay. - *

- * Default value is {@code Duration.ofMinutes(1)}. - * - * @param maxThrottlingDelay The maximum duration requests will delay when the service is throttling. - * @return The updated SearchIndexingBufferedSenderBuilder object. - * @throws IllegalArgumentException If {@code maxThrottlingDelay.isNegative()} or {@code - * maxThrottlingDelay.isZero()} is true. - * @throws NullPointerException If {@code maxThrottlingDelay} is null. - */ - public SearchIndexingBufferedSenderBuilder maxThrottlingDelay(Duration maxThrottlingDelay) { - Objects.requireNonNull(maxThrottlingDelay, "'maxThrottlingDelay' cannot be null."); - - if (maxThrottlingDelay.isNegative() || maxThrottlingDelay.isZero()) { - throw logger.logExceptionAsError( - new IllegalArgumentException("'maxThrottlingDelay' cannot be negative or zero.")); - } - - this.maxThrottlingDelay = maxThrottlingDelay; - return this; - } + /** + * Builds an instance of IndexersClient class. + * + * @return an instance of IndexersClient. + */ + @Generated + public IndexersClient buildIndexersClient() { + return new IndexersClient(buildInnerClient().getIndexers()); + } - /** - * Callback hook for when a document indexing action has been added to a batch queued. - * - * @param onActionAddedConsumer The {@link Consumer} that is called when a document has been added to a batch - * queue. - * @return The updated SearchIndexingBufferedSenderBuilder object. - */ - public SearchIndexingBufferedSenderBuilder - onActionAdded(Consumer> onActionAddedConsumer) { - this.onActionAddedConsumer = onActionAddedConsumer; - return this; - } + /** + * Builds an instance of SkillsetsClient class. + * + * @return an instance of SkillsetsClient. + */ + @Generated + public SkillsetsClient buildSkillsetsClient() { + return new SkillsetsClient(buildInnerClient().getSkillsets()); + } - /** - * Sets the callback hook for when a document indexing action has successfully completed indexing. - * - * @param onActionSucceededConsumer The {@link Consumer} that is called when a document has been successfully - * indexing. - * @return The updated SearchIndexingBufferedSenderBuilder object. - */ - public SearchIndexingBufferedSenderBuilder - onActionSucceeded(Consumer> onActionSucceededConsumer) { - this.onActionSucceededConsumer = onActionSucceededConsumer; - return this; - } + /** + * Builds an instance of SynonymMapsClient class. + * + * @return an instance of SynonymMapsClient. + */ + @Generated + public SynonymMapsClient buildSynonymMapsClient() { + return new SynonymMapsClient(buildInnerClient().getSynonymMaps()); + } - /** - * Sets the callback hook for when a document indexing action has failed to index and isn't retryable. - * - * @param onActionErrorConsumer The {@link Consumer} that is called when a document has failed to index and - * isn't retryable. - * @return The updated SearchIndexingBufferedSenderBuilder object. - */ - public SearchIndexingBufferedSenderBuilder - onActionError(Consumer> onActionErrorConsumer) { - this.onActionErrorConsumer = onActionErrorConsumer; - return this; - } + /** + * Builds an instance of IndexesClient class. + * + * @return an instance of IndexesClient. + */ + @Generated + public IndexesClient buildIndexesClient() { + return new IndexesClient(buildInnerClient().getIndexes()); + } - /** - * Sets the callback hook for when a document indexing has been sent in a batching request. - * - * @param onActionSentConsumer The {@link Consumer} that is called when a document has been sent in a batch - * request. - * @return The updated SearchIndexingBufferedSenderBuilder object. - */ - public SearchIndexingBufferedSenderBuilder - onActionSent(Consumer> onActionSentConsumer) { - this.onActionSentConsumer = onActionSentConsumer; - return this; - } + /** + * Builds an instance of AliasesClient class. + * + * @return an instance of AliasesClient. + */ + @Generated + public AliasesClient buildAliasesClient() { + return new AliasesClient(buildInnerClient().getAliases()); + } - /** - * Sets the function that retrieves the key value from a document. - * - * @param documentKeyRetriever Function that retrieves the key from an {@link IndexAction}. - * @return The updated SearchIndexingBufferedSenderBuilder object. - * @throws NullPointerException If {@code documentKeyRetriever} is null. - */ - public SearchIndexingBufferedSenderBuilder documentKeyRetriever(Function documentKeyRetriever) { - this.documentKeyRetriever - = Objects.requireNonNull(documentKeyRetriever, "'documentKeyRetriever' cannot be null"); - return this; - } + /** + * Builds an instance of DocumentsClient class. + * + * @return an instance of DocumentsClient. + */ + @Generated + public DocumentsClient buildDocumentsClient() { + return new DocumentsClient(buildInnerClient().getDocuments()); } + + private static final ClientLogger LOGGER = new ClientLogger(SearchClientBuilder.class); } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/SearchDocument.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/SearchDocument.java deleted file mode 100644 index 39a92ae538ab..000000000000 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/SearchDocument.java +++ /dev/null @@ -1,30 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.search.documents; - -import java.util.HashMap; -import java.util.Map; - -/** - * Represents an untyped document returned from a search or document lookup. - */ -public final class SearchDocument extends HashMap { - private static final long serialVersionUID = 1L; - - /** - * Initializes a new instance of the SearchDocument class. - */ - public SearchDocument() { - super(); - } - - /** - * Initializes a new instance of the SearchDocument class with initial values. - * - * @param propertyMap Initial values of the document. - */ - public SearchDocument(Map propertyMap) { - super(propertyMap); - } -} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/SearchFilter.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/SearchFilter.java deleted file mode 100644 index be98f5d295a4..000000000000 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/SearchFilter.java +++ /dev/null @@ -1,147 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.search.documents; - -import com.azure.core.models.GeoLineString; -import com.azure.core.models.GeoPoint; -import com.azure.core.models.GeoPolygon; -import com.azure.core.models.GeoPosition; -import com.azure.core.util.CoreUtils; -import com.azure.core.util.logging.ClientLogger; -import com.azure.search.documents.implementation.util.SpatialFormatter; -import com.azure.search.documents.models.AutocompleteOptions; -import com.azure.search.documents.models.SearchOptions; -import com.azure.search.documents.models.SuggestOptions; - -import java.time.OffsetDateTime; -import java.time.ZoneOffset; -import java.time.format.DateTimeFormatter; -import java.util.Date; -import java.util.HashSet; -import java.util.Objects; -import java.util.Set; - -/** - * This class is used to help construct valid OData filter expressions by automatically replacing, quoting, and escaping - * string parameters. - *

- * The constructed OData filter expression is used by {@link AutocompleteOptions#setFilter(String)}, {@link - * SearchOptions#setFilter(String)}, and {@link SuggestOptions#setFilter(String)}. - *

- * For more information, see Filters in Azure Cognitive - * Search. - */ -public final class SearchFilter { - private static final ClientLogger LOGGER; - private static final Set> SAFE_CLASSES; - - static { - LOGGER = new ClientLogger(SearchFilter.class); - SAFE_CLASSES = new HashSet<>(20); - SAFE_CLASSES.add(boolean.class); - SAFE_CLASSES.add(Boolean.class); - SAFE_CLASSES.add(byte.class); - SAFE_CLASSES.add(Byte.class); - SAFE_CLASSES.add(short.class); - SAFE_CLASSES.add(Short.class); - SAFE_CLASSES.add(int.class); - SAFE_CLASSES.add(Integer.class); - SAFE_CLASSES.add(long.class); - SAFE_CLASSES.add(Long.class); - SAFE_CLASSES.add(float.class); - SAFE_CLASSES.add(Float.class); - SAFE_CLASSES.add(double.class); - SAFE_CLASSES.add(Double.class); - } - - /** - * Create an OData filter expression from a formattable string. - *

- * The format argument values will be quoted and escaped as necessary. - * - * @param formattableString The formattable string. - * @param args The arguments for the formattable string. - * @return A valid OData filter expression. - */ - public static String create(String formattableString, Object... args) { - if (formattableString == null) { - return null; - } - - if (CoreUtils.isNullOrEmpty(args)) { - return formattableString; - } - - return String.format(formattableString, cleanseArguments(args)); - } - - @SuppressWarnings("UseOfObsoleteDateTimeApi") - private static Object[] cleanseArguments(Object... args) { - Object[] cleanedArgs = new Object[args.length]; - for (int i = 0; i < args.length; i++) { - Object arg = args[i]; - if (arg == null) { - cleanedArgs[i] = null; - continue; - } - - Class argClass = arg.getClass(); - if (Objects.equals(arg, Float.NEGATIVE_INFINITY) || Objects.equals(arg, Double.NEGATIVE_INFINITY)) { - cleanedArgs[i] = "-INF"; - } else if (Objects.equals(arg, Float.POSITIVE_INFINITY) || Objects.equals(arg, Double.POSITIVE_INFINITY)) { - cleanedArgs[i] = "INF"; - } else if (SAFE_CLASSES.contains(argClass)) { - cleanedArgs[i] = arg; - } else if (arg instanceof Date) { - cleanedArgs[i] = DateTimeFormatter.ISO_OFFSET_DATE_TIME - .format(OffsetDateTime.ofInstant(((Date) arg).toInstant(), ZoneOffset.UTC)); - } else if (arg instanceof OffsetDateTime) { - cleanedArgs[i] = DateTimeFormatter.ISO_OFFSET_DATE_TIME.format((OffsetDateTime) arg); - } else if (arg instanceof CharSequence) { - cleanedArgs[i] = quote(((CharSequence) arg).toString()); - } else if (argClass.isAssignableFrom(char.class) || arg instanceof Character) { - cleanedArgs[i] = quote(((Character) arg).toString()); - } else if (arg instanceof GeoPosition) { - GeoPosition position = (GeoPosition) arg; - cleanedArgs[i] = SpatialFormatter.encodePoint(position.getLongitude(), position.getLatitude()); - } else if (arg instanceof GeoPoint) { - GeoPosition position = ((GeoPoint) arg).getCoordinates(); - cleanedArgs[i] = SpatialFormatter.encodePoint(position.getLongitude(), position.getLatitude()); - } else if (arg instanceof GeoLineString) { - cleanedArgs[i] = SpatialFormatter.encodePolygon((GeoLineString) arg, LOGGER); - } else if (arg instanceof GeoPolygon) { - cleanedArgs[i] = SpatialFormatter.encodePolygon((GeoPolygon) arg, LOGGER); - } else { - throw LOGGER.logExceptionAsError(new IllegalArgumentException(String.format( - "Unable to convert argument %s from type %s to an OData literal.", arg, argClass.getName()))); - } - } - - return cleanedArgs; - } - - /* - * Quote and escape OData strings. - */ - private static String quote(String text) { - if (text == null) { - return "null"; - } - - // Optimistically allocate an extra 5% for escapes - StringBuilder builder = new StringBuilder(2 + (int) (text.length() * 1.05)).append("'"); - - for (char ch : text.toCharArray()) { - builder.append(ch); - if (ch == '\'') { - builder.append(ch); - } - } - - return builder.append("'").toString(); - } - - private SearchFilter() { - } -} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/SearchIndexingBufferedAsyncSender.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/SearchIndexingBufferedAsyncSender.java deleted file mode 100644 index 42bd2f4236f1..000000000000 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/SearchIndexingBufferedAsyncSender.java +++ /dev/null @@ -1,259 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.search.documents; - -import com.azure.core.annotation.ServiceClient; -import com.azure.core.util.Context; -import com.azure.core.util.logging.ClientLogger; -import com.azure.core.util.serializer.JsonSerializer; -import com.azure.search.documents.implementation.SearchIndexClientImpl; -import com.azure.search.documents.implementation.batching.SearchIndexingAsyncPublisher; -import com.azure.search.documents.models.IndexAction; -import com.azure.search.documents.models.IndexActionType; -import com.azure.search.documents.options.OnActionAddedOptions; -import com.azure.search.documents.options.OnActionErrorOptions; -import com.azure.search.documents.options.OnActionSentOptions; -import com.azure.search.documents.options.OnActionSucceededOptions; -import reactor.core.publisher.Mono; - -import java.time.Duration; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Timer; -import java.util.TimerTask; -import java.util.concurrent.atomic.AtomicReference; -import java.util.concurrent.locks.ReentrantLock; -import java.util.function.Consumer; -import java.util.function.Function; - -import static com.azure.core.util.FluxUtil.withContext; - -/** - * This class provides a buffered sender that contains operations for conveniently indexing documents to an Azure Search - * index. - * - * @param The type of the document handled by this buffered indexing sender. - */ -@ServiceClient(builder = SearchClientBuilder.class, isAsync = true) -public final class SearchIndexingBufferedAsyncSender { - private static final ClientLogger LOGGER = new ClientLogger(SearchIndexingBufferedAsyncSender.class); - - private final boolean autoFlush; - private final long flushWindowMillis; - - final SearchIndexingAsyncPublisher publisher; - - private Timer autoFlushTimer; - private final AtomicReference flushTask = new AtomicReference<>(); - - private volatile boolean isClosed = false; - private final ReentrantLock closeLock = new ReentrantLock(); - - SearchIndexingBufferedAsyncSender(SearchIndexClientImpl restClient, JsonSerializer serializer, - Function documentKeyRetriever, boolean autoFlush, Duration autoFlushInterval, - int initialBatchActionCount, int maxRetriesPerAction, Duration throttlingDelay, Duration maxThrottlingDelay, - Consumer> onActionAddedConsumer, - Consumer> onActionSucceededConsumer, - Consumer> onActionErrorConsumer, - Consumer> onActionSentConsumer) { - this.publisher = new SearchIndexingAsyncPublisher<>(restClient, serializer, documentKeyRetriever, autoFlush, - initialBatchActionCount, maxRetriesPerAction, throttlingDelay, maxThrottlingDelay, onActionAddedConsumer, - onActionSucceededConsumer, onActionErrorConsumer, onActionSentConsumer); - - this.autoFlush = autoFlush; - this.flushWindowMillis = Math.max(0, autoFlushInterval.toMillis()); - this.autoFlushTimer = (this.autoFlush && this.flushWindowMillis > 0) ? new Timer() : null; - - } - - /** - * Gets the {@link IndexAction IndexActions} in the batch that are ready to be indexed. - * - * @return The {@link IndexAction IndexActions} in the batch that are ready to be indexed. - */ - public Collection> getActions() { - return publisher.getActions(); - } - - /** - * Gets the number of documents required in a batch for it to be flushed. - *

- * This configuration is only taken into account if auto flushing is enabled. - * - * @return The number of documents required before a flush is triggered. - */ - int getBatchActionCount() { - return publisher.getBatchSize(); - } - - /** - * Adds upload document actions to the batch. - *

- * If the client is enabled for automatic batch sending, adding documents may trigger the batch to be sent for - * indexing. - * - * @param documents Documents to be uploaded. - * @return A reactive response indicating that the documents have been added to the batch. - */ - public Mono addUploadActions(Collection documents) { - return withContext(context -> createAndAddActions(documents, IndexActionType.UPLOAD, context)); - } - - /** - * Adds delete document actions to the batch. - *

- * If the client is enabled for automatic batch sending, adding documents may trigger the batch to be sent for - * indexing. - * - * @param documents Documents to be deleted. - * @return A reactive response indicating that the documents have been added to the batch. - */ - public Mono addDeleteActions(Collection documents) { - return withContext(context -> createAndAddActions(documents, IndexActionType.DELETE, context)); - } - - /** - * Adds merge document actions to the batch. - *

- * If the client is enabled for automatic batch sending, adding documents may trigger the batch to be sent for - * indexing. - * - * @param documents Documents to be merged. - * @return A reactive response indicating that the documents have been added to the batch. - */ - public Mono addMergeActions(Collection documents) { - return withContext(context -> createAndAddActions(documents, IndexActionType.MERGE, context)); - } - - /** - * Adds merge or upload document actions to the batch. - *

- * If the client is enabled for automatic batch sending, adding documents may trigger the batch to be sent for - * indexing. - * - * @param documents Documents to be merged or uploaded. - * @return A reactive response indicating that the documents have been added to the batch. - */ - public Mono addMergeOrUploadActions(Collection documents) { - return withContext(context -> createAndAddActions(documents, IndexActionType.MERGE_OR_UPLOAD, context)); - } - - /** - * Adds document index actions to the batch. - *

- * If the client is enabled for automatic batch sending, adding documents may trigger the batch to be sent for - * indexing. - * - * @param actions Index actions. - * @return A reactive response indicating that the documents have been added to the batch. - */ - public Mono addActions(Collection> actions) { - return withContext(context -> addActions(actions, context)); - } - - Mono createAndAddActions(Collection documents, IndexActionType actionType, Context context) { - return addActions(createDocumentActions(documents, actionType), context); - } - - Mono addActions(Collection> actions, Context context) { - ensureOpen(); - - return publisher.addActions(actions, context, this::rescheduleFlushTask); - } - - /** - * Sends the current batch of documents to be indexed. - * - * @return A reactive response that indicates if the flush operation has completed. - */ - public Mono flush() { - return withContext(this::flush); - } - - Mono flush(Context context) { - ensureOpen(); - - rescheduleFlushTask(); - return publisher.flush(false, false, context); - } - - private void rescheduleFlushTask() { - if (!autoFlush) { - return; - } - - TimerTask newTask = new TimerTask() { - @Override - public void run() { - Mono.defer(() -> publisher.flush(false, false, Context.NONE)).subscribe(); - } - }; - - // If the previous flush task exists cancel it. If it has already executed cancel does nothing. - TimerTask previousTask = this.flushTask.getAndSet(newTask); - if (previousTask != null) { - previousTask.cancel(); - } - - this.autoFlushTimer.schedule(newTask, flushWindowMillis); - } - - /** - * Closes the buffered sender, any documents remaining in the batch will be sent to the Search index for indexing. - *

- * Once the buffered sender has been closed any attempts to add documents or flush it will cause an {@link - * IllegalStateException} to be thrown. - * - * @return A reactive response indicating that the buffered sender has been closed. - */ - public Mono close() { - return withContext(this::close); - } - - Mono close(Context context) { - if (!isClosed) { - closeLock.lock(); - try { - if (!isClosed) { - isClosed = true; - if (this.autoFlush) { - TimerTask currentTask = flushTask.getAndSet(null); - if (currentTask != null) { - currentTask.cancel(); - } - - autoFlushTimer.purge(); - autoFlushTimer.cancel(); - autoFlushTimer = null; - } - - return publisher.flush(true, true, context); - } - - return Mono.empty(); - } finally { - closeLock.unlock(); - } - } - - return Mono.empty(); - } - - private void ensureOpen() { - if (isClosed) { - throw LOGGER.logExceptionAsError(new IllegalStateException("Buffered sender has been closed.")); - } - } - - private static Collection> createDocumentActions(Collection documents, - IndexActionType actionType) { - Collection> actions = new ArrayList<>(documents.size()); - - for (T document : documents) { - actions.add(new IndexAction().setActionType(actionType).setDocument(document)); - } - - return actions; - } -} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/SearchIndexingBufferedSender.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/SearchIndexingBufferedSender.java deleted file mode 100644 index 52185156e3d7..000000000000 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/SearchIndexingBufferedSender.java +++ /dev/null @@ -1,339 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.search.documents; - -import com.azure.core.annotation.ServiceClient; -import com.azure.core.util.Context; -import com.azure.core.util.logging.ClientLogger; -import com.azure.core.util.serializer.JsonSerializer; -import com.azure.search.documents.implementation.SearchIndexClientImpl; -import com.azure.search.documents.implementation.batching.SearchIndexingPublisher; -import com.azure.search.documents.models.IndexAction; -import com.azure.search.documents.models.IndexActionType; -import com.azure.search.documents.options.OnActionAddedOptions; -import com.azure.search.documents.options.OnActionErrorOptions; -import com.azure.search.documents.options.OnActionSentOptions; -import com.azure.search.documents.options.OnActionSucceededOptions; - -import java.time.Duration; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Timer; -import java.util.TimerTask; -import java.util.concurrent.atomic.AtomicBoolean; -import java.util.concurrent.atomic.AtomicReferenceFieldUpdater; -import java.util.concurrent.locks.ReentrantLock; -import java.util.function.Consumer; -import java.util.function.Function; - -/** - * This class provides a buffered sender that contains operations for conveniently indexing documents to an Azure Search - * index. - * - * @param The type of the document handled by this buffered indexing sender. - */ -@ServiceClient(builder = SearchClientBuilder.class) -public final class SearchIndexingBufferedSender { - private static final ClientLogger LOGGER = new ClientLogger(SearchIndexingBufferedSender.class); - - private final boolean autoFlush; - private final long flushWindowMillis; - - final SearchIndexingPublisher publisher; - - private Timer autoFlushTimer; - - @SuppressWarnings("rawtypes") - private static final AtomicReferenceFieldUpdater FLUSH_TASK - = AtomicReferenceFieldUpdater.newUpdater(SearchIndexingBufferedSender.class, TimerTask.class, "flushTask"); - private volatile TimerTask flushTask; - - private final AtomicBoolean closed = new AtomicBoolean(); - private final ReentrantLock closeLock = new ReentrantLock(); - - SearchIndexingBufferedSender(SearchIndexClientImpl restClient, JsonSerializer serializer, - Function documentKeyRetriever, boolean autoFlush, Duration autoFlushInterval, - int initialBatchActionCount, int maxRetriesPerAction, Duration throttlingDelay, Duration maxThrottlingDelay, - Consumer> onActionAddedConsumer, - Consumer> onActionSucceededConsumer, - Consumer> onActionErrorConsumer, - Consumer> onActionSentConsumer) { - this.publisher = new SearchIndexingPublisher<>(restClient, serializer, documentKeyRetriever, autoFlush, - initialBatchActionCount, maxRetriesPerAction, throttlingDelay, maxThrottlingDelay, onActionAddedConsumer, - onActionSucceededConsumer, onActionErrorConsumer, onActionSentConsumer); - - this.autoFlush = autoFlush; - this.flushWindowMillis = Math.max(0, autoFlushInterval.toMillis()); - this.autoFlushTimer = (this.autoFlush && this.flushWindowMillis > 0) ? new Timer() : null; - } - - /** - * Gets the list of {@link IndexAction IndexActions} in the batch that are ready to be indexed. - * - * @return The list of {@link IndexAction IndexActions} in the batch that are ready to be indexed. - */ - public Collection> getActions() { - return publisher.getActions(); - } - - /** - * Gets the number of documents required in a batch for it to be flushed. - *

- * This configuration is only taken into account if auto flushing is enabled. - * - * @return The number of documents required before a flush is triggered. - */ - int getBatchActionCount() { - return publisher.getBatchSize(); - } - - /** - * Adds upload document actions to the batch. - *

- * If the client is enabled for automatic batch sending, adding documents may trigger the batch to be sent for - * indexing. - * - * @param documents Documents to be uploaded. - */ - public void addUploadActions(Collection documents) { - addUploadActions(documents, null, Context.NONE); - } - - /** - * Adds upload document actions to the batch. - *

- * If the client is enabled for automatic batch sending, adding documents may trigger the batch to be sent for - * indexing. - * - * @param documents Documents to be uploaded. - * @param timeout Duration before the operation times out. - * @param context Additional context that is passed through the HTTP pipeline. - */ - public void addUploadActions(Collection documents, Duration timeout, Context context) { - createAndAddActions(documents, IndexActionType.UPLOAD, timeout, context); - } - - /** - * Adds delete document actions to the batch. - *

- * If the client is enabled for automatic batch sending, adding documents may trigger the batch to be sent for - * indexing. - * - * @param documents Documents to be deleted. - */ - public void addDeleteActions(Collection documents) { - addDeleteActions(documents, null, Context.NONE); - } - - /** - * Adds delete document actions to the batch. - *

- * If the client is enabled for automatic batch sending, adding documents may trigger the batch to be sent for - * indexing. - * - * @param documents Documents to be deleted. - * @param timeout Duration before the operation times out. - * @param context Additional context that is passed through the HTTP pipeline. - */ - public void addDeleteActions(Collection documents, Duration timeout, Context context) { - createAndAddActions(documents, IndexActionType.DELETE, timeout, context); - } - - /** - * Adds merge document actions to the batch. - *

- * If the client is enabled for automatic batch sending, adding documents may trigger the batch to be sent for - * indexing. - * - * @param documents Documents to be merged. - */ - public void addMergeActions(Collection documents) { - addMergeActions(documents, null, Context.NONE); - } - - /** - * Adds merge document actions to the batch. - *

- * If the client is enabled for automatic batch sending, adding documents may trigger the batch to be sent for - * indexing. - * - * @param documents Documents to be merged. - * @param timeout Duration before the operation times out. - * @param context Additional context that is passed through the HTTP pipeline. - */ - public void addMergeActions(Collection documents, Duration timeout, Context context) { - createAndAddActions(documents, IndexActionType.MERGE, timeout, context); - } - - /** - * Adds merge or upload document actions to the batch. - *

- * If the client is enabled for automatic batch sending, adding documents may trigger the batch to be sent for - * indexing. - * - * @param documents Documents to be merged or uploaded. - */ - public void addMergeOrUploadActions(Collection documents) { - addMergeOrUploadActions(documents, null, Context.NONE); - } - - /** - * Adds merge or upload document actions to the batch. - *

- * If the client is enabled for automatic batch sending, adding documents may trigger the batch to be sent for - * indexing. - * - * @param documents Documents to be merged or uploaded. - * @param timeout Duration before the operation times out. - * @param context Additional context that is passed through the HTTP pipeline. - */ - public void addMergeOrUploadActions(Collection documents, Duration timeout, Context context) { - createAndAddActions(documents, IndexActionType.MERGE_OR_UPLOAD, timeout, context); - } - - /** - * Adds document index actions to the batch. - *

- * If the client is enabled for automatic batch sending, adding documents may trigger the batch to be sent for - * indexing. - * - * @param actions Index actions. - */ - public void addActions(Collection> actions) { - addActions(actions, null, Context.NONE); - } - - /** - * Adds document index actions to the batch. - *

- * If the client is enabled for automatic batch sending, adding documents may trigger the batch to be sent for - * indexing. - * - * @param actions Index actions. - * @param timeout Duration before the operation times out. - * @param context Additional context that is passed through the HTTP pipeline. - */ - public void addActions(Collection> actions, Duration timeout, Context context) { - addActionsInternal(actions, timeout, context); - } - - void createAndAddActions(Collection documents, IndexActionType actionType, Duration timeout, Context context) { - addActionsInternal(createDocumentActions(documents, actionType), timeout, context); - } - - void addActionsInternal(Collection> actions, Duration timeout, Context context) { - ensureOpen(); - - publisher.addActions(actions, timeout, context, this::rescheduleFlushTask); - } - - /** - * Sends the current batch of documents to be indexed. - */ - public void flush() { - flush(null, Context.NONE); - } - - /** - * Sends the current batch of documents to be indexed. - * - * @param timeout Duration before the operation times out. - * @param context Additional context that is passed through the HTTP pipeline. - */ - public void flush(Duration timeout, Context context) { - flushInternal(timeout, context); - } - - void flushInternal(Duration timeout, Context context) { - ensureOpen(); - - rescheduleFlushTask(); - publisher.flush(false, false, timeout, context); - } - - private void rescheduleFlushTask() { - if (!autoFlush) { - return; - } - - TimerTask newTask = new TimerTask() { - @Override - public void run() { - publisher.flush(false, false, null, Context.NONE); - } - }; - - // If the previous flush task exists cancel it. If it has already executed cancel does nothing. - TimerTask previousTask = FLUSH_TASK.getAndSet(this, newTask); - if (previousTask != null) { - previousTask.cancel(); - } - - this.autoFlushTimer.schedule(newTask, flushWindowMillis); - } - - /** - * Closes the buffered sender, any documents remaining in the batch will be sent to the Search index for indexing. - *

- * Once the buffered sender has been closed any attempts to add documents or flush it will cause an {@link - * IllegalStateException} to be thrown. - */ - public void close() { - close(null, Context.NONE); - } - - /** - * Closes the buffered, any documents remaining in the batch yet to be sent to the Search index for indexing. - *

- * Once the buffered sender has been closed any attempts to add documents or flush it will cause an {@link - * IllegalStateException} to be thrown. - * - * @param timeout Duration before the operation times out. - * @param context Additional context that is passed through the HTTP pipeline. - */ - public void close(Duration timeout, Context context) { - closeInternal(timeout, context); - } - - void closeInternal(Duration timeout, Context context) { - if (!closed.get()) { - closeLock.lock(); - try { - if (closed.compareAndSet(false, true)) { - if (this.autoFlush) { - TimerTask currentTask = FLUSH_TASK.getAndSet(this, null); - if (currentTask != null) { - currentTask.cancel(); - } - - autoFlushTimer.purge(); - autoFlushTimer.cancel(); - autoFlushTimer = null; - } - - publisher.flush(true, true, timeout, context); - } - } finally { - closeLock.unlock(); - } - } - } - - private void ensureOpen() { - if (closed.get()) { - throw LOGGER.logExceptionAsError(new IllegalStateException("Buffered sender has been closed.")); - } - } - - private static Collection> createDocumentActions(Collection documents, - IndexActionType actionType) { - Collection> actions = new ArrayList<>(documents.size()); - - for (T document : documents) { - actions.add(new IndexAction().setActionType(actionType).setDocument(document)); - } - - return actions; - } -} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/SearchServiceVersion.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/SearchServiceVersion.java index 040dd4510280..fe57318cbde1 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/SearchServiceVersion.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/SearchServiceVersion.java @@ -1,33 +1,24 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.search.documents; import com.azure.core.util.ServiceVersion; /** - * The versions of Azure AI Search supported by this client library. + * Service version of SearchClient. */ public enum SearchServiceVersion implements ServiceVersion { /** - * {@code 2020-06-30} service version. - */ - V2020_06_30("2020-06-30"), - - /** - * {@code 2023-11-01} service version. - */ - V2023_11_01("2023-11-01"), - - /** - * {@code 2024-07-01} service version. + * Enum value 2024-07-01. */ V2024_07_01("2024-07-01"), /** - * {@code 2024-11-01-preview} service version. + * Enum value 2025-03-01-preview. */ - V2024_11_01_PREVIEW("2024-11-01-preview"); + V2025_03_01_PREVIEW("2025-03-01-preview"); private final String version; @@ -45,10 +36,10 @@ public String getVersion() { /** * Gets the latest service version supported by this client library. - * - * @return The latest version supported by this client library. + * + * @return The latest {@link SearchServiceVersion}. */ public static SearchServiceVersion getLatest() { - return V2024_11_01_PREVIEW; + return V2025_03_01_PREVIEW; } } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/SkillsetsAsyncClient.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/SkillsetsAsyncClient.java new file mode 100644 index 000000000000..a323d68407d4 --- /dev/null +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/SkillsetsAsyncClient.java @@ -0,0 +1,1149 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.search.documents; + +import com.azure.core.annotation.Generated; +import com.azure.core.annotation.ReturnType; +import com.azure.core.annotation.ServiceClient; +import com.azure.core.annotation.ServiceMethod; +import com.azure.core.exception.ClientAuthenticationException; +import com.azure.core.exception.HttpResponseException; +import com.azure.core.exception.ResourceModifiedException; +import com.azure.core.exception.ResourceNotFoundException; +import com.azure.core.http.HttpHeaderName; +import com.azure.core.http.MatchConditions; +import com.azure.core.http.rest.RequestOptions; +import com.azure.core.http.rest.Response; +import com.azure.core.util.BinaryData; +import com.azure.core.util.FluxUtil; +import com.azure.search.documents.implementation.SkillsetsImpl; +import com.azure.search.documents.models.ListSkillsetsResult; +import com.azure.search.documents.models.SearchIndexerSkillset; +import com.azure.search.documents.models.SkillNames; +import reactor.core.publisher.Mono; + +/** + * Initializes a new instance of the asynchronous SearchClient type. + */ +@ServiceClient(builder = SearchClientBuilder.class, isAsync = true) +public final class SkillsetsAsyncClient { + @Generated + private final SkillsetsImpl serviceClient; + + /** + * Initializes an instance of SkillsetsAsyncClient class. + * + * @param serviceClient the service client implementation. + */ + @Generated + SkillsetsAsyncClient(SkillsetsImpl serviceClient) { + this.serviceClient = serviceClient; + } + + /** + * Creates a new skillset in a search service or updates the skillset if it + * already exists. + *

Query Parameters

+ * + * + * + * + * + *
Query Parameters
NameTypeRequiredDescription
ignoreResetRequirementsBooleanNoIgnores cache reset requirements.
disableCacheReprocessingChangeDetectionBooleanNoDisables cache reprocessing + * change detection.
+ * You can add these to a request with {@link RequestOptions#addQueryParam} + *

Header Parameters

+ * + * + * + * + * + *
Header Parameters
NameTypeRequiredDescription
If-MatchStringNoDefines the If-Match condition. The operation will be + * performed only if the ETag on the server matches this value.
If-None-MatchStringNoDefines the If-None-Match condition. The operation will + * be performed only if the ETag on the server does not match this value.
+ * You can add these to a request with {@link RequestOptions#addHeader} + *

Request Body Schema

+ * + *
+     * {@code
+     * {
+     *     name: String (Required)
+     *     description: String (Optional)
+     *     skills (Required): [
+     *          (Required){
+     *             @odata.type: String (Required)
+     *             name: String (Optional)
+     *             description: String (Optional)
+     *             context: String (Optional)
+     *             inputs (Required): [
+     *                  (Required){
+     *                     name: String (Required)
+     *                     source: String (Optional)
+     *                     sourceContext: String (Optional)
+     *                     inputs (Optional): [
+     *                         (recursive schema, see above)
+     *                     ]
+     *                 }
+     *             ]
+     *             outputs (Required): [
+     *                  (Required){
+     *                     name: String (Required)
+     *                     targetName: String (Optional)
+     *                 }
+     *             ]
+     *         }
+     *     ]
+     *     cognitiveServices (Optional): {
+     *         @odata.type: String (Required)
+     *         description: String (Optional)
+     *     }
+     *     knowledgeStore (Optional): {
+     *         storageConnectionString: String (Required)
+     *         projections (Required): [
+     *              (Required){
+     *                 tables (Optional): [
+     *                      (Optional){
+     *                         referenceKeyName: String (Optional)
+     *                         generatedKeyName: String (Optional)
+     *                         source: String (Optional)
+     *                         sourceContext: String (Optional)
+     *                         inputs (Optional): [
+     *                             (recursive schema, see above)
+     *                         ]
+     *                         tableName: String (Required)
+     *                     }
+     *                 ]
+     *                 objects (Optional): [
+     *                      (Optional){
+     *                         referenceKeyName: String (Optional)
+     *                         generatedKeyName: String (Optional)
+     *                         source: String (Optional)
+     *                         sourceContext: String (Optional)
+     *                         inputs (Optional): [
+     *                             (recursive schema, see above)
+     *                         ]
+     *                         storageContainer: String (Required)
+     *                     }
+     *                 ]
+     *                 files (Optional): [
+     *                      (Optional){
+     *                         referenceKeyName: String (Optional)
+     *                         generatedKeyName: String (Optional)
+     *                         source: String (Optional)
+     *                         sourceContext: String (Optional)
+     *                         inputs (Optional): [
+     *                             (recursive schema, see above)
+     *                         ]
+     *                         storageContainer: String (Required)
+     *                     }
+     *                 ]
+     *             }
+     *         ]
+     *         identity (Optional): {
+     *             @odata.type: String (Required)
+     *         }
+     *         parameters (Optional): {
+     *             synthesizeGeneratedKeyName: Boolean (Optional)
+     *              (Optional): {
+     *                 String: BinaryData (Required)
+     *             }
+     *         }
+     *     }
+     *     indexProjections (Optional): {
+     *         selectors (Required): [
+     *              (Required){
+     *                 targetIndexName: String (Required)
+     *                 parentKeyFieldName: String (Required)
+     *                 sourceContext: String (Required)
+     *                 mappings (Required): [
+     *                     (recursive schema, see above)
+     *                 ]
+     *             }
+     *         ]
+     *         parameters (Optional): {
+     *             projectionMode: String(skipIndexingParentDocuments/includeIndexingParentDocuments) (Optional)
+     *              (Optional): {
+     *                 String: BinaryData (Required)
+     *             }
+     *         }
+     *     }
+     *     @odata.etag: String (Optional)
+     *     encryptionKey (Optional): {
+     *         keyVaultKeyName: String (Required)
+     *         keyVaultKeyVersion: String (Optional)
+     *         keyVaultUri: String (Required)
+     *         accessCredentials (Optional): {
+     *             applicationId: String (Required)
+     *             applicationSecret: String (Optional)
+     *         }
+     *         identity (Optional): (recursive schema, see identity above)
+     *     }
+     * }
+     * }
+     * 
+ * + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     name: String (Required)
+     *     description: String (Optional)
+     *     skills (Required): [
+     *          (Required){
+     *             @odata.type: String (Required)
+     *             name: String (Optional)
+     *             description: String (Optional)
+     *             context: String (Optional)
+     *             inputs (Required): [
+     *                  (Required){
+     *                     name: String (Required)
+     *                     source: String (Optional)
+     *                     sourceContext: String (Optional)
+     *                     inputs (Optional): [
+     *                         (recursive schema, see above)
+     *                     ]
+     *                 }
+     *             ]
+     *             outputs (Required): [
+     *                  (Required){
+     *                     name: String (Required)
+     *                     targetName: String (Optional)
+     *                 }
+     *             ]
+     *         }
+     *     ]
+     *     cognitiveServices (Optional): {
+     *         @odata.type: String (Required)
+     *         description: String (Optional)
+     *     }
+     *     knowledgeStore (Optional): {
+     *         storageConnectionString: String (Required)
+     *         projections (Required): [
+     *              (Required){
+     *                 tables (Optional): [
+     *                      (Optional){
+     *                         referenceKeyName: String (Optional)
+     *                         generatedKeyName: String (Optional)
+     *                         source: String (Optional)
+     *                         sourceContext: String (Optional)
+     *                         inputs (Optional): [
+     *                             (recursive schema, see above)
+     *                         ]
+     *                         tableName: String (Required)
+     *                     }
+     *                 ]
+     *                 objects (Optional): [
+     *                      (Optional){
+     *                         referenceKeyName: String (Optional)
+     *                         generatedKeyName: String (Optional)
+     *                         source: String (Optional)
+     *                         sourceContext: String (Optional)
+     *                         inputs (Optional): [
+     *                             (recursive schema, see above)
+     *                         ]
+     *                         storageContainer: String (Required)
+     *                     }
+     *                 ]
+     *                 files (Optional): [
+     *                      (Optional){
+     *                         referenceKeyName: String (Optional)
+     *                         generatedKeyName: String (Optional)
+     *                         source: String (Optional)
+     *                         sourceContext: String (Optional)
+     *                         inputs (Optional): [
+     *                             (recursive schema, see above)
+     *                         ]
+     *                         storageContainer: String (Required)
+     *                     }
+     *                 ]
+     *             }
+     *         ]
+     *         identity (Optional): {
+     *             @odata.type: String (Required)
+     *         }
+     *         parameters (Optional): {
+     *             synthesizeGeneratedKeyName: Boolean (Optional)
+     *              (Optional): {
+     *                 String: BinaryData (Required)
+     *             }
+     *         }
+     *     }
+     *     indexProjections (Optional): {
+     *         selectors (Required): [
+     *              (Required){
+     *                 targetIndexName: String (Required)
+     *                 parentKeyFieldName: String (Required)
+     *                 sourceContext: String (Required)
+     *                 mappings (Required): [
+     *                     (recursive schema, see above)
+     *                 ]
+     *             }
+     *         ]
+     *         parameters (Optional): {
+     *             projectionMode: String(skipIndexingParentDocuments/includeIndexingParentDocuments) (Optional)
+     *              (Optional): {
+     *                 String: BinaryData (Required)
+     *             }
+     *         }
+     *     }
+     *     @odata.etag: String (Optional)
+     *     encryptionKey (Optional): {
+     *         keyVaultKeyName: String (Required)
+     *         keyVaultKeyVersion: String (Optional)
+     *         keyVaultUri: String (Required)
+     *         accessCredentials (Optional): {
+     *             applicationId: String (Required)
+     *             applicationSecret: String (Optional)
+     *         }
+     *         identity (Optional): (recursive schema, see identity above)
+     *     }
+     * }
+     * }
+     * 
+ * + * @param skillsetName The name of the skillset. + * @param skillset The skillset containing one or more skills to create or update in a search + * service. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return a list of skills along with {@link Response} on successful completion of {@link Mono}. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono> createOrUpdateWithResponse(String skillsetName, BinaryData skillset, + RequestOptions requestOptions) { + return this.serviceClient.createOrUpdateWithResponseAsync(skillsetName, skillset, requestOptions); + } + + /** + * Deletes a skillset in a search service. + *

Header Parameters

+ * + * + * + * + * + *
Header Parameters
NameTypeRequiredDescription
If-MatchStringNoDefines the If-Match condition. The operation will be + * performed only if the ETag on the server matches this value.
If-None-MatchStringNoDefines the If-None-Match condition. The operation will + * be performed only if the ETag on the server does not match this value.
+ * You can add these to a request with {@link RequestOptions#addHeader} + * + * @param skillsetName The name of the skillset. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return the {@link Response} on successful completion of {@link Mono}. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono> deleteWithResponse(String skillsetName, RequestOptions requestOptions) { + return this.serviceClient.deleteWithResponseAsync(skillsetName, requestOptions); + } + + /** + * Retrieves a skillset in a search service. + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     name: String (Required)
+     *     description: String (Optional)
+     *     skills (Required): [
+     *          (Required){
+     *             @odata.type: String (Required)
+     *             name: String (Optional)
+     *             description: String (Optional)
+     *             context: String (Optional)
+     *             inputs (Required): [
+     *                  (Required){
+     *                     name: String (Required)
+     *                     source: String (Optional)
+     *                     sourceContext: String (Optional)
+     *                     inputs (Optional): [
+     *                         (recursive schema, see above)
+     *                     ]
+     *                 }
+     *             ]
+     *             outputs (Required): [
+     *                  (Required){
+     *                     name: String (Required)
+     *                     targetName: String (Optional)
+     *                 }
+     *             ]
+     *         }
+     *     ]
+     *     cognitiveServices (Optional): {
+     *         @odata.type: String (Required)
+     *         description: String (Optional)
+     *     }
+     *     knowledgeStore (Optional): {
+     *         storageConnectionString: String (Required)
+     *         projections (Required): [
+     *              (Required){
+     *                 tables (Optional): [
+     *                      (Optional){
+     *                         referenceKeyName: String (Optional)
+     *                         generatedKeyName: String (Optional)
+     *                         source: String (Optional)
+     *                         sourceContext: String (Optional)
+     *                         inputs (Optional): [
+     *                             (recursive schema, see above)
+     *                         ]
+     *                         tableName: String (Required)
+     *                     }
+     *                 ]
+     *                 objects (Optional): [
+     *                      (Optional){
+     *                         referenceKeyName: String (Optional)
+     *                         generatedKeyName: String (Optional)
+     *                         source: String (Optional)
+     *                         sourceContext: String (Optional)
+     *                         inputs (Optional): [
+     *                             (recursive schema, see above)
+     *                         ]
+     *                         storageContainer: String (Required)
+     *                     }
+     *                 ]
+     *                 files (Optional): [
+     *                      (Optional){
+     *                         referenceKeyName: String (Optional)
+     *                         generatedKeyName: String (Optional)
+     *                         source: String (Optional)
+     *                         sourceContext: String (Optional)
+     *                         inputs (Optional): [
+     *                             (recursive schema, see above)
+     *                         ]
+     *                         storageContainer: String (Required)
+     *                     }
+     *                 ]
+     *             }
+     *         ]
+     *         identity (Optional): {
+     *             @odata.type: String (Required)
+     *         }
+     *         parameters (Optional): {
+     *             synthesizeGeneratedKeyName: Boolean (Optional)
+     *              (Optional): {
+     *                 String: BinaryData (Required)
+     *             }
+     *         }
+     *     }
+     *     indexProjections (Optional): {
+     *         selectors (Required): [
+     *              (Required){
+     *                 targetIndexName: String (Required)
+     *                 parentKeyFieldName: String (Required)
+     *                 sourceContext: String (Required)
+     *                 mappings (Required): [
+     *                     (recursive schema, see above)
+     *                 ]
+     *             }
+     *         ]
+     *         parameters (Optional): {
+     *             projectionMode: String(skipIndexingParentDocuments/includeIndexingParentDocuments) (Optional)
+     *              (Optional): {
+     *                 String: BinaryData (Required)
+     *             }
+     *         }
+     *     }
+     *     @odata.etag: String (Optional)
+     *     encryptionKey (Optional): {
+     *         keyVaultKeyName: String (Required)
+     *         keyVaultKeyVersion: String (Optional)
+     *         keyVaultUri: String (Required)
+     *         accessCredentials (Optional): {
+     *             applicationId: String (Required)
+     *             applicationSecret: String (Optional)
+     *         }
+     *         identity (Optional): (recursive schema, see identity above)
+     *     }
+     * }
+     * }
+     * 
+ * + * @param skillsetName The name of the skillset. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return a list of skills along with {@link Response} on successful completion of {@link Mono}. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono> getWithResponse(String skillsetName, RequestOptions requestOptions) { + return this.serviceClient.getWithResponseAsync(skillsetName, requestOptions); + } + + /** + * List all skillsets in a search service. + *

Query Parameters

+ * + * + * + * + *
Query Parameters
NameTypeRequiredDescription
$selectStringNoSelects 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.
+ * You can add these to a request with {@link RequestOptions#addQueryParam} + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     value (Required): [
+     *          (Required){
+     *             name: String (Required)
+     *             description: String (Optional)
+     *             skills (Required): [
+     *                  (Required){
+     *                     @odata.type: String (Required)
+     *                     name: String (Optional)
+     *                     description: String (Optional)
+     *                     context: String (Optional)
+     *                     inputs (Required): [
+     *                          (Required){
+     *                             name: String (Required)
+     *                             source: String (Optional)
+     *                             sourceContext: String (Optional)
+     *                             inputs (Optional): [
+     *                                 (recursive schema, see above)
+     *                             ]
+     *                         }
+     *                     ]
+     *                     outputs (Required): [
+     *                          (Required){
+     *                             name: String (Required)
+     *                             targetName: String (Optional)
+     *                         }
+     *                     ]
+     *                 }
+     *             ]
+     *             cognitiveServices (Optional): {
+     *                 @odata.type: String (Required)
+     *                 description: String (Optional)
+     *             }
+     *             knowledgeStore (Optional): {
+     *                 storageConnectionString: String (Required)
+     *                 projections (Required): [
+     *                      (Required){
+     *                         tables (Optional): [
+     *                              (Optional){
+     *                                 referenceKeyName: String (Optional)
+     *                                 generatedKeyName: String (Optional)
+     *                                 source: String (Optional)
+     *                                 sourceContext: String (Optional)
+     *                                 inputs (Optional): [
+     *                                     (recursive schema, see above)
+     *                                 ]
+     *                                 tableName: String (Required)
+     *                             }
+     *                         ]
+     *                         objects (Optional): [
+     *                              (Optional){
+     *                                 referenceKeyName: String (Optional)
+     *                                 generatedKeyName: String (Optional)
+     *                                 source: String (Optional)
+     *                                 sourceContext: String (Optional)
+     *                                 inputs (Optional): [
+     *                                     (recursive schema, see above)
+     *                                 ]
+     *                                 storageContainer: String (Required)
+     *                             }
+     *                         ]
+     *                         files (Optional): [
+     *                              (Optional){
+     *                                 referenceKeyName: String (Optional)
+     *                                 generatedKeyName: String (Optional)
+     *                                 source: String (Optional)
+     *                                 sourceContext: String (Optional)
+     *                                 inputs (Optional): [
+     *                                     (recursive schema, see above)
+     *                                 ]
+     *                                 storageContainer: String (Required)
+     *                             }
+     *                         ]
+     *                     }
+     *                 ]
+     *                 identity (Optional): {
+     *                     @odata.type: String (Required)
+     *                 }
+     *                 parameters (Optional): {
+     *                     synthesizeGeneratedKeyName: Boolean (Optional)
+     *                      (Optional): {
+     *                         String: BinaryData (Required)
+     *                     }
+     *                 }
+     *             }
+     *             indexProjections (Optional): {
+     *                 selectors (Required): [
+     *                      (Required){
+     *                         targetIndexName: String (Required)
+     *                         parentKeyFieldName: String (Required)
+     *                         sourceContext: String (Required)
+     *                         mappings (Required): [
+     *                             (recursive schema, see above)
+     *                         ]
+     *                     }
+     *                 ]
+     *                 parameters (Optional): {
+     *                     projectionMode: String(skipIndexingParentDocuments/includeIndexingParentDocuments) (Optional)
+     *                      (Optional): {
+     *                         String: BinaryData (Required)
+     *                     }
+     *                 }
+     *             }
+     *             @odata.etag: String (Optional)
+     *             encryptionKey (Optional): {
+     *                 keyVaultKeyName: String (Required)
+     *                 keyVaultKeyVersion: String (Optional)
+     *                 keyVaultUri: String (Required)
+     *                 accessCredentials (Optional): {
+     *                     applicationId: String (Required)
+     *                     applicationSecret: String (Optional)
+     *                 }
+     *                 identity (Optional): (recursive schema, see identity above)
+     *             }
+     *         }
+     *     ]
+     * }
+     * }
+     * 
+ * + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return response from a list skillset request along with {@link Response} on successful completion of + * {@link Mono}. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono> listWithResponse(RequestOptions requestOptions) { + return this.serviceClient.listWithResponseAsync(requestOptions); + } + + /** + * Creates a new skillset in a search service. + *

Request Body Schema

+ * + *
+     * {@code
+     * {
+     *     name: String (Required)
+     *     description: String (Optional)
+     *     skills (Required): [
+     *          (Required){
+     *             @odata.type: String (Required)
+     *             name: String (Optional)
+     *             description: String (Optional)
+     *             context: String (Optional)
+     *             inputs (Required): [
+     *                  (Required){
+     *                     name: String (Required)
+     *                     source: String (Optional)
+     *                     sourceContext: String (Optional)
+     *                     inputs (Optional): [
+     *                         (recursive schema, see above)
+     *                     ]
+     *                 }
+     *             ]
+     *             outputs (Required): [
+     *                  (Required){
+     *                     name: String (Required)
+     *                     targetName: String (Optional)
+     *                 }
+     *             ]
+     *         }
+     *     ]
+     *     cognitiveServices (Optional): {
+     *         @odata.type: String (Required)
+     *         description: String (Optional)
+     *     }
+     *     knowledgeStore (Optional): {
+     *         storageConnectionString: String (Required)
+     *         projections (Required): [
+     *              (Required){
+     *                 tables (Optional): [
+     *                      (Optional){
+     *                         referenceKeyName: String (Optional)
+     *                         generatedKeyName: String (Optional)
+     *                         source: String (Optional)
+     *                         sourceContext: String (Optional)
+     *                         inputs (Optional): [
+     *                             (recursive schema, see above)
+     *                         ]
+     *                         tableName: String (Required)
+     *                     }
+     *                 ]
+     *                 objects (Optional): [
+     *                      (Optional){
+     *                         referenceKeyName: String (Optional)
+     *                         generatedKeyName: String (Optional)
+     *                         source: String (Optional)
+     *                         sourceContext: String (Optional)
+     *                         inputs (Optional): [
+     *                             (recursive schema, see above)
+     *                         ]
+     *                         storageContainer: String (Required)
+     *                     }
+     *                 ]
+     *                 files (Optional): [
+     *                      (Optional){
+     *                         referenceKeyName: String (Optional)
+     *                         generatedKeyName: String (Optional)
+     *                         source: String (Optional)
+     *                         sourceContext: String (Optional)
+     *                         inputs (Optional): [
+     *                             (recursive schema, see above)
+     *                         ]
+     *                         storageContainer: String (Required)
+     *                     }
+     *                 ]
+     *             }
+     *         ]
+     *         identity (Optional): {
+     *             @odata.type: String (Required)
+     *         }
+     *         parameters (Optional): {
+     *             synthesizeGeneratedKeyName: Boolean (Optional)
+     *              (Optional): {
+     *                 String: BinaryData (Required)
+     *             }
+     *         }
+     *     }
+     *     indexProjections (Optional): {
+     *         selectors (Required): [
+     *              (Required){
+     *                 targetIndexName: String (Required)
+     *                 parentKeyFieldName: String (Required)
+     *                 sourceContext: String (Required)
+     *                 mappings (Required): [
+     *                     (recursive schema, see above)
+     *                 ]
+     *             }
+     *         ]
+     *         parameters (Optional): {
+     *             projectionMode: String(skipIndexingParentDocuments/includeIndexingParentDocuments) (Optional)
+     *              (Optional): {
+     *                 String: BinaryData (Required)
+     *             }
+     *         }
+     *     }
+     *     @odata.etag: String (Optional)
+     *     encryptionKey (Optional): {
+     *         keyVaultKeyName: String (Required)
+     *         keyVaultKeyVersion: String (Optional)
+     *         keyVaultUri: String (Required)
+     *         accessCredentials (Optional): {
+     *             applicationId: String (Required)
+     *             applicationSecret: String (Optional)
+     *         }
+     *         identity (Optional): (recursive schema, see identity above)
+     *     }
+     * }
+     * }
+     * 
+ * + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     name: String (Required)
+     *     description: String (Optional)
+     *     skills (Required): [
+     *          (Required){
+     *             @odata.type: String (Required)
+     *             name: String (Optional)
+     *             description: String (Optional)
+     *             context: String (Optional)
+     *             inputs (Required): [
+     *                  (Required){
+     *                     name: String (Required)
+     *                     source: String (Optional)
+     *                     sourceContext: String (Optional)
+     *                     inputs (Optional): [
+     *                         (recursive schema, see above)
+     *                     ]
+     *                 }
+     *             ]
+     *             outputs (Required): [
+     *                  (Required){
+     *                     name: String (Required)
+     *                     targetName: String (Optional)
+     *                 }
+     *             ]
+     *         }
+     *     ]
+     *     cognitiveServices (Optional): {
+     *         @odata.type: String (Required)
+     *         description: String (Optional)
+     *     }
+     *     knowledgeStore (Optional): {
+     *         storageConnectionString: String (Required)
+     *         projections (Required): [
+     *              (Required){
+     *                 tables (Optional): [
+     *                      (Optional){
+     *                         referenceKeyName: String (Optional)
+     *                         generatedKeyName: String (Optional)
+     *                         source: String (Optional)
+     *                         sourceContext: String (Optional)
+     *                         inputs (Optional): [
+     *                             (recursive schema, see above)
+     *                         ]
+     *                         tableName: String (Required)
+     *                     }
+     *                 ]
+     *                 objects (Optional): [
+     *                      (Optional){
+     *                         referenceKeyName: String (Optional)
+     *                         generatedKeyName: String (Optional)
+     *                         source: String (Optional)
+     *                         sourceContext: String (Optional)
+     *                         inputs (Optional): [
+     *                             (recursive schema, see above)
+     *                         ]
+     *                         storageContainer: String (Required)
+     *                     }
+     *                 ]
+     *                 files (Optional): [
+     *                      (Optional){
+     *                         referenceKeyName: String (Optional)
+     *                         generatedKeyName: String (Optional)
+     *                         source: String (Optional)
+     *                         sourceContext: String (Optional)
+     *                         inputs (Optional): [
+     *                             (recursive schema, see above)
+     *                         ]
+     *                         storageContainer: String (Required)
+     *                     }
+     *                 ]
+     *             }
+     *         ]
+     *         identity (Optional): {
+     *             @odata.type: String (Required)
+     *         }
+     *         parameters (Optional): {
+     *             synthesizeGeneratedKeyName: Boolean (Optional)
+     *              (Optional): {
+     *                 String: BinaryData (Required)
+     *             }
+     *         }
+     *     }
+     *     indexProjections (Optional): {
+     *         selectors (Required): [
+     *              (Required){
+     *                 targetIndexName: String (Required)
+     *                 parentKeyFieldName: String (Required)
+     *                 sourceContext: String (Required)
+     *                 mappings (Required): [
+     *                     (recursive schema, see above)
+     *                 ]
+     *             }
+     *         ]
+     *         parameters (Optional): {
+     *             projectionMode: String(skipIndexingParentDocuments/includeIndexingParentDocuments) (Optional)
+     *              (Optional): {
+     *                 String: BinaryData (Required)
+     *             }
+     *         }
+     *     }
+     *     @odata.etag: String (Optional)
+     *     encryptionKey (Optional): {
+     *         keyVaultKeyName: String (Required)
+     *         keyVaultKeyVersion: String (Optional)
+     *         keyVaultUri: String (Required)
+     *         accessCredentials (Optional): {
+     *             applicationId: String (Required)
+     *             applicationSecret: String (Optional)
+     *         }
+     *         identity (Optional): (recursive schema, see identity above)
+     *     }
+     * }
+     * }
+     * 
+ * + * @param skillset The skillset containing one or more skills to create in a search service. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return a list of skills along with {@link Response} on successful completion of {@link Mono}. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono> createWithResponse(BinaryData skillset, RequestOptions requestOptions) { + return this.serviceClient.createWithResponseAsync(skillset, requestOptions); + } + + /** + * Reset an existing skillset in a search service. + *

Request Body Schema

+ * + *
+     * {@code
+     * {
+     *     skillNames (Optional): [
+     *         String (Optional)
+     *     ]
+     * }
+     * }
+     * 
+ * + * @param skillsetName The name of the skillset. + * @param skillNames The names of the skills to reset. If not specified, all skills in the skillset + * will be reset. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return the {@link Response} on successful completion of {@link Mono}. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono> resetSkillsWithResponse(String skillsetName, BinaryData skillNames, + RequestOptions requestOptions) { + return this.serviceClient.resetSkillsWithResponseAsync(skillsetName, skillNames, requestOptions); + } + + /** + * Creates a new skillset in a search service or updates the skillset if it + * already exists. + * + * @param skillsetName The name of the skillset. + * @param skillset The skillset containing one or more skills to create or update in a search + * service. + * @param skipIndexerResetRequirementForCache Ignores cache reset requirements. + * @param disableCacheReprocessingChangeDetection Disables cache reprocessing change detection. + * @param matchConditions Specifies HTTP options for conditional requests. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a list of skills on successful completion of {@link Mono}. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono createOrUpdate(String skillsetName, SearchIndexerSkillset skillset, + Boolean skipIndexerResetRequirementForCache, Boolean disableCacheReprocessingChangeDetection, + MatchConditions matchConditions) { + // Generated convenience method for createOrUpdateWithResponse + RequestOptions requestOptions = new RequestOptions(); + String ifMatch = matchConditions == null ? null : matchConditions.getIfMatch(); + String ifNoneMatch = matchConditions == null ? null : matchConditions.getIfNoneMatch(); + if (skipIndexerResetRequirementForCache != null) { + requestOptions.addQueryParam("ignoreResetRequirements", String.valueOf(skipIndexerResetRequirementForCache), + false); + } + if (disableCacheReprocessingChangeDetection != null) { + requestOptions.addQueryParam("disableCacheReprocessingChangeDetection", + String.valueOf(disableCacheReprocessingChangeDetection), false); + } + if (ifMatch != null) { + requestOptions.setHeader(HttpHeaderName.IF_MATCH, ifMatch); + } + if (ifNoneMatch != null) { + requestOptions.setHeader(HttpHeaderName.IF_NONE_MATCH, ifNoneMatch); + } + return createOrUpdateWithResponse(skillsetName, BinaryData.fromObject(skillset), requestOptions) + .flatMap(FluxUtil::toMono) + .map(protocolMethodData -> protocolMethodData.toObject(SearchIndexerSkillset.class)); + } + + /** + * Creates a new skillset in a search service or updates the skillset if it + * already exists. + * + * @param skillsetName The name of the skillset. + * @param skillset The skillset containing one or more skills to create or update in a search + * service. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a list of skills on successful completion of {@link Mono}. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono createOrUpdate(String skillsetName, SearchIndexerSkillset skillset) { + // Generated convenience method for createOrUpdateWithResponse + RequestOptions requestOptions = new RequestOptions(); + return createOrUpdateWithResponse(skillsetName, BinaryData.fromObject(skillset), requestOptions) + .flatMap(FluxUtil::toMono) + .map(protocolMethodData -> protocolMethodData.toObject(SearchIndexerSkillset.class)); + } + + /** + * Deletes a skillset in a search service. + * + * @param skillsetName The name of the skillset. + * @param matchConditions Specifies HTTP options for conditional requests. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return A {@link Mono} that completes when a successful response is received. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono delete(String skillsetName, MatchConditions matchConditions) { + // Generated convenience method for deleteWithResponse + RequestOptions requestOptions = new RequestOptions(); + String ifMatch = matchConditions == null ? null : matchConditions.getIfMatch(); + String ifNoneMatch = matchConditions == null ? null : matchConditions.getIfNoneMatch(); + if (ifMatch != null) { + requestOptions.setHeader(HttpHeaderName.IF_MATCH, ifMatch); + } + if (ifNoneMatch != null) { + requestOptions.setHeader(HttpHeaderName.IF_NONE_MATCH, ifNoneMatch); + } + return deleteWithResponse(skillsetName, requestOptions).flatMap(FluxUtil::toMono); + } + + /** + * Deletes a skillset in a search service. + * + * @param skillsetName The name of the skillset. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return A {@link Mono} that completes when a successful response is received. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono delete(String skillsetName) { + // Generated convenience method for deleteWithResponse + RequestOptions requestOptions = new RequestOptions(); + return deleteWithResponse(skillsetName, requestOptions).flatMap(FluxUtil::toMono); + } + + /** + * Retrieves a skillset in a search service. + * + * @param skillsetName The name of the skillset. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a list of skills on successful completion of {@link Mono}. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono get(String skillsetName) { + // Generated convenience method for getWithResponse + RequestOptions requestOptions = new RequestOptions(); + return getWithResponse(skillsetName, requestOptions).flatMap(FluxUtil::toMono) + .map(protocolMethodData -> protocolMethodData.toObject(SearchIndexerSkillset.class)); + } + + /** + * List all skillsets in a search service. + * + * @param 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. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return response from a list skillset request on successful completion of {@link Mono}. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono list(String select) { + // Generated convenience method for listWithResponse + RequestOptions requestOptions = new RequestOptions(); + if (select != null) { + requestOptions.addQueryParam("$select", select, false); + } + return listWithResponse(requestOptions).flatMap(FluxUtil::toMono) + .map(protocolMethodData -> protocolMethodData.toObject(ListSkillsetsResult.class)); + } + + /** + * List all skillsets in a search service. + * + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return response from a list skillset request on successful completion of {@link Mono}. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono list() { + // Generated convenience method for listWithResponse + RequestOptions requestOptions = new RequestOptions(); + return listWithResponse(requestOptions).flatMap(FluxUtil::toMono) + .map(protocolMethodData -> protocolMethodData.toObject(ListSkillsetsResult.class)); + } + + /** + * Creates a new skillset in a search service. + * + * @param skillset The skillset containing one or more skills to create in a search service. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a list of skills on successful completion of {@link Mono}. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono create(SearchIndexerSkillset skillset) { + // Generated convenience method for createWithResponse + RequestOptions requestOptions = new RequestOptions(); + return createWithResponse(BinaryData.fromObject(skillset), requestOptions).flatMap(FluxUtil::toMono) + .map(protocolMethodData -> protocolMethodData.toObject(SearchIndexerSkillset.class)); + } + + /** + * Reset an existing skillset in a search service. + * + * @param skillsetName The name of the skillset. + * @param skillNames The names of the skills to reset. If not specified, all skills in the skillset + * will be reset. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return A {@link Mono} that completes when a successful response is received. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono resetSkills(String skillsetName, SkillNames skillNames) { + // Generated convenience method for resetSkillsWithResponse + RequestOptions requestOptions = new RequestOptions(); + return resetSkillsWithResponse(skillsetName, BinaryData.fromObject(skillNames), requestOptions) + .flatMap(FluxUtil::toMono); + } +} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/SkillsetsClient.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/SkillsetsClient.java new file mode 100644 index 000000000000..abeb55bed63f --- /dev/null +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/SkillsetsClient.java @@ -0,0 +1,1137 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.search.documents; + +import com.azure.core.annotation.Generated; +import com.azure.core.annotation.ReturnType; +import com.azure.core.annotation.ServiceClient; +import com.azure.core.annotation.ServiceMethod; +import com.azure.core.exception.ClientAuthenticationException; +import com.azure.core.exception.HttpResponseException; +import com.azure.core.exception.ResourceModifiedException; +import com.azure.core.exception.ResourceNotFoundException; +import com.azure.core.http.HttpHeaderName; +import com.azure.core.http.MatchConditions; +import com.azure.core.http.rest.RequestOptions; +import com.azure.core.http.rest.Response; +import com.azure.core.util.BinaryData; +import com.azure.search.documents.implementation.SkillsetsImpl; +import com.azure.search.documents.models.ListSkillsetsResult; +import com.azure.search.documents.models.SearchIndexerSkillset; +import com.azure.search.documents.models.SkillNames; + +/** + * Initializes a new instance of the synchronous SearchClient type. + */ +@ServiceClient(builder = SearchClientBuilder.class) +public final class SkillsetsClient { + @Generated + private final SkillsetsImpl serviceClient; + + /** + * Initializes an instance of SkillsetsClient class. + * + * @param serviceClient the service client implementation. + */ + @Generated + SkillsetsClient(SkillsetsImpl serviceClient) { + this.serviceClient = serviceClient; + } + + /** + * Creates a new skillset in a search service or updates the skillset if it + * already exists. + *

Query Parameters

+ * + * + * + * + * + *
Query Parameters
NameTypeRequiredDescription
ignoreResetRequirementsBooleanNoIgnores cache reset requirements.
disableCacheReprocessingChangeDetectionBooleanNoDisables cache reprocessing + * change detection.
+ * You can add these to a request with {@link RequestOptions#addQueryParam} + *

Header Parameters

+ * + * + * + * + * + *
Header Parameters
NameTypeRequiredDescription
If-MatchStringNoDefines the If-Match condition. The operation will be + * performed only if the ETag on the server matches this value.
If-None-MatchStringNoDefines the If-None-Match condition. The operation will + * be performed only if the ETag on the server does not match this value.
+ * You can add these to a request with {@link RequestOptions#addHeader} + *

Request Body Schema

+ * + *
+     * {@code
+     * {
+     *     name: String (Required)
+     *     description: String (Optional)
+     *     skills (Required): [
+     *          (Required){
+     *             @odata.type: String (Required)
+     *             name: String (Optional)
+     *             description: String (Optional)
+     *             context: String (Optional)
+     *             inputs (Required): [
+     *                  (Required){
+     *                     name: String (Required)
+     *                     source: String (Optional)
+     *                     sourceContext: String (Optional)
+     *                     inputs (Optional): [
+     *                         (recursive schema, see above)
+     *                     ]
+     *                 }
+     *             ]
+     *             outputs (Required): [
+     *                  (Required){
+     *                     name: String (Required)
+     *                     targetName: String (Optional)
+     *                 }
+     *             ]
+     *         }
+     *     ]
+     *     cognitiveServices (Optional): {
+     *         @odata.type: String (Required)
+     *         description: String (Optional)
+     *     }
+     *     knowledgeStore (Optional): {
+     *         storageConnectionString: String (Required)
+     *         projections (Required): [
+     *              (Required){
+     *                 tables (Optional): [
+     *                      (Optional){
+     *                         referenceKeyName: String (Optional)
+     *                         generatedKeyName: String (Optional)
+     *                         source: String (Optional)
+     *                         sourceContext: String (Optional)
+     *                         inputs (Optional): [
+     *                             (recursive schema, see above)
+     *                         ]
+     *                         tableName: String (Required)
+     *                     }
+     *                 ]
+     *                 objects (Optional): [
+     *                      (Optional){
+     *                         referenceKeyName: String (Optional)
+     *                         generatedKeyName: String (Optional)
+     *                         source: String (Optional)
+     *                         sourceContext: String (Optional)
+     *                         inputs (Optional): [
+     *                             (recursive schema, see above)
+     *                         ]
+     *                         storageContainer: String (Required)
+     *                     }
+     *                 ]
+     *                 files (Optional): [
+     *                      (Optional){
+     *                         referenceKeyName: String (Optional)
+     *                         generatedKeyName: String (Optional)
+     *                         source: String (Optional)
+     *                         sourceContext: String (Optional)
+     *                         inputs (Optional): [
+     *                             (recursive schema, see above)
+     *                         ]
+     *                         storageContainer: String (Required)
+     *                     }
+     *                 ]
+     *             }
+     *         ]
+     *         identity (Optional): {
+     *             @odata.type: String (Required)
+     *         }
+     *         parameters (Optional): {
+     *             synthesizeGeneratedKeyName: Boolean (Optional)
+     *              (Optional): {
+     *                 String: BinaryData (Required)
+     *             }
+     *         }
+     *     }
+     *     indexProjections (Optional): {
+     *         selectors (Required): [
+     *              (Required){
+     *                 targetIndexName: String (Required)
+     *                 parentKeyFieldName: String (Required)
+     *                 sourceContext: String (Required)
+     *                 mappings (Required): [
+     *                     (recursive schema, see above)
+     *                 ]
+     *             }
+     *         ]
+     *         parameters (Optional): {
+     *             projectionMode: String(skipIndexingParentDocuments/includeIndexingParentDocuments) (Optional)
+     *              (Optional): {
+     *                 String: BinaryData (Required)
+     *             }
+     *         }
+     *     }
+     *     @odata.etag: String (Optional)
+     *     encryptionKey (Optional): {
+     *         keyVaultKeyName: String (Required)
+     *         keyVaultKeyVersion: String (Optional)
+     *         keyVaultUri: String (Required)
+     *         accessCredentials (Optional): {
+     *             applicationId: String (Required)
+     *             applicationSecret: String (Optional)
+     *         }
+     *         identity (Optional): (recursive schema, see identity above)
+     *     }
+     * }
+     * }
+     * 
+ * + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     name: String (Required)
+     *     description: String (Optional)
+     *     skills (Required): [
+     *          (Required){
+     *             @odata.type: String (Required)
+     *             name: String (Optional)
+     *             description: String (Optional)
+     *             context: String (Optional)
+     *             inputs (Required): [
+     *                  (Required){
+     *                     name: String (Required)
+     *                     source: String (Optional)
+     *                     sourceContext: String (Optional)
+     *                     inputs (Optional): [
+     *                         (recursive schema, see above)
+     *                     ]
+     *                 }
+     *             ]
+     *             outputs (Required): [
+     *                  (Required){
+     *                     name: String (Required)
+     *                     targetName: String (Optional)
+     *                 }
+     *             ]
+     *         }
+     *     ]
+     *     cognitiveServices (Optional): {
+     *         @odata.type: String (Required)
+     *         description: String (Optional)
+     *     }
+     *     knowledgeStore (Optional): {
+     *         storageConnectionString: String (Required)
+     *         projections (Required): [
+     *              (Required){
+     *                 tables (Optional): [
+     *                      (Optional){
+     *                         referenceKeyName: String (Optional)
+     *                         generatedKeyName: String (Optional)
+     *                         source: String (Optional)
+     *                         sourceContext: String (Optional)
+     *                         inputs (Optional): [
+     *                             (recursive schema, see above)
+     *                         ]
+     *                         tableName: String (Required)
+     *                     }
+     *                 ]
+     *                 objects (Optional): [
+     *                      (Optional){
+     *                         referenceKeyName: String (Optional)
+     *                         generatedKeyName: String (Optional)
+     *                         source: String (Optional)
+     *                         sourceContext: String (Optional)
+     *                         inputs (Optional): [
+     *                             (recursive schema, see above)
+     *                         ]
+     *                         storageContainer: String (Required)
+     *                     }
+     *                 ]
+     *                 files (Optional): [
+     *                      (Optional){
+     *                         referenceKeyName: String (Optional)
+     *                         generatedKeyName: String (Optional)
+     *                         source: String (Optional)
+     *                         sourceContext: String (Optional)
+     *                         inputs (Optional): [
+     *                             (recursive schema, see above)
+     *                         ]
+     *                         storageContainer: String (Required)
+     *                     }
+     *                 ]
+     *             }
+     *         ]
+     *         identity (Optional): {
+     *             @odata.type: String (Required)
+     *         }
+     *         parameters (Optional): {
+     *             synthesizeGeneratedKeyName: Boolean (Optional)
+     *              (Optional): {
+     *                 String: BinaryData (Required)
+     *             }
+     *         }
+     *     }
+     *     indexProjections (Optional): {
+     *         selectors (Required): [
+     *              (Required){
+     *                 targetIndexName: String (Required)
+     *                 parentKeyFieldName: String (Required)
+     *                 sourceContext: String (Required)
+     *                 mappings (Required): [
+     *                     (recursive schema, see above)
+     *                 ]
+     *             }
+     *         ]
+     *         parameters (Optional): {
+     *             projectionMode: String(skipIndexingParentDocuments/includeIndexingParentDocuments) (Optional)
+     *              (Optional): {
+     *                 String: BinaryData (Required)
+     *             }
+     *         }
+     *     }
+     *     @odata.etag: String (Optional)
+     *     encryptionKey (Optional): {
+     *         keyVaultKeyName: String (Required)
+     *         keyVaultKeyVersion: String (Optional)
+     *         keyVaultUri: String (Required)
+     *         accessCredentials (Optional): {
+     *             applicationId: String (Required)
+     *             applicationSecret: String (Optional)
+     *         }
+     *         identity (Optional): (recursive schema, see identity above)
+     *     }
+     * }
+     * }
+     * 
+ * + * @param skillsetName The name of the skillset. + * @param skillset The skillset containing one or more skills to create or update in a search + * service. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return a list of skills along with {@link Response}. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public Response createOrUpdateWithResponse(String skillsetName, BinaryData skillset, + RequestOptions requestOptions) { + return this.serviceClient.createOrUpdateWithResponse(skillsetName, skillset, requestOptions); + } + + /** + * Deletes a skillset in a search service. + *

Header Parameters

+ * + * + * + * + * + *
Header Parameters
NameTypeRequiredDescription
If-MatchStringNoDefines the If-Match condition. The operation will be + * performed only if the ETag on the server matches this value.
If-None-MatchStringNoDefines the If-None-Match condition. The operation will + * be performed only if the ETag on the server does not match this value.
+ * You can add these to a request with {@link RequestOptions#addHeader} + * + * @param skillsetName The name of the skillset. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return the {@link Response}. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public Response deleteWithResponse(String skillsetName, RequestOptions requestOptions) { + return this.serviceClient.deleteWithResponse(skillsetName, requestOptions); + } + + /** + * Retrieves a skillset in a search service. + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     name: String (Required)
+     *     description: String (Optional)
+     *     skills (Required): [
+     *          (Required){
+     *             @odata.type: String (Required)
+     *             name: String (Optional)
+     *             description: String (Optional)
+     *             context: String (Optional)
+     *             inputs (Required): [
+     *                  (Required){
+     *                     name: String (Required)
+     *                     source: String (Optional)
+     *                     sourceContext: String (Optional)
+     *                     inputs (Optional): [
+     *                         (recursive schema, see above)
+     *                     ]
+     *                 }
+     *             ]
+     *             outputs (Required): [
+     *                  (Required){
+     *                     name: String (Required)
+     *                     targetName: String (Optional)
+     *                 }
+     *             ]
+     *         }
+     *     ]
+     *     cognitiveServices (Optional): {
+     *         @odata.type: String (Required)
+     *         description: String (Optional)
+     *     }
+     *     knowledgeStore (Optional): {
+     *         storageConnectionString: String (Required)
+     *         projections (Required): [
+     *              (Required){
+     *                 tables (Optional): [
+     *                      (Optional){
+     *                         referenceKeyName: String (Optional)
+     *                         generatedKeyName: String (Optional)
+     *                         source: String (Optional)
+     *                         sourceContext: String (Optional)
+     *                         inputs (Optional): [
+     *                             (recursive schema, see above)
+     *                         ]
+     *                         tableName: String (Required)
+     *                     }
+     *                 ]
+     *                 objects (Optional): [
+     *                      (Optional){
+     *                         referenceKeyName: String (Optional)
+     *                         generatedKeyName: String (Optional)
+     *                         source: String (Optional)
+     *                         sourceContext: String (Optional)
+     *                         inputs (Optional): [
+     *                             (recursive schema, see above)
+     *                         ]
+     *                         storageContainer: String (Required)
+     *                     }
+     *                 ]
+     *                 files (Optional): [
+     *                      (Optional){
+     *                         referenceKeyName: String (Optional)
+     *                         generatedKeyName: String (Optional)
+     *                         source: String (Optional)
+     *                         sourceContext: String (Optional)
+     *                         inputs (Optional): [
+     *                             (recursive schema, see above)
+     *                         ]
+     *                         storageContainer: String (Required)
+     *                     }
+     *                 ]
+     *             }
+     *         ]
+     *         identity (Optional): {
+     *             @odata.type: String (Required)
+     *         }
+     *         parameters (Optional): {
+     *             synthesizeGeneratedKeyName: Boolean (Optional)
+     *              (Optional): {
+     *                 String: BinaryData (Required)
+     *             }
+     *         }
+     *     }
+     *     indexProjections (Optional): {
+     *         selectors (Required): [
+     *              (Required){
+     *                 targetIndexName: String (Required)
+     *                 parentKeyFieldName: String (Required)
+     *                 sourceContext: String (Required)
+     *                 mappings (Required): [
+     *                     (recursive schema, see above)
+     *                 ]
+     *             }
+     *         ]
+     *         parameters (Optional): {
+     *             projectionMode: String(skipIndexingParentDocuments/includeIndexingParentDocuments) (Optional)
+     *              (Optional): {
+     *                 String: BinaryData (Required)
+     *             }
+     *         }
+     *     }
+     *     @odata.etag: String (Optional)
+     *     encryptionKey (Optional): {
+     *         keyVaultKeyName: String (Required)
+     *         keyVaultKeyVersion: String (Optional)
+     *         keyVaultUri: String (Required)
+     *         accessCredentials (Optional): {
+     *             applicationId: String (Required)
+     *             applicationSecret: String (Optional)
+     *         }
+     *         identity (Optional): (recursive schema, see identity above)
+     *     }
+     * }
+     * }
+     * 
+ * + * @param skillsetName The name of the skillset. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return a list of skills along with {@link Response}. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public Response getWithResponse(String skillsetName, RequestOptions requestOptions) { + return this.serviceClient.getWithResponse(skillsetName, requestOptions); + } + + /** + * List all skillsets in a search service. + *

Query Parameters

+ * + * + * + * + *
Query Parameters
NameTypeRequiredDescription
$selectStringNoSelects 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.
+ * You can add these to a request with {@link RequestOptions#addQueryParam} + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     value (Required): [
+     *          (Required){
+     *             name: String (Required)
+     *             description: String (Optional)
+     *             skills (Required): [
+     *                  (Required){
+     *                     @odata.type: String (Required)
+     *                     name: String (Optional)
+     *                     description: String (Optional)
+     *                     context: String (Optional)
+     *                     inputs (Required): [
+     *                          (Required){
+     *                             name: String (Required)
+     *                             source: String (Optional)
+     *                             sourceContext: String (Optional)
+     *                             inputs (Optional): [
+     *                                 (recursive schema, see above)
+     *                             ]
+     *                         }
+     *                     ]
+     *                     outputs (Required): [
+     *                          (Required){
+     *                             name: String (Required)
+     *                             targetName: String (Optional)
+     *                         }
+     *                     ]
+     *                 }
+     *             ]
+     *             cognitiveServices (Optional): {
+     *                 @odata.type: String (Required)
+     *                 description: String (Optional)
+     *             }
+     *             knowledgeStore (Optional): {
+     *                 storageConnectionString: String (Required)
+     *                 projections (Required): [
+     *                      (Required){
+     *                         tables (Optional): [
+     *                              (Optional){
+     *                                 referenceKeyName: String (Optional)
+     *                                 generatedKeyName: String (Optional)
+     *                                 source: String (Optional)
+     *                                 sourceContext: String (Optional)
+     *                                 inputs (Optional): [
+     *                                     (recursive schema, see above)
+     *                                 ]
+     *                                 tableName: String (Required)
+     *                             }
+     *                         ]
+     *                         objects (Optional): [
+     *                              (Optional){
+     *                                 referenceKeyName: String (Optional)
+     *                                 generatedKeyName: String (Optional)
+     *                                 source: String (Optional)
+     *                                 sourceContext: String (Optional)
+     *                                 inputs (Optional): [
+     *                                     (recursive schema, see above)
+     *                                 ]
+     *                                 storageContainer: String (Required)
+     *                             }
+     *                         ]
+     *                         files (Optional): [
+     *                              (Optional){
+     *                                 referenceKeyName: String (Optional)
+     *                                 generatedKeyName: String (Optional)
+     *                                 source: String (Optional)
+     *                                 sourceContext: String (Optional)
+     *                                 inputs (Optional): [
+     *                                     (recursive schema, see above)
+     *                                 ]
+     *                                 storageContainer: String (Required)
+     *                             }
+     *                         ]
+     *                     }
+     *                 ]
+     *                 identity (Optional): {
+     *                     @odata.type: String (Required)
+     *                 }
+     *                 parameters (Optional): {
+     *                     synthesizeGeneratedKeyName: Boolean (Optional)
+     *                      (Optional): {
+     *                         String: BinaryData (Required)
+     *                     }
+     *                 }
+     *             }
+     *             indexProjections (Optional): {
+     *                 selectors (Required): [
+     *                      (Required){
+     *                         targetIndexName: String (Required)
+     *                         parentKeyFieldName: String (Required)
+     *                         sourceContext: String (Required)
+     *                         mappings (Required): [
+     *                             (recursive schema, see above)
+     *                         ]
+     *                     }
+     *                 ]
+     *                 parameters (Optional): {
+     *                     projectionMode: String(skipIndexingParentDocuments/includeIndexingParentDocuments) (Optional)
+     *                      (Optional): {
+     *                         String: BinaryData (Required)
+     *                     }
+     *                 }
+     *             }
+     *             @odata.etag: String (Optional)
+     *             encryptionKey (Optional): {
+     *                 keyVaultKeyName: String (Required)
+     *                 keyVaultKeyVersion: String (Optional)
+     *                 keyVaultUri: String (Required)
+     *                 accessCredentials (Optional): {
+     *                     applicationId: String (Required)
+     *                     applicationSecret: String (Optional)
+     *                 }
+     *                 identity (Optional): (recursive schema, see identity above)
+     *             }
+     *         }
+     *     ]
+     * }
+     * }
+     * 
+ * + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return response from a list skillset request along with {@link Response}. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public Response listWithResponse(RequestOptions requestOptions) { + return this.serviceClient.listWithResponse(requestOptions); + } + + /** + * Creates a new skillset in a search service. + *

Request Body Schema

+ * + *
+     * {@code
+     * {
+     *     name: String (Required)
+     *     description: String (Optional)
+     *     skills (Required): [
+     *          (Required){
+     *             @odata.type: String (Required)
+     *             name: String (Optional)
+     *             description: String (Optional)
+     *             context: String (Optional)
+     *             inputs (Required): [
+     *                  (Required){
+     *                     name: String (Required)
+     *                     source: String (Optional)
+     *                     sourceContext: String (Optional)
+     *                     inputs (Optional): [
+     *                         (recursive schema, see above)
+     *                     ]
+     *                 }
+     *             ]
+     *             outputs (Required): [
+     *                  (Required){
+     *                     name: String (Required)
+     *                     targetName: String (Optional)
+     *                 }
+     *             ]
+     *         }
+     *     ]
+     *     cognitiveServices (Optional): {
+     *         @odata.type: String (Required)
+     *         description: String (Optional)
+     *     }
+     *     knowledgeStore (Optional): {
+     *         storageConnectionString: String (Required)
+     *         projections (Required): [
+     *              (Required){
+     *                 tables (Optional): [
+     *                      (Optional){
+     *                         referenceKeyName: String (Optional)
+     *                         generatedKeyName: String (Optional)
+     *                         source: String (Optional)
+     *                         sourceContext: String (Optional)
+     *                         inputs (Optional): [
+     *                             (recursive schema, see above)
+     *                         ]
+     *                         tableName: String (Required)
+     *                     }
+     *                 ]
+     *                 objects (Optional): [
+     *                      (Optional){
+     *                         referenceKeyName: String (Optional)
+     *                         generatedKeyName: String (Optional)
+     *                         source: String (Optional)
+     *                         sourceContext: String (Optional)
+     *                         inputs (Optional): [
+     *                             (recursive schema, see above)
+     *                         ]
+     *                         storageContainer: String (Required)
+     *                     }
+     *                 ]
+     *                 files (Optional): [
+     *                      (Optional){
+     *                         referenceKeyName: String (Optional)
+     *                         generatedKeyName: String (Optional)
+     *                         source: String (Optional)
+     *                         sourceContext: String (Optional)
+     *                         inputs (Optional): [
+     *                             (recursive schema, see above)
+     *                         ]
+     *                         storageContainer: String (Required)
+     *                     }
+     *                 ]
+     *             }
+     *         ]
+     *         identity (Optional): {
+     *             @odata.type: String (Required)
+     *         }
+     *         parameters (Optional): {
+     *             synthesizeGeneratedKeyName: Boolean (Optional)
+     *              (Optional): {
+     *                 String: BinaryData (Required)
+     *             }
+     *         }
+     *     }
+     *     indexProjections (Optional): {
+     *         selectors (Required): [
+     *              (Required){
+     *                 targetIndexName: String (Required)
+     *                 parentKeyFieldName: String (Required)
+     *                 sourceContext: String (Required)
+     *                 mappings (Required): [
+     *                     (recursive schema, see above)
+     *                 ]
+     *             }
+     *         ]
+     *         parameters (Optional): {
+     *             projectionMode: String(skipIndexingParentDocuments/includeIndexingParentDocuments) (Optional)
+     *              (Optional): {
+     *                 String: BinaryData (Required)
+     *             }
+     *         }
+     *     }
+     *     @odata.etag: String (Optional)
+     *     encryptionKey (Optional): {
+     *         keyVaultKeyName: String (Required)
+     *         keyVaultKeyVersion: String (Optional)
+     *         keyVaultUri: String (Required)
+     *         accessCredentials (Optional): {
+     *             applicationId: String (Required)
+     *             applicationSecret: String (Optional)
+     *         }
+     *         identity (Optional): (recursive schema, see identity above)
+     *     }
+     * }
+     * }
+     * 
+ * + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     name: String (Required)
+     *     description: String (Optional)
+     *     skills (Required): [
+     *          (Required){
+     *             @odata.type: String (Required)
+     *             name: String (Optional)
+     *             description: String (Optional)
+     *             context: String (Optional)
+     *             inputs (Required): [
+     *                  (Required){
+     *                     name: String (Required)
+     *                     source: String (Optional)
+     *                     sourceContext: String (Optional)
+     *                     inputs (Optional): [
+     *                         (recursive schema, see above)
+     *                     ]
+     *                 }
+     *             ]
+     *             outputs (Required): [
+     *                  (Required){
+     *                     name: String (Required)
+     *                     targetName: String (Optional)
+     *                 }
+     *             ]
+     *         }
+     *     ]
+     *     cognitiveServices (Optional): {
+     *         @odata.type: String (Required)
+     *         description: String (Optional)
+     *     }
+     *     knowledgeStore (Optional): {
+     *         storageConnectionString: String (Required)
+     *         projections (Required): [
+     *              (Required){
+     *                 tables (Optional): [
+     *                      (Optional){
+     *                         referenceKeyName: String (Optional)
+     *                         generatedKeyName: String (Optional)
+     *                         source: String (Optional)
+     *                         sourceContext: String (Optional)
+     *                         inputs (Optional): [
+     *                             (recursive schema, see above)
+     *                         ]
+     *                         tableName: String (Required)
+     *                     }
+     *                 ]
+     *                 objects (Optional): [
+     *                      (Optional){
+     *                         referenceKeyName: String (Optional)
+     *                         generatedKeyName: String (Optional)
+     *                         source: String (Optional)
+     *                         sourceContext: String (Optional)
+     *                         inputs (Optional): [
+     *                             (recursive schema, see above)
+     *                         ]
+     *                         storageContainer: String (Required)
+     *                     }
+     *                 ]
+     *                 files (Optional): [
+     *                      (Optional){
+     *                         referenceKeyName: String (Optional)
+     *                         generatedKeyName: String (Optional)
+     *                         source: String (Optional)
+     *                         sourceContext: String (Optional)
+     *                         inputs (Optional): [
+     *                             (recursive schema, see above)
+     *                         ]
+     *                         storageContainer: String (Required)
+     *                     }
+     *                 ]
+     *             }
+     *         ]
+     *         identity (Optional): {
+     *             @odata.type: String (Required)
+     *         }
+     *         parameters (Optional): {
+     *             synthesizeGeneratedKeyName: Boolean (Optional)
+     *              (Optional): {
+     *                 String: BinaryData (Required)
+     *             }
+     *         }
+     *     }
+     *     indexProjections (Optional): {
+     *         selectors (Required): [
+     *              (Required){
+     *                 targetIndexName: String (Required)
+     *                 parentKeyFieldName: String (Required)
+     *                 sourceContext: String (Required)
+     *                 mappings (Required): [
+     *                     (recursive schema, see above)
+     *                 ]
+     *             }
+     *         ]
+     *         parameters (Optional): {
+     *             projectionMode: String(skipIndexingParentDocuments/includeIndexingParentDocuments) (Optional)
+     *              (Optional): {
+     *                 String: BinaryData (Required)
+     *             }
+     *         }
+     *     }
+     *     @odata.etag: String (Optional)
+     *     encryptionKey (Optional): {
+     *         keyVaultKeyName: String (Required)
+     *         keyVaultKeyVersion: String (Optional)
+     *         keyVaultUri: String (Required)
+     *         accessCredentials (Optional): {
+     *             applicationId: String (Required)
+     *             applicationSecret: String (Optional)
+     *         }
+     *         identity (Optional): (recursive schema, see identity above)
+     *     }
+     * }
+     * }
+     * 
+ * + * @param skillset The skillset containing one or more skills to create in a search service. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return a list of skills along with {@link Response}. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public Response createWithResponse(BinaryData skillset, RequestOptions requestOptions) { + return this.serviceClient.createWithResponse(skillset, requestOptions); + } + + /** + * Reset an existing skillset in a search service. + *

Request Body Schema

+ * + *
+     * {@code
+     * {
+     *     skillNames (Optional): [
+     *         String (Optional)
+     *     ]
+     * }
+     * }
+     * 
+ * + * @param skillsetName The name of the skillset. + * @param skillNames The names of the skills to reset. If not specified, all skills in the skillset + * will be reset. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return the {@link Response}. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public Response resetSkillsWithResponse(String skillsetName, BinaryData skillNames, + RequestOptions requestOptions) { + return this.serviceClient.resetSkillsWithResponse(skillsetName, skillNames, requestOptions); + } + + /** + * Creates a new skillset in a search service or updates the skillset if it + * already exists. + * + * @param skillsetName The name of the skillset. + * @param skillset The skillset containing one or more skills to create or update in a search + * service. + * @param skipIndexerResetRequirementForCache Ignores cache reset requirements. + * @param disableCacheReprocessingChangeDetection Disables cache reprocessing change detection. + * @param matchConditions Specifies HTTP options for conditional requests. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a list of skills. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public SearchIndexerSkillset createOrUpdate(String skillsetName, SearchIndexerSkillset skillset, + Boolean skipIndexerResetRequirementForCache, Boolean disableCacheReprocessingChangeDetection, + MatchConditions matchConditions) { + // Generated convenience method for createOrUpdateWithResponse + RequestOptions requestOptions = new RequestOptions(); + String ifMatch = matchConditions == null ? null : matchConditions.getIfMatch(); + String ifNoneMatch = matchConditions == null ? null : matchConditions.getIfNoneMatch(); + if (skipIndexerResetRequirementForCache != null) { + requestOptions.addQueryParam("ignoreResetRequirements", String.valueOf(skipIndexerResetRequirementForCache), + false); + } + if (disableCacheReprocessingChangeDetection != null) { + requestOptions.addQueryParam("disableCacheReprocessingChangeDetection", + String.valueOf(disableCacheReprocessingChangeDetection), false); + } + if (ifMatch != null) { + requestOptions.setHeader(HttpHeaderName.IF_MATCH, ifMatch); + } + if (ifNoneMatch != null) { + requestOptions.setHeader(HttpHeaderName.IF_NONE_MATCH, ifNoneMatch); + } + return createOrUpdateWithResponse(skillsetName, BinaryData.fromObject(skillset), requestOptions).getValue() + .toObject(SearchIndexerSkillset.class); + } + + /** + * Creates a new skillset in a search service or updates the skillset if it + * already exists. + * + * @param skillsetName The name of the skillset. + * @param skillset The skillset containing one or more skills to create or update in a search + * service. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a list of skills. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public SearchIndexerSkillset createOrUpdate(String skillsetName, SearchIndexerSkillset skillset) { + // Generated convenience method for createOrUpdateWithResponse + RequestOptions requestOptions = new RequestOptions(); + return createOrUpdateWithResponse(skillsetName, BinaryData.fromObject(skillset), requestOptions).getValue() + .toObject(SearchIndexerSkillset.class); + } + + /** + * Deletes a skillset in a search service. + * + * @param skillsetName The name of the skillset. + * @param matchConditions Specifies HTTP options for conditional requests. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public void delete(String skillsetName, MatchConditions matchConditions) { + // Generated convenience method for deleteWithResponse + RequestOptions requestOptions = new RequestOptions(); + String ifMatch = matchConditions == null ? null : matchConditions.getIfMatch(); + String ifNoneMatch = matchConditions == null ? null : matchConditions.getIfNoneMatch(); + if (ifMatch != null) { + requestOptions.setHeader(HttpHeaderName.IF_MATCH, ifMatch); + } + if (ifNoneMatch != null) { + requestOptions.setHeader(HttpHeaderName.IF_NONE_MATCH, ifNoneMatch); + } + deleteWithResponse(skillsetName, requestOptions).getValue(); + } + + /** + * Deletes a skillset in a search service. + * + * @param skillsetName The name of the skillset. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public void delete(String skillsetName) { + // Generated convenience method for deleteWithResponse + RequestOptions requestOptions = new RequestOptions(); + deleteWithResponse(skillsetName, requestOptions).getValue(); + } + + /** + * Retrieves a skillset in a search service. + * + * @param skillsetName The name of the skillset. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a list of skills. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public SearchIndexerSkillset get(String skillsetName) { + // Generated convenience method for getWithResponse + RequestOptions requestOptions = new RequestOptions(); + return getWithResponse(skillsetName, requestOptions).getValue().toObject(SearchIndexerSkillset.class); + } + + /** + * List all skillsets in a search service. + * + * @param 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. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return response from a list skillset request. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public ListSkillsetsResult list(String select) { + // Generated convenience method for listWithResponse + RequestOptions requestOptions = new RequestOptions(); + if (select != null) { + requestOptions.addQueryParam("$select", select, false); + } + return listWithResponse(requestOptions).getValue().toObject(ListSkillsetsResult.class); + } + + /** + * List all skillsets in a search service. + * + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return response from a list skillset request. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public ListSkillsetsResult list() { + // Generated convenience method for listWithResponse + RequestOptions requestOptions = new RequestOptions(); + return listWithResponse(requestOptions).getValue().toObject(ListSkillsetsResult.class); + } + + /** + * Creates a new skillset in a search service. + * + * @param skillset The skillset containing one or more skills to create in a search service. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a list of skills. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public SearchIndexerSkillset create(SearchIndexerSkillset skillset) { + // Generated convenience method for createWithResponse + RequestOptions requestOptions = new RequestOptions(); + return createWithResponse(BinaryData.fromObject(skillset), requestOptions).getValue() + .toObject(SearchIndexerSkillset.class); + } + + /** + * Reset an existing skillset in a search service. + * + * @param skillsetName The name of the skillset. + * @param skillNames The names of the skills to reset. If not specified, all skills in the skillset + * will be reset. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public void resetSkills(String skillsetName, SkillNames skillNames) { + // Generated convenience method for resetSkillsWithResponse + RequestOptions requestOptions = new RequestOptions(); + resetSkillsWithResponse(skillsetName, BinaryData.fromObject(skillNames), requestOptions).getValue(); + } +} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/SynonymMapsAsyncClient.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/SynonymMapsAsyncClient.java new file mode 100644 index 000000000000..33be81d8dd7e --- /dev/null +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/SynonymMapsAsyncClient.java @@ -0,0 +1,498 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.search.documents; + +import com.azure.core.annotation.Generated; +import com.azure.core.annotation.ReturnType; +import com.azure.core.annotation.ServiceClient; +import com.azure.core.annotation.ServiceMethod; +import com.azure.core.exception.ClientAuthenticationException; +import com.azure.core.exception.HttpResponseException; +import com.azure.core.exception.ResourceModifiedException; +import com.azure.core.exception.ResourceNotFoundException; +import com.azure.core.http.HttpHeaderName; +import com.azure.core.http.MatchConditions; +import com.azure.core.http.rest.RequestOptions; +import com.azure.core.http.rest.Response; +import com.azure.core.util.BinaryData; +import com.azure.core.util.FluxUtil; +import com.azure.search.documents.implementation.SynonymMapsImpl; +import com.azure.search.documents.models.ListSynonymMapsResult; +import com.azure.search.documents.models.SynonymMap; +import reactor.core.publisher.Mono; + +/** + * Initializes a new instance of the asynchronous SearchClient type. + */ +@ServiceClient(builder = SearchClientBuilder.class, isAsync = true) +public final class SynonymMapsAsyncClient { + @Generated + private final SynonymMapsImpl serviceClient; + + /** + * Initializes an instance of SynonymMapsAsyncClient class. + * + * @param serviceClient the service client implementation. + */ + @Generated + SynonymMapsAsyncClient(SynonymMapsImpl serviceClient) { + this.serviceClient = serviceClient; + } + + /** + * Creates a new synonym map or updates a synonym map if it already exists. + *

Header Parameters

+ * + * + * + * + * + *
Header Parameters
NameTypeRequiredDescription
If-MatchStringNoDefines the If-Match condition. The operation will be + * performed only if the ETag on the server matches this value.
If-None-MatchStringNoDefines the If-None-Match condition. The operation will + * be performed only if the ETag on the server does not match this value.
+ * You can add these to a request with {@link RequestOptions#addHeader} + *

Request Body Schema

+ * + *
+     * {@code
+     * {
+     *     name: String (Required)
+     *     format: String (Required)
+     *     synonyms: String (Required)
+     *     encryptionKey (Optional): {
+     *         keyVaultKeyName: String (Required)
+     *         keyVaultKeyVersion: String (Optional)
+     *         keyVaultUri: String (Required)
+     *         accessCredentials (Optional): {
+     *             applicationId: String (Required)
+     *             applicationSecret: String (Optional)
+     *         }
+     *         identity (Optional): {
+     *             @odata.type: String (Required)
+     *         }
+     *     }
+     *     @odata.etag: String (Optional)
+     * }
+     * }
+     * 
+ * + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     name: String (Required)
+     *     format: String (Required)
+     *     synonyms: String (Required)
+     *     encryptionKey (Optional): {
+     *         keyVaultKeyName: String (Required)
+     *         keyVaultKeyVersion: String (Optional)
+     *         keyVaultUri: String (Required)
+     *         accessCredentials (Optional): {
+     *             applicationId: String (Required)
+     *             applicationSecret: String (Optional)
+     *         }
+     *         identity (Optional): {
+     *             @odata.type: String (Required)
+     *         }
+     *     }
+     *     @odata.etag: String (Optional)
+     * }
+     * }
+     * 
+ * + * @param synonymMapName The name of the synonym map. + * @param synonymMap The definition of the synonym map to create or update. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return represents a synonym map definition along with {@link Response} on successful completion of {@link Mono}. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono> createOrUpdateWithResponse(String synonymMapName, BinaryData synonymMap, + RequestOptions requestOptions) { + return this.serviceClient.createOrUpdateWithResponseAsync(synonymMapName, synonymMap, requestOptions); + } + + /** + * Deletes a synonym map. + *

Header Parameters

+ * + * + * + * + * + *
Header Parameters
NameTypeRequiredDescription
If-MatchStringNoDefines the If-Match condition. The operation will be + * performed only if the ETag on the server matches this value.
If-None-MatchStringNoDefines the If-None-Match condition. The operation will + * be performed only if the ETag on the server does not match this value.
+ * You can add these to a request with {@link RequestOptions#addHeader} + * + * @param synonymMapName The name of the synonym map. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return the {@link Response} on successful completion of {@link Mono}. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono> deleteWithResponse(String synonymMapName, RequestOptions requestOptions) { + return this.serviceClient.deleteWithResponseAsync(synonymMapName, requestOptions); + } + + /** + * Retrieves a synonym map definition. + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     name: String (Required)
+     *     format: String (Required)
+     *     synonyms: String (Required)
+     *     encryptionKey (Optional): {
+     *         keyVaultKeyName: String (Required)
+     *         keyVaultKeyVersion: String (Optional)
+     *         keyVaultUri: String (Required)
+     *         accessCredentials (Optional): {
+     *             applicationId: String (Required)
+     *             applicationSecret: String (Optional)
+     *         }
+     *         identity (Optional): {
+     *             @odata.type: String (Required)
+     *         }
+     *     }
+     *     @odata.etag: String (Optional)
+     * }
+     * }
+     * 
+ * + * @param synonymMapName The name of the synonym map. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return represents a synonym map definition along with {@link Response} on successful completion of {@link Mono}. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono> getWithResponse(String synonymMapName, RequestOptions requestOptions) { + return this.serviceClient.getWithResponseAsync(synonymMapName, requestOptions); + } + + /** + * Lists all synonym maps available for a search service. + *

Query Parameters

+ * + * + * + * + *
Query Parameters
NameTypeRequiredDescription
$selectStringNoSelects 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.
+ * You can add these to a request with {@link RequestOptions#addQueryParam} + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     value (Required): [
+     *          (Required){
+     *             name: String (Required)
+     *             format: String (Required)
+     *             synonyms: String (Required)
+     *             encryptionKey (Optional): {
+     *                 keyVaultKeyName: String (Required)
+     *                 keyVaultKeyVersion: String (Optional)
+     *                 keyVaultUri: String (Required)
+     *                 accessCredentials (Optional): {
+     *                     applicationId: String (Required)
+     *                     applicationSecret: String (Optional)
+     *                 }
+     *                 identity (Optional): {
+     *                     @odata.type: String (Required)
+     *                 }
+     *             }
+     *             @odata.etag: String (Optional)
+     *         }
+     *     ]
+     * }
+     * }
+     * 
+ * + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return response from a List SynonymMaps request along with {@link Response} on successful completion of + * {@link Mono}. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono> listWithResponse(RequestOptions requestOptions) { + return this.serviceClient.listWithResponseAsync(requestOptions); + } + + /** + * Creates a new synonym map. + *

Request Body Schema

+ * + *
+     * {@code
+     * {
+     *     name: String (Required)
+     *     format: String (Required)
+     *     synonyms: String (Required)
+     *     encryptionKey (Optional): {
+     *         keyVaultKeyName: String (Required)
+     *         keyVaultKeyVersion: String (Optional)
+     *         keyVaultUri: String (Required)
+     *         accessCredentials (Optional): {
+     *             applicationId: String (Required)
+     *             applicationSecret: String (Optional)
+     *         }
+     *         identity (Optional): {
+     *             @odata.type: String (Required)
+     *         }
+     *     }
+     *     @odata.etag: String (Optional)
+     * }
+     * }
+     * 
+ * + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     name: String (Required)
+     *     format: String (Required)
+     *     synonyms: String (Required)
+     *     encryptionKey (Optional): {
+     *         keyVaultKeyName: String (Required)
+     *         keyVaultKeyVersion: String (Optional)
+     *         keyVaultUri: String (Required)
+     *         accessCredentials (Optional): {
+     *             applicationId: String (Required)
+     *             applicationSecret: String (Optional)
+     *         }
+     *         identity (Optional): {
+     *             @odata.type: String (Required)
+     *         }
+     *     }
+     *     @odata.etag: String (Optional)
+     * }
+     * }
+     * 
+ * + * @param synonymMap The definition of the synonym map to create. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return represents a synonym map definition along with {@link Response} on successful completion of {@link Mono}. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono> createWithResponse(BinaryData synonymMap, RequestOptions requestOptions) { + return this.serviceClient.createWithResponseAsync(synonymMap, requestOptions); + } + + /** + * Creates a new synonym map or updates a synonym map if it already exists. + * + * @param synonymMapName The name of the synonym map. + * @param synonymMap The definition of the synonym map to create or update. + * @param matchConditions Specifies HTTP options for conditional requests. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return represents a synonym map definition on successful completion of {@link Mono}. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono createOrUpdate(String synonymMapName, SynonymMap synonymMap, + MatchConditions matchConditions) { + // Generated convenience method for createOrUpdateWithResponse + RequestOptions requestOptions = new RequestOptions(); + String ifMatch = matchConditions == null ? null : matchConditions.getIfMatch(); + String ifNoneMatch = matchConditions == null ? null : matchConditions.getIfNoneMatch(); + if (ifMatch != null) { + requestOptions.setHeader(HttpHeaderName.IF_MATCH, ifMatch); + } + if (ifNoneMatch != null) { + requestOptions.setHeader(HttpHeaderName.IF_NONE_MATCH, ifNoneMatch); + } + return createOrUpdateWithResponse(synonymMapName, BinaryData.fromObject(synonymMap), requestOptions) + .flatMap(FluxUtil::toMono) + .map(protocolMethodData -> protocolMethodData.toObject(SynonymMap.class)); + } + + /** + * Creates a new synonym map or updates a synonym map if it already exists. + * + * @param synonymMapName The name of the synonym map. + * @param synonymMap The definition of the synonym map to create or update. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return represents a synonym map definition on successful completion of {@link Mono}. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono createOrUpdate(String synonymMapName, SynonymMap synonymMap) { + // Generated convenience method for createOrUpdateWithResponse + RequestOptions requestOptions = new RequestOptions(); + return createOrUpdateWithResponse(synonymMapName, BinaryData.fromObject(synonymMap), requestOptions) + .flatMap(FluxUtil::toMono) + .map(protocolMethodData -> protocolMethodData.toObject(SynonymMap.class)); + } + + /** + * Deletes a synonym map. + * + * @param synonymMapName The name of the synonym map. + * @param matchConditions Specifies HTTP options for conditional requests. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return A {@link Mono} that completes when a successful response is received. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono delete(String synonymMapName, MatchConditions matchConditions) { + // Generated convenience method for deleteWithResponse + RequestOptions requestOptions = new RequestOptions(); + String ifMatch = matchConditions == null ? null : matchConditions.getIfMatch(); + String ifNoneMatch = matchConditions == null ? null : matchConditions.getIfNoneMatch(); + if (ifMatch != null) { + requestOptions.setHeader(HttpHeaderName.IF_MATCH, ifMatch); + } + if (ifNoneMatch != null) { + requestOptions.setHeader(HttpHeaderName.IF_NONE_MATCH, ifNoneMatch); + } + return deleteWithResponse(synonymMapName, requestOptions).flatMap(FluxUtil::toMono); + } + + /** + * Deletes a synonym map. + * + * @param synonymMapName The name of the synonym map. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return A {@link Mono} that completes when a successful response is received. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono delete(String synonymMapName) { + // Generated convenience method for deleteWithResponse + RequestOptions requestOptions = new RequestOptions(); + return deleteWithResponse(synonymMapName, requestOptions).flatMap(FluxUtil::toMono); + } + + /** + * Retrieves a synonym map definition. + * + * @param synonymMapName The name of the synonym map. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return represents a synonym map definition on successful completion of {@link Mono}. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono get(String synonymMapName) { + // Generated convenience method for getWithResponse + RequestOptions requestOptions = new RequestOptions(); + return getWithResponse(synonymMapName, requestOptions).flatMap(FluxUtil::toMono) + .map(protocolMethodData -> protocolMethodData.toObject(SynonymMap.class)); + } + + /** + * Lists all synonym maps available for a search service. + * + * @param 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. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return response from a List SynonymMaps request on successful completion of {@link Mono}. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono list(String select) { + // Generated convenience method for listWithResponse + RequestOptions requestOptions = new RequestOptions(); + if (select != null) { + requestOptions.addQueryParam("$select", select, false); + } + return listWithResponse(requestOptions).flatMap(FluxUtil::toMono) + .map(protocolMethodData -> protocolMethodData.toObject(ListSynonymMapsResult.class)); + } + + /** + * Lists all synonym maps available for a search service. + * + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return response from a List SynonymMaps request on successful completion of {@link Mono}. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono list() { + // Generated convenience method for listWithResponse + RequestOptions requestOptions = new RequestOptions(); + return listWithResponse(requestOptions).flatMap(FluxUtil::toMono) + .map(protocolMethodData -> protocolMethodData.toObject(ListSynonymMapsResult.class)); + } + + /** + * Creates a new synonym map. + * + * @param synonymMap The definition of the synonym map to create. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return represents a synonym map definition on successful completion of {@link Mono}. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono create(SynonymMap synonymMap) { + // Generated convenience method for createWithResponse + RequestOptions requestOptions = new RequestOptions(); + return createWithResponse(BinaryData.fromObject(synonymMap), requestOptions).flatMap(FluxUtil::toMono) + .map(protocolMethodData -> protocolMethodData.toObject(SynonymMap.class)); + } +} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/SynonymMapsClient.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/SynonymMapsClient.java new file mode 100644 index 000000000000..bdf8cd077288 --- /dev/null +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/SynonymMapsClient.java @@ -0,0 +1,487 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.search.documents; + +import com.azure.core.annotation.Generated; +import com.azure.core.annotation.ReturnType; +import com.azure.core.annotation.ServiceClient; +import com.azure.core.annotation.ServiceMethod; +import com.azure.core.exception.ClientAuthenticationException; +import com.azure.core.exception.HttpResponseException; +import com.azure.core.exception.ResourceModifiedException; +import com.azure.core.exception.ResourceNotFoundException; +import com.azure.core.http.HttpHeaderName; +import com.azure.core.http.MatchConditions; +import com.azure.core.http.rest.RequestOptions; +import com.azure.core.http.rest.Response; +import com.azure.core.util.BinaryData; +import com.azure.search.documents.implementation.SynonymMapsImpl; +import com.azure.search.documents.models.ListSynonymMapsResult; +import com.azure.search.documents.models.SynonymMap; + +/** + * Initializes a new instance of the synchronous SearchClient type. + */ +@ServiceClient(builder = SearchClientBuilder.class) +public final class SynonymMapsClient { + @Generated + private final SynonymMapsImpl serviceClient; + + /** + * Initializes an instance of SynonymMapsClient class. + * + * @param serviceClient the service client implementation. + */ + @Generated + SynonymMapsClient(SynonymMapsImpl serviceClient) { + this.serviceClient = serviceClient; + } + + /** + * Creates a new synonym map or updates a synonym map if it already exists. + *

Header Parameters

+ * + * + * + * + * + *
Header Parameters
NameTypeRequiredDescription
If-MatchStringNoDefines the If-Match condition. The operation will be + * performed only if the ETag on the server matches this value.
If-None-MatchStringNoDefines the If-None-Match condition. The operation will + * be performed only if the ETag on the server does not match this value.
+ * You can add these to a request with {@link RequestOptions#addHeader} + *

Request Body Schema

+ * + *
+     * {@code
+     * {
+     *     name: String (Required)
+     *     format: String (Required)
+     *     synonyms: String (Required)
+     *     encryptionKey (Optional): {
+     *         keyVaultKeyName: String (Required)
+     *         keyVaultKeyVersion: String (Optional)
+     *         keyVaultUri: String (Required)
+     *         accessCredentials (Optional): {
+     *             applicationId: String (Required)
+     *             applicationSecret: String (Optional)
+     *         }
+     *         identity (Optional): {
+     *             @odata.type: String (Required)
+     *         }
+     *     }
+     *     @odata.etag: String (Optional)
+     * }
+     * }
+     * 
+ * + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     name: String (Required)
+     *     format: String (Required)
+     *     synonyms: String (Required)
+     *     encryptionKey (Optional): {
+     *         keyVaultKeyName: String (Required)
+     *         keyVaultKeyVersion: String (Optional)
+     *         keyVaultUri: String (Required)
+     *         accessCredentials (Optional): {
+     *             applicationId: String (Required)
+     *             applicationSecret: String (Optional)
+     *         }
+     *         identity (Optional): {
+     *             @odata.type: String (Required)
+     *         }
+     *     }
+     *     @odata.etag: String (Optional)
+     * }
+     * }
+     * 
+ * + * @param synonymMapName The name of the synonym map. + * @param synonymMap The definition of the synonym map to create or update. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return represents a synonym map definition along with {@link Response}. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public Response createOrUpdateWithResponse(String synonymMapName, BinaryData synonymMap, + RequestOptions requestOptions) { + return this.serviceClient.createOrUpdateWithResponse(synonymMapName, synonymMap, requestOptions); + } + + /** + * Deletes a synonym map. + *

Header Parameters

+ * + * + * + * + * + *
Header Parameters
NameTypeRequiredDescription
If-MatchStringNoDefines the If-Match condition. The operation will be + * performed only if the ETag on the server matches this value.
If-None-MatchStringNoDefines the If-None-Match condition. The operation will + * be performed only if the ETag on the server does not match this value.
+ * You can add these to a request with {@link RequestOptions#addHeader} + * + * @param synonymMapName The name of the synonym map. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return the {@link Response}. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public Response deleteWithResponse(String synonymMapName, RequestOptions requestOptions) { + return this.serviceClient.deleteWithResponse(synonymMapName, requestOptions); + } + + /** + * Retrieves a synonym map definition. + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     name: String (Required)
+     *     format: String (Required)
+     *     synonyms: String (Required)
+     *     encryptionKey (Optional): {
+     *         keyVaultKeyName: String (Required)
+     *         keyVaultKeyVersion: String (Optional)
+     *         keyVaultUri: String (Required)
+     *         accessCredentials (Optional): {
+     *             applicationId: String (Required)
+     *             applicationSecret: String (Optional)
+     *         }
+     *         identity (Optional): {
+     *             @odata.type: String (Required)
+     *         }
+     *     }
+     *     @odata.etag: String (Optional)
+     * }
+     * }
+     * 
+ * + * @param synonymMapName The name of the synonym map. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return represents a synonym map definition along with {@link Response}. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public Response getWithResponse(String synonymMapName, RequestOptions requestOptions) { + return this.serviceClient.getWithResponse(synonymMapName, requestOptions); + } + + /** + * Lists all synonym maps available for a search service. + *

Query Parameters

+ * + * + * + * + *
Query Parameters
NameTypeRequiredDescription
$selectStringNoSelects 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.
+ * You can add these to a request with {@link RequestOptions#addQueryParam} + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     value (Required): [
+     *          (Required){
+     *             name: String (Required)
+     *             format: String (Required)
+     *             synonyms: String (Required)
+     *             encryptionKey (Optional): {
+     *                 keyVaultKeyName: String (Required)
+     *                 keyVaultKeyVersion: String (Optional)
+     *                 keyVaultUri: String (Required)
+     *                 accessCredentials (Optional): {
+     *                     applicationId: String (Required)
+     *                     applicationSecret: String (Optional)
+     *                 }
+     *                 identity (Optional): {
+     *                     @odata.type: String (Required)
+     *                 }
+     *             }
+     *             @odata.etag: String (Optional)
+     *         }
+     *     ]
+     * }
+     * }
+     * 
+ * + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return response from a List SynonymMaps request along with {@link Response}. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public Response listWithResponse(RequestOptions requestOptions) { + return this.serviceClient.listWithResponse(requestOptions); + } + + /** + * Creates a new synonym map. + *

Request Body Schema

+ * + *
+     * {@code
+     * {
+     *     name: String (Required)
+     *     format: String (Required)
+     *     synonyms: String (Required)
+     *     encryptionKey (Optional): {
+     *         keyVaultKeyName: String (Required)
+     *         keyVaultKeyVersion: String (Optional)
+     *         keyVaultUri: String (Required)
+     *         accessCredentials (Optional): {
+     *             applicationId: String (Required)
+     *             applicationSecret: String (Optional)
+     *         }
+     *         identity (Optional): {
+     *             @odata.type: String (Required)
+     *         }
+     *     }
+     *     @odata.etag: String (Optional)
+     * }
+     * }
+     * 
+ * + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     name: String (Required)
+     *     format: String (Required)
+     *     synonyms: String (Required)
+     *     encryptionKey (Optional): {
+     *         keyVaultKeyName: String (Required)
+     *         keyVaultKeyVersion: String (Optional)
+     *         keyVaultUri: String (Required)
+     *         accessCredentials (Optional): {
+     *             applicationId: String (Required)
+     *             applicationSecret: String (Optional)
+     *         }
+     *         identity (Optional): {
+     *             @odata.type: String (Required)
+     *         }
+     *     }
+     *     @odata.etag: String (Optional)
+     * }
+     * }
+     * 
+ * + * @param synonymMap The definition of the synonym map to create. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return represents a synonym map definition along with {@link Response}. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public Response createWithResponse(BinaryData synonymMap, RequestOptions requestOptions) { + return this.serviceClient.createWithResponse(synonymMap, requestOptions); + } + + /** + * Creates a new synonym map or updates a synonym map if it already exists. + * + * @param synonymMapName The name of the synonym map. + * @param synonymMap The definition of the synonym map to create or update. + * @param matchConditions Specifies HTTP options for conditional requests. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return represents a synonym map definition. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public SynonymMap createOrUpdate(String synonymMapName, SynonymMap synonymMap, MatchConditions matchConditions) { + // Generated convenience method for createOrUpdateWithResponse + RequestOptions requestOptions = new RequestOptions(); + String ifMatch = matchConditions == null ? null : matchConditions.getIfMatch(); + String ifNoneMatch = matchConditions == null ? null : matchConditions.getIfNoneMatch(); + if (ifMatch != null) { + requestOptions.setHeader(HttpHeaderName.IF_MATCH, ifMatch); + } + if (ifNoneMatch != null) { + requestOptions.setHeader(HttpHeaderName.IF_NONE_MATCH, ifNoneMatch); + } + return createOrUpdateWithResponse(synonymMapName, BinaryData.fromObject(synonymMap), requestOptions).getValue() + .toObject(SynonymMap.class); + } + + /** + * Creates a new synonym map or updates a synonym map if it already exists. + * + * @param synonymMapName The name of the synonym map. + * @param synonymMap The definition of the synonym map to create or update. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return represents a synonym map definition. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public SynonymMap createOrUpdate(String synonymMapName, SynonymMap synonymMap) { + // Generated convenience method for createOrUpdateWithResponse + RequestOptions requestOptions = new RequestOptions(); + return createOrUpdateWithResponse(synonymMapName, BinaryData.fromObject(synonymMap), requestOptions).getValue() + .toObject(SynonymMap.class); + } + + /** + * Deletes a synonym map. + * + * @param synonymMapName The name of the synonym map. + * @param matchConditions Specifies HTTP options for conditional requests. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public void delete(String synonymMapName, MatchConditions matchConditions) { + // Generated convenience method for deleteWithResponse + RequestOptions requestOptions = new RequestOptions(); + String ifMatch = matchConditions == null ? null : matchConditions.getIfMatch(); + String ifNoneMatch = matchConditions == null ? null : matchConditions.getIfNoneMatch(); + if (ifMatch != null) { + requestOptions.setHeader(HttpHeaderName.IF_MATCH, ifMatch); + } + if (ifNoneMatch != null) { + requestOptions.setHeader(HttpHeaderName.IF_NONE_MATCH, ifNoneMatch); + } + deleteWithResponse(synonymMapName, requestOptions).getValue(); + } + + /** + * Deletes a synonym map. + * + * @param synonymMapName The name of the synonym map. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public void delete(String synonymMapName) { + // Generated convenience method for deleteWithResponse + RequestOptions requestOptions = new RequestOptions(); + deleteWithResponse(synonymMapName, requestOptions).getValue(); + } + + /** + * Retrieves a synonym map definition. + * + * @param synonymMapName The name of the synonym map. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return represents a synonym map definition. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public SynonymMap get(String synonymMapName) { + // Generated convenience method for getWithResponse + RequestOptions requestOptions = new RequestOptions(); + return getWithResponse(synonymMapName, requestOptions).getValue().toObject(SynonymMap.class); + } + + /** + * Lists all synonym maps available for a search service. + * + * @param 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. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return response from a List SynonymMaps request. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public ListSynonymMapsResult list(String select) { + // Generated convenience method for listWithResponse + RequestOptions requestOptions = new RequestOptions(); + if (select != null) { + requestOptions.addQueryParam("$select", select, false); + } + return listWithResponse(requestOptions).getValue().toObject(ListSynonymMapsResult.class); + } + + /** + * Lists all synonym maps available for a search service. + * + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return response from a List SynonymMaps request. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public ListSynonymMapsResult list() { + // Generated convenience method for listWithResponse + RequestOptions requestOptions = new RequestOptions(); + return listWithResponse(requestOptions).getValue().toObject(ListSynonymMapsResult.class); + } + + /** + * Creates a new synonym map. + * + * @param synonymMap The definition of the synonym map to create. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return represents a synonym map definition. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public SynonymMap create(SynonymMap synonymMap) { + // Generated convenience method for createWithResponse + RequestOptions requestOptions = new RequestOptions(); + return createWithResponse(BinaryData.fromObject(synonymMap), requestOptions).getValue() + .toObject(SynonymMap.class); + } +} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/implementation/AliasesImpl.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/implementation/AliasesImpl.java new file mode 100644 index 000000000000..7aec6f696b89 --- /dev/null +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/implementation/AliasesImpl.java @@ -0,0 +1,664 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.search.documents.implementation; + +import com.azure.core.annotation.BodyParam; +import com.azure.core.annotation.Delete; +import com.azure.core.annotation.ExpectedResponses; +import com.azure.core.annotation.Get; +import com.azure.core.annotation.HeaderParam; +import com.azure.core.annotation.Host; +import com.azure.core.annotation.HostParam; +import com.azure.core.annotation.PathParam; +import com.azure.core.annotation.Post; +import com.azure.core.annotation.Put; +import com.azure.core.annotation.QueryParam; +import com.azure.core.annotation.ReturnType; +import com.azure.core.annotation.ServiceInterface; +import com.azure.core.annotation.ServiceMethod; +import com.azure.core.annotation.UnexpectedResponseExceptionType; +import com.azure.core.exception.ClientAuthenticationException; +import com.azure.core.exception.HttpResponseException; +import com.azure.core.exception.ResourceModifiedException; +import com.azure.core.exception.ResourceNotFoundException; +import com.azure.core.http.rest.PagedFlux; +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.http.rest.PagedResponse; +import com.azure.core.http.rest.PagedResponseBase; +import com.azure.core.http.rest.RequestOptions; +import com.azure.core.http.rest.Response; +import com.azure.core.http.rest.RestProxy; +import com.azure.core.util.BinaryData; +import com.azure.core.util.Context; +import com.azure.core.util.FluxUtil; +import com.azure.search.documents.SearchServiceVersion; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; +import reactor.core.publisher.Mono; + +/** + * An instance of this class provides access to all the operations defined in Aliases. + */ +public final class AliasesImpl { + /** + * The proxy service used to perform REST calls. + */ + private final AliasesService service; + + /** + * The service client containing this operation class. + */ + private final SearchClientImpl client; + + /** + * Initializes an instance of AliasesImpl. + * + * @param client the instance of the service client containing this operation class. + */ + AliasesImpl(SearchClientImpl client) { + this.service = RestProxy.create(AliasesService.class, client.getHttpPipeline(), client.getSerializerAdapter()); + this.client = client; + } + + /** + * Gets Service version. + * + * @return the serviceVersion value. + */ + public SearchServiceVersion getServiceVersion() { + return client.getServiceVersion(); + } + + /** + * The interface defining all the services for SearchClientAliases to be used by the proxy service to perform REST + * calls. + */ + @Host("{endpoint}") + @ServiceInterface(name = "SearchClientAliases") + public interface AliasesService { + @Post("/aliases") + @ExpectedResponses({ 201 }) + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Mono> create(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @HeaderParam("Content-Type") String contentType, + @HeaderParam("Accept") String accept, @BodyParam("application/json") BinaryData alias, + RequestOptions requestOptions, Context context); + + @Post("/aliases") + @ExpectedResponses({ 201 }) + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Response createSync(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @HeaderParam("Content-Type") String contentType, + @HeaderParam("Accept") String accept, @BodyParam("application/json") BinaryData alias, + RequestOptions requestOptions, Context context); + + @Get("/aliases") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Mono> list(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, + RequestOptions requestOptions, Context context); + + @Get("/aliases") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Response listSync(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, + RequestOptions requestOptions, Context context); + + @Put("/aliases('{aliasName}')") + @ExpectedResponses({ 200, 201 }) + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Mono> createOrUpdate(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @HeaderParam("Prefer") String prefer, + @PathParam("aliasName") String aliasName, @HeaderParam("Content-Type") String contentType, + @HeaderParam("Accept") String accept, @BodyParam("application/json") BinaryData alias, + RequestOptions requestOptions, Context context); + + @Put("/aliases('{aliasName}')") + @ExpectedResponses({ 200, 201 }) + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Response createOrUpdateSync(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @HeaderParam("Prefer") String prefer, + @PathParam("aliasName") String aliasName, @HeaderParam("Content-Type") String contentType, + @HeaderParam("Accept") String accept, @BodyParam("application/json") BinaryData alias, + RequestOptions requestOptions, Context context); + + @Delete("/aliases('{aliasName}')") + @ExpectedResponses({ 204, 404 }) + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Mono> delete(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @PathParam("aliasName") String aliasName, + @HeaderParam("Accept") String accept, RequestOptions requestOptions, Context context); + + @Delete("/aliases('{aliasName}')") + @ExpectedResponses({ 204, 404 }) + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Response deleteSync(@HostParam("endpoint") String endpoint, @QueryParam("api-version") String apiVersion, + @PathParam("aliasName") String aliasName, @HeaderParam("Accept") String accept, + RequestOptions requestOptions, Context context); + + @Get("/aliases('{aliasName}')") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Mono> get(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @PathParam("aliasName") String aliasName, + @HeaderParam("Accept") String accept, RequestOptions requestOptions, Context context); + + @Get("/aliases('{aliasName}')") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Response getSync(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @PathParam("aliasName") String aliasName, + @HeaderParam("Accept") String accept, RequestOptions requestOptions, Context context); + } + + /** + * Creates a new search alias. + *

Request Body Schema

+ * + *
+     * {@code
+     * {
+     *     name: String (Required)
+     *     indexes (Required): [
+     *         String (Required)
+     *     ]
+     *     @odata.etag: String (Optional)
+     * }
+     * }
+     * 
+ * + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     name: String (Required)
+     *     indexes (Required): [
+     *         String (Required)
+     *     ]
+     *     @odata.etag: String (Optional)
+     * }
+     * }
+     * 
+ * + * @param alias The definition of the alias to create. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return represents an index alias, which describes a mapping from the alias name to an + * index along with {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono> createWithResponseAsync(BinaryData alias, RequestOptions requestOptions) { + final String contentType = "application/json"; + final String accept = "application/json"; + return FluxUtil.withContext(context -> service.create(this.client.getEndpoint(), + this.client.getServiceVersion().getVersion(), contentType, accept, alias, requestOptions, context)); + } + + /** + * Creates a new search alias. + *

Request Body Schema

+ * + *
+     * {@code
+     * {
+     *     name: String (Required)
+     *     indexes (Required): [
+     *         String (Required)
+     *     ]
+     *     @odata.etag: String (Optional)
+     * }
+     * }
+     * 
+ * + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     name: String (Required)
+     *     indexes (Required): [
+     *         String (Required)
+     *     ]
+     *     @odata.etag: String (Optional)
+     * }
+     * }
+     * 
+ * + * @param alias The definition of the alias to create. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return represents an index alias, which describes a mapping from the alias name to an + * index along with {@link Response}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Response createWithResponse(BinaryData alias, RequestOptions requestOptions) { + final String contentType = "application/json"; + final String accept = "application/json"; + return service.createSync(this.client.getEndpoint(), this.client.getServiceVersion().getVersion(), contentType, + accept, alias, requestOptions, Context.NONE); + } + + /** + * Lists all aliases available for a search service. + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     name: String (Required)
+     *     indexes (Required): [
+     *         String (Required)
+     *     ]
+     *     @odata.etag: String (Optional)
+     * }
+     * }
+     * 
+ * + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return response from a List Aliases request along with {@link PagedResponse} on successful completion of + * {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> listSinglePageAsync(RequestOptions requestOptions) { + final String accept = "application/json"; + return FluxUtil + .withContext(context -> service.list(this.client.getEndpoint(), + this.client.getServiceVersion().getVersion(), accept, requestOptions, context)) + .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), + getValues(res.getValue(), "value"), null, null)); + } + + /** + * Lists all aliases available for a search service. + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     name: String (Required)
+     *     indexes (Required): [
+     *         String (Required)
+     *     ]
+     *     @odata.etag: String (Optional)
+     * }
+     * }
+     * 
+ * + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return response from a List Aliases request as paginated response with {@link PagedFlux}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + public PagedFlux listAsync(RequestOptions requestOptions) { + return new PagedFlux<>(() -> listSinglePageAsync(requestOptions)); + } + + /** + * Lists all aliases available for a search service. + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     name: String (Required)
+     *     indexes (Required): [
+     *         String (Required)
+     *     ]
+     *     @odata.etag: String (Optional)
+     * }
+     * }
+     * 
+ * + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return response from a List Aliases request along with {@link PagedResponse}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private PagedResponse listSinglePage(RequestOptions requestOptions) { + final String accept = "application/json"; + Response res = service.listSync(this.client.getEndpoint(), + this.client.getServiceVersion().getVersion(), accept, requestOptions, Context.NONE); + return new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), + getValues(res.getValue(), "value"), null, null); + } + + /** + * Lists all aliases available for a search service. + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     name: String (Required)
+     *     indexes (Required): [
+     *         String (Required)
+     *     ]
+     *     @odata.etag: String (Optional)
+     * }
+     * }
+     * 
+ * + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return response from a List Aliases request as paginated response with {@link PagedIterable}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + public PagedIterable list(RequestOptions requestOptions) { + return new PagedIterable<>(() -> listSinglePage(requestOptions)); + } + + /** + * Creates a new search alias or updates an alias if it already exists. + *

Header Parameters

+ * + * + * + * + * + *
Header Parameters
NameTypeRequiredDescription
If-MatchStringNoDefines the If-Match condition. The operation will be + * performed only if the ETag on the server matches this value.
If-None-MatchStringNoDefines the If-None-Match condition. The operation will + * be performed only if the ETag on the server does not match this value.
+ * You can add these to a request with {@link RequestOptions#addHeader} + *

Request Body Schema

+ * + *
+     * {@code
+     * {
+     *     name: String (Required)
+     *     indexes (Required): [
+     *         String (Required)
+     *     ]
+     *     @odata.etag: String (Optional)
+     * }
+     * }
+     * 
+ * + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     name: String (Required)
+     *     indexes (Required): [
+     *         String (Required)
+     *     ]
+     *     @odata.etag: String (Optional)
+     * }
+     * }
+     * 
+ * + * @param aliasName The name of the alias. + * @param alias The definition of the alias to create or update. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return represents an index alias, which describes a mapping from the alias name to an + * index along with {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono> createOrUpdateWithResponseAsync(String aliasName, BinaryData alias, + RequestOptions requestOptions) { + final String prefer = "return=representation"; + final String contentType = "application/json"; + final String accept = "application/json"; + return FluxUtil.withContext( + context -> service.createOrUpdate(this.client.getEndpoint(), this.client.getServiceVersion().getVersion(), + prefer, aliasName, contentType, accept, alias, requestOptions, context)); + } + + /** + * Creates a new search alias or updates an alias if it already exists. + *

Header Parameters

+ * + * + * + * + * + *
Header Parameters
NameTypeRequiredDescription
If-MatchStringNoDefines the If-Match condition. The operation will be + * performed only if the ETag on the server matches this value.
If-None-MatchStringNoDefines the If-None-Match condition. The operation will + * be performed only if the ETag on the server does not match this value.
+ * You can add these to a request with {@link RequestOptions#addHeader} + *

Request Body Schema

+ * + *
+     * {@code
+     * {
+     *     name: String (Required)
+     *     indexes (Required): [
+     *         String (Required)
+     *     ]
+     *     @odata.etag: String (Optional)
+     * }
+     * }
+     * 
+ * + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     name: String (Required)
+     *     indexes (Required): [
+     *         String (Required)
+     *     ]
+     *     @odata.etag: String (Optional)
+     * }
+     * }
+     * 
+ * + * @param aliasName The name of the alias. + * @param alias The definition of the alias to create or update. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return represents an index alias, which describes a mapping from the alias name to an + * index along with {@link Response}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Response createOrUpdateWithResponse(String aliasName, BinaryData alias, + RequestOptions requestOptions) { + final String prefer = "return=representation"; + final String contentType = "application/json"; + final String accept = "application/json"; + return service.createOrUpdateSync(this.client.getEndpoint(), this.client.getServiceVersion().getVersion(), + prefer, aliasName, contentType, accept, alias, requestOptions, Context.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. + *

Header Parameters

+ * + * + * + * + * + *
Header Parameters
NameTypeRequiredDescription
If-MatchStringNoDefines the If-Match condition. The operation will be + * performed only if the ETag on the server matches this value.
If-None-MatchStringNoDefines the If-None-Match condition. The operation will + * be performed only if the ETag on the server does not match this value.
+ * You can add these to a request with {@link RequestOptions#addHeader} + * + * @param aliasName The name of the alias. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return the {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono> deleteWithResponseAsync(String aliasName, RequestOptions requestOptions) { + final String accept = "application/json"; + return FluxUtil.withContext(context -> service.delete(this.client.getEndpoint(), + this.client.getServiceVersion().getVersion(), aliasName, accept, requestOptions, context)); + } + + /** + * 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. + *

Header Parameters

+ * + * + * + * + * + *
Header Parameters
NameTypeRequiredDescription
If-MatchStringNoDefines the If-Match condition. The operation will be + * performed only if the ETag on the server matches this value.
If-None-MatchStringNoDefines the If-None-Match condition. The operation will + * be performed only if the ETag on the server does not match this value.
+ * You can add these to a request with {@link RequestOptions#addHeader} + * + * @param aliasName The name of the alias. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return the {@link Response}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Response deleteWithResponse(String aliasName, RequestOptions requestOptions) { + final String accept = "application/json"; + return service.deleteSync(this.client.getEndpoint(), this.client.getServiceVersion().getVersion(), aliasName, + accept, requestOptions, Context.NONE); + } + + /** + * Retrieves an alias definition. + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     name: String (Required)
+     *     indexes (Required): [
+     *         String (Required)
+     *     ]
+     *     @odata.etag: String (Optional)
+     * }
+     * }
+     * 
+ * + * @param aliasName The name of the alias. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return represents an index alias, which describes a mapping from the alias name to an + * index along with {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono> getWithResponseAsync(String aliasName, RequestOptions requestOptions) { + final String accept = "application/json"; + return FluxUtil.withContext(context -> service.get(this.client.getEndpoint(), + this.client.getServiceVersion().getVersion(), aliasName, accept, requestOptions, context)); + } + + /** + * Retrieves an alias definition. + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     name: String (Required)
+     *     indexes (Required): [
+     *         String (Required)
+     *     ]
+     *     @odata.etag: String (Optional)
+     * }
+     * }
+     * 
+ * + * @param aliasName The name of the alias. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return represents an index alias, which describes a mapping from the alias name to an + * index along with {@link Response}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Response getWithResponse(String aliasName, RequestOptions requestOptions) { + final String accept = "application/json"; + return service.getSync(this.client.getEndpoint(), this.client.getServiceVersion().getVersion(), aliasName, + accept, requestOptions, Context.NONE); + } + + private List getValues(BinaryData binaryData, String path) { + try { + Map obj = binaryData.toObject(Map.class); + List values = (List) obj.get(path); + return values.stream().map(BinaryData::fromObject).collect(Collectors.toList()); + } catch (RuntimeException e) { + return null; + } + } + + private String getNextLink(BinaryData binaryData, String path) { + try { + Map obj = binaryData.toObject(Map.class); + return (String) obj.get(path); + } catch (RuntimeException e) { + return null; + } + } +} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/implementation/DataSourcesImpl.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/implementation/DataSourcesImpl.java new file mode 100644 index 000000000000..0c79ce1089c5 --- /dev/null +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/implementation/DataSourcesImpl.java @@ -0,0 +1,914 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.search.documents.implementation; + +import com.azure.core.annotation.BodyParam; +import com.azure.core.annotation.Delete; +import com.azure.core.annotation.ExpectedResponses; +import com.azure.core.annotation.Get; +import com.azure.core.annotation.HeaderParam; +import com.azure.core.annotation.Host; +import com.azure.core.annotation.HostParam; +import com.azure.core.annotation.PathParam; +import com.azure.core.annotation.Post; +import com.azure.core.annotation.Put; +import com.azure.core.annotation.QueryParam; +import com.azure.core.annotation.ReturnType; +import com.azure.core.annotation.ServiceInterface; +import com.azure.core.annotation.ServiceMethod; +import com.azure.core.annotation.UnexpectedResponseExceptionType; +import com.azure.core.exception.ClientAuthenticationException; +import com.azure.core.exception.HttpResponseException; +import com.azure.core.exception.ResourceModifiedException; +import com.azure.core.exception.ResourceNotFoundException; +import com.azure.core.http.rest.RequestOptions; +import com.azure.core.http.rest.Response; +import com.azure.core.http.rest.RestProxy; +import com.azure.core.util.BinaryData; +import com.azure.core.util.Context; +import com.azure.core.util.FluxUtil; +import com.azure.search.documents.SearchServiceVersion; +import reactor.core.publisher.Mono; + +/** + * An instance of this class provides access to all the operations defined in DataSources. + */ +public final class DataSourcesImpl { + /** + * The proxy service used to perform REST calls. + */ + private final DataSourcesService service; + + /** + * The service client containing this operation class. + */ + private final SearchClientImpl client; + + /** + * Initializes an instance of DataSourcesImpl. + * + * @param client the instance of the service client containing this operation class. + */ + DataSourcesImpl(SearchClientImpl client) { + this.service + = RestProxy.create(DataSourcesService.class, client.getHttpPipeline(), client.getSerializerAdapter()); + this.client = client; + } + + /** + * Gets Service version. + * + * @return the serviceVersion value. + */ + public SearchServiceVersion getServiceVersion() { + return client.getServiceVersion(); + } + + /** + * The interface defining all the services for SearchClientDataSources to be used by the proxy service to perform + * REST calls. + */ + @Host("{endpoint}") + @ServiceInterface(name = "SearchClientDataSour") + public interface DataSourcesService { + @Put("/datasources('{dataSourceName}')") + @ExpectedResponses({ 200, 201 }) + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Mono> createOrUpdate(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @HeaderParam("Prefer") String prefer, + @PathParam("dataSourceName") String dataSourceName, @HeaderParam("Content-Type") String contentType, + @HeaderParam("Accept") String accept, @BodyParam("application/json") BinaryData dataSource, + RequestOptions requestOptions, Context context); + + @Put("/datasources('{dataSourceName}')") + @ExpectedResponses({ 200, 201 }) + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Response createOrUpdateSync(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @HeaderParam("Prefer") String prefer, + @PathParam("dataSourceName") String dataSourceName, @HeaderParam("Content-Type") String contentType, + @HeaderParam("Accept") String accept, @BodyParam("application/json") BinaryData dataSource, + RequestOptions requestOptions, Context context); + + @Delete("/datasources('{dataSourceName}')") + @ExpectedResponses({ 204, 404 }) + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Mono> delete(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @PathParam("dataSourceName") String dataSourceName, + @HeaderParam("Accept") String accept, RequestOptions requestOptions, Context context); + + @Delete("/datasources('{dataSourceName}')") + @ExpectedResponses({ 204, 404 }) + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Response deleteSync(@HostParam("endpoint") String endpoint, @QueryParam("api-version") String apiVersion, + @PathParam("dataSourceName") String dataSourceName, @HeaderParam("Accept") String accept, + RequestOptions requestOptions, Context context); + + @Get("/datasources('{dataSourceName}')") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Mono> get(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @PathParam("dataSourceName") String dataSourceName, + @HeaderParam("Accept") String accept, RequestOptions requestOptions, Context context); + + @Get("/datasources('{dataSourceName}')") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Response getSync(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @PathParam("dataSourceName") String dataSourceName, + @HeaderParam("Accept") String accept, RequestOptions requestOptions, Context context); + + @Get("/datasources") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Mono> list(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, + RequestOptions requestOptions, Context context); + + @Get("/datasources") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Response listSync(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, + RequestOptions requestOptions, Context context); + + @Post("/datasources") + @ExpectedResponses({ 201 }) + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Mono> create(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @HeaderParam("Content-Type") String contentType, + @HeaderParam("Accept") String accept, @BodyParam("application/json") BinaryData dataSource, + RequestOptions requestOptions, Context context); + + @Post("/datasources") + @ExpectedResponses({ 201 }) + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Response createSync(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @HeaderParam("Content-Type") String contentType, + @HeaderParam("Accept") String accept, @BodyParam("application/json") BinaryData dataSource, + RequestOptions requestOptions, Context context); + } + + /** + * Creates a new datasource or updates a datasource if it already exists. + *

Query Parameters

+ * + * + * + * + *
Query Parameters
NameTypeRequiredDescription
ignoreResetRequirementsBooleanNoIgnores cache reset requirements.
+ * You can add these to a request with {@link RequestOptions#addQueryParam} + *

Header Parameters

+ * + * + * + * + * + *
Header Parameters
NameTypeRequiredDescription
If-MatchStringNoDefines the If-Match condition. The operation will be + * performed only if the ETag on the server matches this value.
If-None-MatchStringNoDefines the If-None-Match condition. The operation will + * be performed only if the ETag on the server does not match this value.
+ * You can add these to a request with {@link RequestOptions#addHeader} + *

Request Body Schema

+ * + *
+     * {@code
+     * {
+     *     name: String (Required)
+     *     description: String (Optional)
+     *     type: String(azuresql/cosmosdb/azureblob/azuretable/mysql/adlsgen2/onelake) (Required)
+     *     credentials (Required): {
+     *         connectionString: String (Optional)
+     *     }
+     *     container (Required): {
+     *         name: String (Required)
+     *         query: String (Optional)
+     *     }
+     *     identity (Optional): {
+     *         @odata.type: String (Required)
+     *     }
+     *     dataChangeDetectionPolicy (Optional): {
+     *         @odata.type: String (Required)
+     *     }
+     *     dataDeletionDetectionPolicy (Optional): {
+     *         @odata.type: String (Required)
+     *     }
+     *     @odata.etag: String (Optional)
+     *     encryptionKey (Optional): {
+     *         keyVaultKeyName: String (Required)
+     *         keyVaultKeyVersion: String (Optional)
+     *         keyVaultUri: String (Required)
+     *         accessCredentials (Optional): {
+     *             applicationId: String (Required)
+     *             applicationSecret: String (Optional)
+     *         }
+     *         identity (Optional): (recursive schema, see identity above)
+     *     }
+     * }
+     * }
+     * 
+ * + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     name: String (Required)
+     *     description: String (Optional)
+     *     type: String(azuresql/cosmosdb/azureblob/azuretable/mysql/adlsgen2/onelake) (Required)
+     *     credentials (Required): {
+     *         connectionString: String (Optional)
+     *     }
+     *     container (Required): {
+     *         name: String (Required)
+     *         query: String (Optional)
+     *     }
+     *     identity (Optional): {
+     *         @odata.type: String (Required)
+     *     }
+     *     dataChangeDetectionPolicy (Optional): {
+     *         @odata.type: String (Required)
+     *     }
+     *     dataDeletionDetectionPolicy (Optional): {
+     *         @odata.type: String (Required)
+     *     }
+     *     @odata.etag: String (Optional)
+     *     encryptionKey (Optional): {
+     *         keyVaultKeyName: String (Required)
+     *         keyVaultKeyVersion: String (Optional)
+     *         keyVaultUri: String (Required)
+     *         accessCredentials (Optional): {
+     *             applicationId: String (Required)
+     *             applicationSecret: String (Optional)
+     *         }
+     *         identity (Optional): (recursive schema, see identity above)
+     *     }
+     * }
+     * }
+     * 
+ * + * @param dataSourceName The name of the datasource. + * @param dataSource The definition of the datasource to create or update. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return represents a datasource definition, which can be used to configure an indexer along with {@link Response} + * on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono> createOrUpdateWithResponseAsync(String dataSourceName, BinaryData dataSource, + RequestOptions requestOptions) { + final String prefer = "return=representation"; + final String contentType = "application/json"; + final String accept = "application/json"; + return FluxUtil.withContext( + context -> service.createOrUpdate(this.client.getEndpoint(), this.client.getServiceVersion().getVersion(), + prefer, dataSourceName, contentType, accept, dataSource, requestOptions, context)); + } + + /** + * Creates a new datasource or updates a datasource if it already exists. + *

Query Parameters

+ * + * + * + * + *
Query Parameters
NameTypeRequiredDescription
ignoreResetRequirementsBooleanNoIgnores cache reset requirements.
+ * You can add these to a request with {@link RequestOptions#addQueryParam} + *

Header Parameters

+ * + * + * + * + * + *
Header Parameters
NameTypeRequiredDescription
If-MatchStringNoDefines the If-Match condition. The operation will be + * performed only if the ETag on the server matches this value.
If-None-MatchStringNoDefines the If-None-Match condition. The operation will + * be performed only if the ETag on the server does not match this value.
+ * You can add these to a request with {@link RequestOptions#addHeader} + *

Request Body Schema

+ * + *
+     * {@code
+     * {
+     *     name: String (Required)
+     *     description: String (Optional)
+     *     type: String(azuresql/cosmosdb/azureblob/azuretable/mysql/adlsgen2/onelake) (Required)
+     *     credentials (Required): {
+     *         connectionString: String (Optional)
+     *     }
+     *     container (Required): {
+     *         name: String (Required)
+     *         query: String (Optional)
+     *     }
+     *     identity (Optional): {
+     *         @odata.type: String (Required)
+     *     }
+     *     dataChangeDetectionPolicy (Optional): {
+     *         @odata.type: String (Required)
+     *     }
+     *     dataDeletionDetectionPolicy (Optional): {
+     *         @odata.type: String (Required)
+     *     }
+     *     @odata.etag: String (Optional)
+     *     encryptionKey (Optional): {
+     *         keyVaultKeyName: String (Required)
+     *         keyVaultKeyVersion: String (Optional)
+     *         keyVaultUri: String (Required)
+     *         accessCredentials (Optional): {
+     *             applicationId: String (Required)
+     *             applicationSecret: String (Optional)
+     *         }
+     *         identity (Optional): (recursive schema, see identity above)
+     *     }
+     * }
+     * }
+     * 
+ * + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     name: String (Required)
+     *     description: String (Optional)
+     *     type: String(azuresql/cosmosdb/azureblob/azuretable/mysql/adlsgen2/onelake) (Required)
+     *     credentials (Required): {
+     *         connectionString: String (Optional)
+     *     }
+     *     container (Required): {
+     *         name: String (Required)
+     *         query: String (Optional)
+     *     }
+     *     identity (Optional): {
+     *         @odata.type: String (Required)
+     *     }
+     *     dataChangeDetectionPolicy (Optional): {
+     *         @odata.type: String (Required)
+     *     }
+     *     dataDeletionDetectionPolicy (Optional): {
+     *         @odata.type: String (Required)
+     *     }
+     *     @odata.etag: String (Optional)
+     *     encryptionKey (Optional): {
+     *         keyVaultKeyName: String (Required)
+     *         keyVaultKeyVersion: String (Optional)
+     *         keyVaultUri: String (Required)
+     *         accessCredentials (Optional): {
+     *             applicationId: String (Required)
+     *             applicationSecret: String (Optional)
+     *         }
+     *         identity (Optional): (recursive schema, see identity above)
+     *     }
+     * }
+     * }
+     * 
+ * + * @param dataSourceName The name of the datasource. + * @param dataSource The definition of the datasource to create or update. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return represents a datasource definition, which can be used to configure an indexer along with + * {@link Response}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Response createOrUpdateWithResponse(String dataSourceName, BinaryData dataSource, + RequestOptions requestOptions) { + final String prefer = "return=representation"; + final String contentType = "application/json"; + final String accept = "application/json"; + return service.createOrUpdateSync(this.client.getEndpoint(), this.client.getServiceVersion().getVersion(), + prefer, dataSourceName, contentType, accept, dataSource, requestOptions, Context.NONE); + } + + /** + * Deletes a datasource. + *

Header Parameters

+ * + * + * + * + * + *
Header Parameters
NameTypeRequiredDescription
If-MatchStringNoDefines the If-Match condition. The operation will be + * performed only if the ETag on the server matches this value.
If-None-MatchStringNoDefines the If-None-Match condition. The operation will + * be performed only if the ETag on the server does not match this value.
+ * You can add these to a request with {@link RequestOptions#addHeader} + * + * @param dataSourceName The name of the datasource. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return the {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono> deleteWithResponseAsync(String dataSourceName, RequestOptions requestOptions) { + final String accept = "application/json"; + return FluxUtil.withContext(context -> service.delete(this.client.getEndpoint(), + this.client.getServiceVersion().getVersion(), dataSourceName, accept, requestOptions, context)); + } + + /** + * Deletes a datasource. + *

Header Parameters

+ * + * + * + * + * + *
Header Parameters
NameTypeRequiredDescription
If-MatchStringNoDefines the If-Match condition. The operation will be + * performed only if the ETag on the server matches this value.
If-None-MatchStringNoDefines the If-None-Match condition. The operation will + * be performed only if the ETag on the server does not match this value.
+ * You can add these to a request with {@link RequestOptions#addHeader} + * + * @param dataSourceName The name of the datasource. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return the {@link Response}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Response deleteWithResponse(String dataSourceName, RequestOptions requestOptions) { + final String accept = "application/json"; + return service.deleteSync(this.client.getEndpoint(), this.client.getServiceVersion().getVersion(), + dataSourceName, accept, requestOptions, Context.NONE); + } + + /** + * Retrieves a datasource definition. + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     name: String (Required)
+     *     description: String (Optional)
+     *     type: String(azuresql/cosmosdb/azureblob/azuretable/mysql/adlsgen2/onelake) (Required)
+     *     credentials (Required): {
+     *         connectionString: String (Optional)
+     *     }
+     *     container (Required): {
+     *         name: String (Required)
+     *         query: String (Optional)
+     *     }
+     *     identity (Optional): {
+     *         @odata.type: String (Required)
+     *     }
+     *     dataChangeDetectionPolicy (Optional): {
+     *         @odata.type: String (Required)
+     *     }
+     *     dataDeletionDetectionPolicy (Optional): {
+     *         @odata.type: String (Required)
+     *     }
+     *     @odata.etag: String (Optional)
+     *     encryptionKey (Optional): {
+     *         keyVaultKeyName: String (Required)
+     *         keyVaultKeyVersion: String (Optional)
+     *         keyVaultUri: String (Required)
+     *         accessCredentials (Optional): {
+     *             applicationId: String (Required)
+     *             applicationSecret: String (Optional)
+     *         }
+     *         identity (Optional): (recursive schema, see identity above)
+     *     }
+     * }
+     * }
+     * 
+ * + * @param dataSourceName The name of the datasource. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return represents a datasource definition, which can be used to configure an indexer along with {@link Response} + * on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono> getWithResponseAsync(String dataSourceName, RequestOptions requestOptions) { + final String accept = "application/json"; + return FluxUtil.withContext(context -> service.get(this.client.getEndpoint(), + this.client.getServiceVersion().getVersion(), dataSourceName, accept, requestOptions, context)); + } + + /** + * Retrieves a datasource definition. + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     name: String (Required)
+     *     description: String (Optional)
+     *     type: String(azuresql/cosmosdb/azureblob/azuretable/mysql/adlsgen2/onelake) (Required)
+     *     credentials (Required): {
+     *         connectionString: String (Optional)
+     *     }
+     *     container (Required): {
+     *         name: String (Required)
+     *         query: String (Optional)
+     *     }
+     *     identity (Optional): {
+     *         @odata.type: String (Required)
+     *     }
+     *     dataChangeDetectionPolicy (Optional): {
+     *         @odata.type: String (Required)
+     *     }
+     *     dataDeletionDetectionPolicy (Optional): {
+     *         @odata.type: String (Required)
+     *     }
+     *     @odata.etag: String (Optional)
+     *     encryptionKey (Optional): {
+     *         keyVaultKeyName: String (Required)
+     *         keyVaultKeyVersion: String (Optional)
+     *         keyVaultUri: String (Required)
+     *         accessCredentials (Optional): {
+     *             applicationId: String (Required)
+     *             applicationSecret: String (Optional)
+     *         }
+     *         identity (Optional): (recursive schema, see identity above)
+     *     }
+     * }
+     * }
+     * 
+ * + * @param dataSourceName The name of the datasource. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return represents a datasource definition, which can be used to configure an indexer along with + * {@link Response}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Response getWithResponse(String dataSourceName, RequestOptions requestOptions) { + final String accept = "application/json"; + return service.getSync(this.client.getEndpoint(), this.client.getServiceVersion().getVersion(), dataSourceName, + accept, requestOptions, Context.NONE); + } + + /** + * Lists all datasources available for a search service. + *

Query Parameters

+ * + * + * + * + *
Query Parameters
NameTypeRequiredDescription
$selectStringNoSelects 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.
+ * You can add these to a request with {@link RequestOptions#addQueryParam} + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     value (Required): [
+     *          (Required){
+     *             name: String (Required)
+     *             description: String (Optional)
+     *             type: String(azuresql/cosmosdb/azureblob/azuretable/mysql/adlsgen2/onelake) (Required)
+     *             credentials (Required): {
+     *                 connectionString: String (Optional)
+     *             }
+     *             container (Required): {
+     *                 name: String (Required)
+     *                 query: String (Optional)
+     *             }
+     *             identity (Optional): {
+     *                 @odata.type: String (Required)
+     *             }
+     *             dataChangeDetectionPolicy (Optional): {
+     *                 @odata.type: String (Required)
+     *             }
+     *             dataDeletionDetectionPolicy (Optional): {
+     *                 @odata.type: String (Required)
+     *             }
+     *             @odata.etag: String (Optional)
+     *             encryptionKey (Optional): {
+     *                 keyVaultKeyName: String (Required)
+     *                 keyVaultKeyVersion: String (Optional)
+     *                 keyVaultUri: String (Required)
+     *                 accessCredentials (Optional): {
+     *                     applicationId: String (Required)
+     *                     applicationSecret: String (Optional)
+     *                 }
+     *                 identity (Optional): (recursive schema, see identity above)
+     *             }
+     *         }
+     *     ]
+     * }
+     * }
+     * 
+ * + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return response from a List Datasources request along with {@link Response} on successful completion of + * {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono> listWithResponseAsync(RequestOptions requestOptions) { + final String accept = "application/json"; + return FluxUtil.withContext(context -> service.list(this.client.getEndpoint(), + this.client.getServiceVersion().getVersion(), accept, requestOptions, context)); + } + + /** + * Lists all datasources available for a search service. + *

Query Parameters

+ * + * + * + * + *
Query Parameters
NameTypeRequiredDescription
$selectStringNoSelects 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.
+ * You can add these to a request with {@link RequestOptions#addQueryParam} + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     value (Required): [
+     *          (Required){
+     *             name: String (Required)
+     *             description: String (Optional)
+     *             type: String(azuresql/cosmosdb/azureblob/azuretable/mysql/adlsgen2/onelake) (Required)
+     *             credentials (Required): {
+     *                 connectionString: String (Optional)
+     *             }
+     *             container (Required): {
+     *                 name: String (Required)
+     *                 query: String (Optional)
+     *             }
+     *             identity (Optional): {
+     *                 @odata.type: String (Required)
+     *             }
+     *             dataChangeDetectionPolicy (Optional): {
+     *                 @odata.type: String (Required)
+     *             }
+     *             dataDeletionDetectionPolicy (Optional): {
+     *                 @odata.type: String (Required)
+     *             }
+     *             @odata.etag: String (Optional)
+     *             encryptionKey (Optional): {
+     *                 keyVaultKeyName: String (Required)
+     *                 keyVaultKeyVersion: String (Optional)
+     *                 keyVaultUri: String (Required)
+     *                 accessCredentials (Optional): {
+     *                     applicationId: String (Required)
+     *                     applicationSecret: String (Optional)
+     *                 }
+     *                 identity (Optional): (recursive schema, see identity above)
+     *             }
+     *         }
+     *     ]
+     * }
+     * }
+     * 
+ * + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return response from a List Datasources request along with {@link Response}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Response listWithResponse(RequestOptions requestOptions) { + final String accept = "application/json"; + return service.listSync(this.client.getEndpoint(), this.client.getServiceVersion().getVersion(), accept, + requestOptions, Context.NONE); + } + + /** + * Creates a new datasource. + *

Request Body Schema

+ * + *
+     * {@code
+     * {
+     *     name: String (Required)
+     *     description: String (Optional)
+     *     type: String(azuresql/cosmosdb/azureblob/azuretable/mysql/adlsgen2/onelake) (Required)
+     *     credentials (Required): {
+     *         connectionString: String (Optional)
+     *     }
+     *     container (Required): {
+     *         name: String (Required)
+     *         query: String (Optional)
+     *     }
+     *     identity (Optional): {
+     *         @odata.type: String (Required)
+     *     }
+     *     dataChangeDetectionPolicy (Optional): {
+     *         @odata.type: String (Required)
+     *     }
+     *     dataDeletionDetectionPolicy (Optional): {
+     *         @odata.type: String (Required)
+     *     }
+     *     @odata.etag: String (Optional)
+     *     encryptionKey (Optional): {
+     *         keyVaultKeyName: String (Required)
+     *         keyVaultKeyVersion: String (Optional)
+     *         keyVaultUri: String (Required)
+     *         accessCredentials (Optional): {
+     *             applicationId: String (Required)
+     *             applicationSecret: String (Optional)
+     *         }
+     *         identity (Optional): (recursive schema, see identity above)
+     *     }
+     * }
+     * }
+     * 
+ * + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     name: String (Required)
+     *     description: String (Optional)
+     *     type: String(azuresql/cosmosdb/azureblob/azuretable/mysql/adlsgen2/onelake) (Required)
+     *     credentials (Required): {
+     *         connectionString: String (Optional)
+     *     }
+     *     container (Required): {
+     *         name: String (Required)
+     *         query: String (Optional)
+     *     }
+     *     identity (Optional): {
+     *         @odata.type: String (Required)
+     *     }
+     *     dataChangeDetectionPolicy (Optional): {
+     *         @odata.type: String (Required)
+     *     }
+     *     dataDeletionDetectionPolicy (Optional): {
+     *         @odata.type: String (Required)
+     *     }
+     *     @odata.etag: String (Optional)
+     *     encryptionKey (Optional): {
+     *         keyVaultKeyName: String (Required)
+     *         keyVaultKeyVersion: String (Optional)
+     *         keyVaultUri: String (Required)
+     *         accessCredentials (Optional): {
+     *             applicationId: String (Required)
+     *             applicationSecret: String (Optional)
+     *         }
+     *         identity (Optional): (recursive schema, see identity above)
+     *     }
+     * }
+     * }
+     * 
+ * + * @param dataSource The definition of the datasource to create. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return represents a datasource definition, which can be used to configure an indexer along with {@link Response} + * on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono> createWithResponseAsync(BinaryData dataSource, RequestOptions requestOptions) { + final String contentType = "application/json"; + final String accept = "application/json"; + return FluxUtil.withContext(context -> service.create(this.client.getEndpoint(), + this.client.getServiceVersion().getVersion(), contentType, accept, dataSource, requestOptions, context)); + } + + /** + * Creates a new datasource. + *

Request Body Schema

+ * + *
+     * {@code
+     * {
+     *     name: String (Required)
+     *     description: String (Optional)
+     *     type: String(azuresql/cosmosdb/azureblob/azuretable/mysql/adlsgen2/onelake) (Required)
+     *     credentials (Required): {
+     *         connectionString: String (Optional)
+     *     }
+     *     container (Required): {
+     *         name: String (Required)
+     *         query: String (Optional)
+     *     }
+     *     identity (Optional): {
+     *         @odata.type: String (Required)
+     *     }
+     *     dataChangeDetectionPolicy (Optional): {
+     *         @odata.type: String (Required)
+     *     }
+     *     dataDeletionDetectionPolicy (Optional): {
+     *         @odata.type: String (Required)
+     *     }
+     *     @odata.etag: String (Optional)
+     *     encryptionKey (Optional): {
+     *         keyVaultKeyName: String (Required)
+     *         keyVaultKeyVersion: String (Optional)
+     *         keyVaultUri: String (Required)
+     *         accessCredentials (Optional): {
+     *             applicationId: String (Required)
+     *             applicationSecret: String (Optional)
+     *         }
+     *         identity (Optional): (recursive schema, see identity above)
+     *     }
+     * }
+     * }
+     * 
+ * + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     name: String (Required)
+     *     description: String (Optional)
+     *     type: String(azuresql/cosmosdb/azureblob/azuretable/mysql/adlsgen2/onelake) (Required)
+     *     credentials (Required): {
+     *         connectionString: String (Optional)
+     *     }
+     *     container (Required): {
+     *         name: String (Required)
+     *         query: String (Optional)
+     *     }
+     *     identity (Optional): {
+     *         @odata.type: String (Required)
+     *     }
+     *     dataChangeDetectionPolicy (Optional): {
+     *         @odata.type: String (Required)
+     *     }
+     *     dataDeletionDetectionPolicy (Optional): {
+     *         @odata.type: String (Required)
+     *     }
+     *     @odata.etag: String (Optional)
+     *     encryptionKey (Optional): {
+     *         keyVaultKeyName: String (Required)
+     *         keyVaultKeyVersion: String (Optional)
+     *         keyVaultUri: String (Required)
+     *         accessCredentials (Optional): {
+     *             applicationId: String (Required)
+     *             applicationSecret: String (Optional)
+     *         }
+     *         identity (Optional): (recursive schema, see identity above)
+     *     }
+     * }
+     * }
+     * 
+ * + * @param dataSource The definition of the datasource to create. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return represents a datasource definition, which can be used to configure an indexer along with + * {@link Response}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Response createWithResponse(BinaryData dataSource, RequestOptions requestOptions) { + final String contentType = "application/json"; + final String accept = "application/json"; + return service.createSync(this.client.getEndpoint(), this.client.getServiceVersion().getVersion(), contentType, + accept, dataSource, requestOptions, Context.NONE); + } +} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/implementation/DocumentsImpl.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/implementation/DocumentsImpl.java index e0fdfc6cf631..c863b2355ef4 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/implementation/DocumentsImpl.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/implementation/DocumentsImpl.java @@ -1,8 +1,7 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) TypeSpec Code Generator. + package com.azure.search.documents.implementation; import com.azure.core.annotation.BodyParam; @@ -18,32 +17,23 @@ import com.azure.core.annotation.ServiceInterface; import com.azure.core.annotation.ServiceMethod; import com.azure.core.annotation.UnexpectedResponseExceptionType; +import com.azure.core.exception.ClientAuthenticationException; +import com.azure.core.exception.HttpResponseException; +import com.azure.core.exception.ResourceModifiedException; +import com.azure.core.exception.ResourceNotFoundException; +import com.azure.core.http.rest.RequestOptions; import com.azure.core.http.rest.Response; import com.azure.core.http.rest.RestProxy; +import com.azure.core.util.BinaryData; import com.azure.core.util.Context; import com.azure.core.util.FluxUtil; -import com.azure.search.documents.implementation.models.AutocompleteRequest; -import com.azure.search.documents.implementation.models.ErrorResponseException; -import com.azure.search.documents.implementation.models.IndexBatch; -import com.azure.search.documents.implementation.models.RequestOptions; -import com.azure.search.documents.implementation.models.SearchDocumentsResult; -import com.azure.search.documents.implementation.models.SearchRequest; -import com.azure.search.documents.implementation.models.SuggestDocumentsResult; -import com.azure.search.documents.implementation.models.SuggestRequest; -import com.azure.search.documents.models.AutocompleteResult; -import com.azure.search.documents.models.IndexDocumentsResult; -import java.util.List; -import java.util.Map; -import java.util.Objects; -import java.util.UUID; -import java.util.stream.Collectors; +import com.azure.search.documents.SearchServiceVersion; import reactor.core.publisher.Mono; /** * An instance of this class provides access to all the operations defined in Documents. */ public final class DocumentsImpl { - /** * The proxy service used to perform REST calls. */ @@ -52,819 +42,2180 @@ public final class DocumentsImpl { /** * The service client containing this operation class. */ - private final SearchIndexClientImpl client; + private final SearchClientImpl client; /** * Initializes an instance of DocumentsImpl. - * + * * @param client the instance of the service client containing this operation class. */ - DocumentsImpl(SearchIndexClientImpl client) { + DocumentsImpl(SearchClientImpl client) { this.service = RestProxy.create(DocumentsService.class, client.getHttpPipeline(), client.getSerializerAdapter()); this.client = client; } /** - * The interface defining all the services for SearchIndexClientDocuments to be used by the proxy service to perform - * REST calls. + * Gets Service version. + * + * @return the serviceVersion value. + */ + public SearchServiceVersion getServiceVersion() { + return client.getServiceVersion(); + } + + /** + * The interface defining all the services for SearchClientDocuments to be used by the proxy service to perform REST + * calls. */ - @Host("{endpoint}/indexes('{indexName}')") - @ServiceInterface(name = "SearchIndexClientDoc") + @Host("{endpoint}") + @ServiceInterface(name = "SearchClientDocument") public interface DocumentsService { + @Get("/indexes('{indexName}')/docs/$count") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Mono> count(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @PathParam("indexName") String indexName, + @HeaderParam("Accept") String accept, RequestOptions requestOptions, Context context); - @Get("/docs/$count") + @Get("/indexes('{indexName}')/docs/$count") @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(ErrorResponseException.class) - Mono> count(@HostParam("endpoint") String endpoint, @HostParam("indexName") String indexName, - @HeaderParam("x-ms-client-request-id") UUID xMsClientRequestId, - @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, Context context); + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Response countSync(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @PathParam("indexName") String indexName, + @HeaderParam("Accept") String accept, RequestOptions requestOptions, Context context); - @Get("/docs/$count") + @Get("/indexes('{indexName}')/docs") @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(ErrorResponseException.class) - Response countSync(@HostParam("endpoint") String endpoint, @HostParam("indexName") String indexName, - @HeaderParam("x-ms-client-request-id") UUID xMsClientRequestId, - @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, Context context); + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Mono> searchGet(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @PathParam("indexName") String indexName, + @HeaderParam("Accept") String accept, RequestOptions requestOptions, Context context); - @Post("/docs/search.post.search") + @Get("/indexes('{indexName}')/docs") @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(ErrorResponseException.class) - Mono> searchPost(@HostParam("endpoint") String endpoint, - @HostParam("indexName") String indexName, @QueryParam("api-version") String apiVersion, - @HeaderParam("x-ms-client-request-id") UUID xMsClientRequestId, @HeaderParam("Accept") String accept, - @BodyParam("application/json") SearchRequest searchRequest, Context context); + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Response searchGetSync(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @PathParam("indexName") String indexName, + @HeaderParam("Accept") String accept, RequestOptions requestOptions, Context context); - @Post("/docs/search.post.search") + @Post("/indexes('{indexName}')/docs/search.post.search") @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(ErrorResponseException.class) - Response searchPostSync(@HostParam("endpoint") String endpoint, - @HostParam("indexName") String indexName, @QueryParam("api-version") String apiVersion, - @HeaderParam("x-ms-client-request-id") UUID xMsClientRequestId, @HeaderParam("Accept") String accept, - @BodyParam("application/json") SearchRequest searchRequest, Context context); + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Mono> searchPost(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @PathParam("indexName") String indexName, + @HeaderParam("Content-Type") String contentType, @HeaderParam("Accept") String accept, + @BodyParam("application/json") BinaryData searchRequest, RequestOptions requestOptions, Context context); - @Get("/docs('{key}')") + @Post("/indexes('{indexName}')/docs/search.post.search") @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(ErrorResponseException.class) - Mono>> get(@HostParam("endpoint") String endpoint, - @HostParam("indexName") String indexName, @PathParam("key") String key, - @QueryParam("$select") String selectedFields, @QueryParam("api-version") String apiVersion, - @HeaderParam("x-ms-client-request-id") UUID xMsClientRequestId, @HeaderParam("Accept") String accept, - Context context); + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Response searchPostSync(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @PathParam("indexName") String indexName, + @HeaderParam("Content-Type") String contentType, @HeaderParam("Accept") String accept, + @BodyParam("application/json") BinaryData searchRequest, RequestOptions requestOptions, Context context); - @Get("/docs('{key}')") + @Get("/indexes('{indexName}')/docs('{key}')") @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(ErrorResponseException.class) - Response> getSync(@HostParam("endpoint") String endpoint, - @HostParam("indexName") String indexName, @PathParam("key") String key, - @QueryParam("$select") String selectedFields, @QueryParam("api-version") String apiVersion, - @HeaderParam("x-ms-client-request-id") UUID xMsClientRequestId, @HeaderParam("Accept") String accept, - Context context); + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Mono> get(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @PathParam("key") String key, + @PathParam("indexName") String indexName, @HeaderParam("Accept") String accept, + RequestOptions requestOptions, Context context); + + @Get("/indexes('{indexName}')/docs('{key}')") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Response getSync(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @PathParam("key") String key, + @PathParam("indexName") String indexName, @HeaderParam("Accept") String accept, + RequestOptions requestOptions, Context context); - @Post("/docs/search.post.suggest") + @Get("/indexes('{indexName}')/docs/search.suggest") @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(ErrorResponseException.class) - Mono> suggestPost(@HostParam("endpoint") String endpoint, - @HostParam("indexName") String indexName, @QueryParam("api-version") String apiVersion, - @HeaderParam("x-ms-client-request-id") UUID xMsClientRequestId, @HeaderParam("Accept") String accept, - @BodyParam("application/json") SuggestRequest suggestRequest, Context context); + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Mono> suggestGet(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @QueryParam("search") String searchText, + @QueryParam("suggesterName") String suggesterName, @PathParam("indexName") String indexName, + @HeaderParam("Accept") String accept, RequestOptions requestOptions, Context context); - @Post("/docs/search.post.suggest") + @Get("/indexes('{indexName}')/docs/search.suggest") @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(ErrorResponseException.class) - Response suggestPostSync(@HostParam("endpoint") String endpoint, - @HostParam("indexName") String indexName, @QueryParam("api-version") String apiVersion, - @HeaderParam("x-ms-client-request-id") UUID xMsClientRequestId, @HeaderParam("Accept") String accept, - @BodyParam("application/json") SuggestRequest suggestRequest, Context context); + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Response suggestGetSync(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @QueryParam("search") String searchText, + @QueryParam("suggesterName") String suggesterName, @PathParam("indexName") String indexName, + @HeaderParam("Accept") String accept, RequestOptions requestOptions, Context context); - @Post("/docs/search.index") + @Post("/indexes('{indexName}')/docs/search.post.suggest") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Mono> suggestPost(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @PathParam("indexName") String indexName, + @HeaderParam("Content-Type") String contentType, @HeaderParam("Accept") String accept, + @BodyParam("application/json") BinaryData suggestRequest, RequestOptions requestOptions, Context context); + + @Post("/indexes('{indexName}')/docs/search.post.suggest") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Response suggestPostSync(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @PathParam("indexName") String indexName, + @HeaderParam("Content-Type") String contentType, @HeaderParam("Accept") String accept, + @BodyParam("application/json") BinaryData suggestRequest, RequestOptions requestOptions, Context context); + + @Post("/indexes('{indexName}')/docs/search.index") @ExpectedResponses({ 200, 207 }) - @UnexpectedResponseExceptionType(ErrorResponseException.class) - Mono> index(@HostParam("endpoint") String endpoint, - @HostParam("indexName") String indexName, @QueryParam("api-version") String apiVersion, - @HeaderParam("x-ms-client-request-id") UUID xMsClientRequestId, @HeaderParam("Accept") String accept, - @BodyParam("application/json") IndexBatch batch, Context context); + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Mono> index(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @PathParam("indexName") String indexName, + @HeaderParam("Content-Type") String contentType, @HeaderParam("Accept") String accept, + @BodyParam("application/json") BinaryData batch, RequestOptions requestOptions, Context context); - @Post("/docs/search.index") + @Post("/indexes('{indexName}')/docs/search.index") @ExpectedResponses({ 200, 207 }) - @UnexpectedResponseExceptionType(ErrorResponseException.class) - Response indexSync(@HostParam("endpoint") String endpoint, - @HostParam("indexName") String indexName, @QueryParam("api-version") String apiVersion, - @HeaderParam("x-ms-client-request-id") UUID xMsClientRequestId, @HeaderParam("Accept") String accept, - @BodyParam("application/json") IndexBatch batch, Context context); + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Response indexSync(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @PathParam("indexName") String indexName, + @HeaderParam("Content-Type") String contentType, @HeaderParam("Accept") String accept, + @BodyParam("application/json") BinaryData batch, RequestOptions requestOptions, Context context); - @Post("/docs/search.post.autocomplete") + @Get("/indexes('{indexName}')/docs/search.autocomplete") @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(ErrorResponseException.class) - Mono> autocompletePost(@HostParam("endpoint") String endpoint, - @HostParam("indexName") String indexName, @HeaderParam("x-ms-client-request-id") UUID xMsClientRequestId, - @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, - @BodyParam("application/json") AutocompleteRequest autocompleteRequest, Context context); + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Mono> autocompleteGet(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @QueryParam("search") String searchText, + @QueryParam("suggesterName") String suggesterName, @PathParam("indexName") String indexName, + @HeaderParam("Accept") String accept, RequestOptions requestOptions, Context context); - @Post("/docs/search.post.autocomplete") + @Get("/indexes('{indexName}')/docs/search.autocomplete") @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(ErrorResponseException.class) - Response autocompletePostSync(@HostParam("endpoint") String endpoint, - @HostParam("indexName") String indexName, @HeaderParam("x-ms-client-request-id") UUID xMsClientRequestId, - @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, - @BodyParam("application/json") AutocompleteRequest autocompleteRequest, Context context); - } - - /** - * Queries the number of documents in the index. - * - * @param requestOptions Parameter group. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the response body along with {@link Response} on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> countWithResponseAsync(RequestOptions requestOptions) { - return FluxUtil.withContext(context -> countWithResponseAsync(requestOptions, context)); - } + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Response autocompleteGetSync(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @QueryParam("search") String searchText, + @QueryParam("suggesterName") String suggesterName, @PathParam("indexName") String indexName, + @HeaderParam("Accept") String accept, RequestOptions requestOptions, Context context); - /** - * Queries the number of documents in the index. - * - * @param requestOptions Parameter group. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the response body along with {@link Response} on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> countWithResponseAsync(RequestOptions requestOptions, Context context) { - final String accept = "application/json; odata.metadata=none"; - UUID xMsClientRequestIdInternal = null; - if (requestOptions != null) { - xMsClientRequestIdInternal = requestOptions.getXMsClientRequestId(); - } - UUID xMsClientRequestId = xMsClientRequestIdInternal; - return service.count(this.client.getEndpoint(), this.client.getIndexName(), xMsClientRequestId, - this.client.getApiVersion(), accept, context); - } - - /** - * Queries the number of documents in the index. - * - * @param requestOptions Parameter group. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the response body on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono countAsync(RequestOptions requestOptions) { - return countWithResponseAsync(requestOptions).flatMap(res -> Mono.justOrEmpty(res.getValue())); - } + @Post("/indexes('{indexName}')/docs/search.post.autocomplete") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Mono> autocompletePost(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @PathParam("indexName") String indexName, + @HeaderParam("Content-Type") String contentType, @HeaderParam("Accept") String accept, + @BodyParam("application/json") BinaryData autocompleteRequest, RequestOptions requestOptions, + Context context); - /** - * Queries the number of documents in the index. - * - * @param requestOptions Parameter group. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the response body on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono countAsync(RequestOptions requestOptions, Context context) { - return countWithResponseAsync(requestOptions, context).flatMap(res -> Mono.justOrEmpty(res.getValue())); + @Post("/indexes('{indexName}')/docs/search.post.autocomplete") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Response autocompletePostSync(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @PathParam("indexName") String indexName, + @HeaderParam("Content-Type") String contentType, @HeaderParam("Accept") String accept, + @BodyParam("application/json") BinaryData autocompleteRequest, RequestOptions requestOptions, + Context context); } /** * Queries the number of documents in the index. - * - * @param requestOptions Parameter group. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the response body along with {@link Response}. + *

Response Body Schema

+ * + *
+     * {@code
+     * int
+     * }
+     * 
+ * + * @param indexName The name of the index. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return a 32-bit integer along with {@link Response} on successful completion of {@link Mono}. */ @ServiceMethod(returns = ReturnType.SINGLE) - public Response countWithResponse(RequestOptions requestOptions, Context context) { - final String accept = "application/json; odata.metadata=none"; - UUID xMsClientRequestIdInternal = null; - if (requestOptions != null) { - xMsClientRequestIdInternal = requestOptions.getXMsClientRequestId(); - } - UUID xMsClientRequestId = xMsClientRequestIdInternal; - return service.countSync(this.client.getEndpoint(), this.client.getIndexName(), xMsClientRequestId, - this.client.getApiVersion(), accept, context); + public Mono> countWithResponseAsync(String indexName, RequestOptions requestOptions) { + final String accept = "text/plain"; + return FluxUtil.withContext(context -> service.count(this.client.getEndpoint(), + this.client.getServiceVersion().getVersion(), indexName, accept, requestOptions, context)); } /** * Queries the number of documents in the index. - * - * @param requestOptions Parameter group. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the response. + *

Response Body Schema

+ * + *
+     * {@code
+     * int
+     * }
+     * 
+ * + * @param indexName The name of the index. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return a 32-bit integer along with {@link Response}. */ @ServiceMethod(returns = ReturnType.SINGLE) - public long count(RequestOptions requestOptions) { - return countWithResponse(requestOptions, Context.NONE).getValue(); + public Response countWithResponse(String indexName, RequestOptions requestOptions) { + final String accept = "text/plain"; + return service.countSync(this.client.getEndpoint(), this.client.getServiceVersion().getVersion(), indexName, + accept, requestOptions, Context.NONE); } /** * Searches for documents in the index. - * - * @param searchRequest The definition of the Search request. - * @param requestOptions Parameter group. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + *

Query Parameters

+ * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + *
Query Parameters
NameTypeRequiredDescription
searchStringNoA full-text search query expression; Use "*" or omit this + * parameter to match + * all documents.
$countBooleanNoA 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.
facetList<String>NoThe 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. Call {@link RequestOptions#addQueryParam} to add string to array.
$filterStringNoThe OData $filter expression to apply to the search + * query.
highlightList<String>NoThe list of field names to use for hit + * highlights. Only searchable fields can + * be used for hit highlighting. In the form of "," separated string.
highlightPostTagStringNoA string tag that is appended to hit highlights. Must + * be set with + * highlightPreTag. Default is &lt;/em&gt;.
highlightPreTagStringNoA string tag that is prepended to hit highlights. Must + * be set with + * highlightPostTag. Default is &lt;em&gt;.
minimumCoverageDoubleNoA 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.
$orderbyList<String>NoThe 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. In the form of "," separated string.
queryTypeStringNoA value that specifies the syntax of the search query. The + * default is 'simple'. + * Use 'full' if your query uses the Lucene query syntax. Allowed values: "simple", "full", "semantic".
scoringParameterList<String>NoThe 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). Call + * {@link RequestOptions#addQueryParam} to add string to array.
scoringProfileStringNoThe name of a scoring profile to evaluate match scores + * for matching documents + * in order to sort the results.
searchFieldsList<String>NoThe 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. In the form of "," separated string.
searchModeStringNoA value that specifies whether any or all of the search + * terms must be matched + * in order to count the document as a match. Allowed values: "any", "all".
scoringStatisticsStringNoA value that specifies whether we want to calculate + * scoring statistics (such as + * document frequency) globally for more consistent scoring, or locally, for lower + * latency. Allowed values: "local", "global".
sessionIdStringNoA 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.
$selectList<String>NoThe list of fields to retrieve. If unspecified, all + * fields marked as + * retrievable in the schema are included. In the form of "," separated string.
$skipIntegerNoThe 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.
$topIntegerNoThe 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.
semanticConfigurationStringNoThe name of the semantic configuration that lists + * which fields should be used + * for semantic ranking, captions, highlights, and answers
semanticErrorHandlingStringNoAllows the user to choose whether a semantic call + * should fail completely, or to + * return partial results (default). Allowed values: "partial", "fail".
semanticMaxWaitInMillisecondsIntegerNoAllows the user to set an upper bound on + * the amount of time it takes for + * semantic enrichment to finish processing before the request fails.
answersStringNoThis 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-<number of answers>` 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-<confidence 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-<number of maximum character length>', + * such as 'extractive|maxcharlength-600'. Allowed values: "none", "extractive".
captionsStringNoThis 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-<true/false>` 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-<number of maximum + * character length>', such as 'extractive|maxcharlength-600'. Allowed values: "none", "extractive".
semanticQueryStringNoAllows 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.
queryRewritesStringNoWhen 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-<number of rewrites>` option, such as + * `generative|count-3`. Defaults to `None`. This parameter is only valid if the + * query type is `semantic`. Allowed values: "none", "generative".
debugStringNoEnables a debugging tool that can be used to further explore your + * search + * results. Allowed values: "disabled", "semantic", "vector", "queryRewrites", "all".
queryLanguageStringNoThe language of the query. Allowed values: "none", + * "en-us", "en-gb", "en-in", "en-ca", "en-au", "fr-fr", "fr-ca", "de-de", "es-es", "es-mx", "zh-cn", "zh-tw", + * "pt-br", "pt-pt", "it-it", "ja-jp", "ko-kr", "ru-ru", "cs-cz", "nl-be", "nl-nl", "hu-hu", "pl-pl", "sv-se", + * "tr-tr", "hi-in", "ar-sa", "ar-eg", "ar-ma", "ar-kw", "ar-jo", "da-dk", "no-no", "bg-bg", "hr-hr", "hr-ba", + * "ms-my", "ms-bn", "sl-sl", "ta-in", "vi-vn", "el-gr", "ro-ro", "is-is", "id-id", "th-th", "lt-lt", "uk-ua", + * "lv-lv", "et-ee", "ca-es", "fi-fi", "sr-ba", "sr-me", "sr-rs", "sk-sk", "nb-no", "hy-am", "bn-in", "eu-es", + * "gl-es", "gu-in", "he-il", "ga-ie", "kn-in", "ml-in", "mr-in", "fa-ae", "pa-in", "te-in", "ur-pk".
spellerStringNoImprove search recall by spell-correcting individual search + * query terms. Allowed values: "none", "lexicon".
semanticFieldsList<String>NoThe list of field names used for semantic + * ranking. In the form of "," separated string.
+ * You can add these to a request with {@link RequestOptions#addQueryParam} + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     @odata.count: Long (Optional)
+     *     @search.coverage: Double (Optional)
+     *     @search.facets (Optional): {
+     *         String (Required): [
+     *              (Required){
+     *                 count: Long (Optional)
+     *                 @search.facets (Optional): {
+     *                     String (Required): [
+     *                         (recursive schema, see above)
+     *                     ]
+     *                 }
+     *                 sum: Long (Optional)
+     *                  (Optional): {
+     *                     String: BinaryData (Required)
+     *                 }
+     *             }
+     *         ]
+     *     }
+     *     @search.answers (Optional): [
+     *          (Optional){
+     *             score: Double (Optional)
+     *             key: String (Optional)
+     *             text: String (Optional)
+     *             highlights: String (Optional)
+     *              (Optional): {
+     *                 String: BinaryData (Required)
+     *             }
+     *         }
+     *     ]
+     *     @search.debug (Optional): {
+     *         queryRewrites (Optional): {
+     *             text (Optional): {
+     *                 inputQuery: String (Optional)
+     *                 rewrites (Optional): [
+     *                     String (Optional)
+     *                 ]
+     *             }
+     *             vectors (Optional): [
+     *                 (recursive schema, see above)
+     *             ]
+     *         }
+     *     }
+     *     @search.nextPageParameters (Optional): {
+     *         count: Boolean (Optional)
+     *         facets (Optional): [
+     *             String (Optional)
+     *         ]
+     *         filter: String (Optional)
+     *         highlight: String (Optional)
+     *         highlightPostTag: String (Optional)
+     *         highlightPreTag: String (Optional)
+     *         minimumCoverage: Double (Optional)
+     *         orderby: String (Optional)
+     *         queryType: String(simple/full/semantic) (Optional)
+     *         scoringStatistics: String(local/global) (Optional)
+     *         sessionId: String (Optional)
+     *         scoringParameters (Optional): [
+     *             String (Optional)
+     *         ]
+     *         scoringProfile: String (Optional)
+     *         debug: String(disabled/semantic/vector/queryRewrites/all) (Optional)
+     *         search: String (Optional)
+     *         searchFields: String (Optional)
+     *         searchMode: String(any/all) (Optional)
+     *         queryLanguage: String(none/en-us/en-gb/en-in/en-ca/en-au/fr-fr/fr-ca/de-de/es-es/es-mx/zh-cn/zh-tw/pt-br/pt-pt/it-it/ja-jp/ko-kr/ru-ru/cs-cz/nl-be/nl-nl/hu-hu/pl-pl/sv-se/tr-tr/hi-in/ar-sa/ar-eg/ar-ma/ar-kw/ar-jo/da-dk/no-no/bg-bg/hr-hr/hr-ba/ms-my/ms-bn/sl-sl/ta-in/vi-vn/el-gr/ro-ro/is-is/id-id/th-th/lt-lt/uk-ua/lv-lv/et-ee/ca-es/fi-fi/sr-ba/sr-me/sr-rs/sk-sk/nb-no/hy-am/bn-in/eu-es/gl-es/gu-in/he-il/ga-ie/kn-in/ml-in/mr-in/fa-ae/pa-in/te-in/ur-pk) (Optional)
+     *         speller: String(none/lexicon) (Optional)
+     *         select: String (Optional)
+     *         skip: Integer (Optional)
+     *         top: Integer (Optional)
+     *         semanticConfiguration: String (Optional)
+     *         semanticErrorHandling: String(partial/fail) (Optional)
+     *         semanticMaxWaitInMilliseconds: Integer (Optional)
+     *         semanticQuery: String (Optional)
+     *         answers: String(none/extractive) (Optional)
+     *         captions: String(none/extractive) (Optional)
+     *         queryRewrites: String(none/generative) (Optional)
+     *         semanticFields: String (Optional)
+     *         vectorQueries (Optional): [
+     *              (Optional){
+     *                 kind: String(vector/text/imageUrl/imageBinary) (Required)
+     *                 k: Integer (Optional)
+     *                 fields: String (Optional)
+     *                 exhaustive: Boolean (Optional)
+     *                 oversampling: Double (Optional)
+     *                 weight: Double (Optional)
+     *                 threshold (Optional): {
+     *                     kind: String(vectorSimilarity/searchScore) (Required)
+     *                 }
+     *                 filterOverride: String (Optional)
+     *             }
+     *         ]
+     *         vectorFilterMode: String(postFilter/preFilter) (Optional)
+     *         hybridSearch (Optional): {
+     *             maxTextRecallSize: Integer (Optional)
+     *             countAndFacetMode: String(countRetrievableResults/countAllResults) (Optional)
+     *         }
+     *     }
+     *     value (Required): [
+     *          (Required){
+     *             @search.score: double (Required)
+     *             @search.rerankerScore: Double (Optional)
+     *             @search.highlights (Optional): {
+     *                 String (Required): [
+     *                     String (Required)
+     *                 ]
+     *             }
+     *             @search.captions (Optional): [
+     *                  (Optional){
+     *                     text: String (Optional)
+     *                     highlights: String (Optional)
+     *                      (Optional): {
+     *                         String: BinaryData (Required)
+     *                     }
+     *                 }
+     *             ]
+     *             @search.documentDebugInfo (Optional): [
+     *                  (Optional){
+     *                     semantic (Optional): {
+     *                         titleField (Optional): {
+     *                             name: String (Optional)
+     *                             state: String(used/unused/partial) (Optional)
+     *                         }
+     *                         contentFields (Optional): [
+     *                             (recursive schema, see above)
+     *                         ]
+     *                         keywordFields (Optional): [
+     *                             (recursive schema, see above)
+     *                         ]
+     *                         rerankerInput (Optional): {
+     *                             title: String (Optional)
+     *                             content: String (Optional)
+     *                             keywords: String (Optional)
+     *                         }
+     *                     }
+     *                     vectors (Optional): {
+     *                         subscores (Optional): {
+     *                             text (Optional): {
+     *                                 searchScore: Double (Optional)
+     *                             }
+     *                             vectors (Optional): [
+     *                                  (Optional){
+     *                                     String (Required): {
+     *                                         searchScore: Double (Optional)
+     *                                         vectorSimilarity: Double (Optional)
+     *                                     }
+     *                                 }
+     *                             ]
+     *                             documentBoost: Double (Optional)
+     *                         }
+     *                     }
+     *                 }
+     *             ]
+     *              (Optional): {
+     *                 String: BinaryData (Required)
+     *             }
+     *         }
+     *     ]
+     *     @odata.nextLink: String (Optional)
+     *     @search.semanticPartialResponseReason: String(maxWaitExceeded/capacityOverloaded/transient) (Optional)
+     *     @search.semanticPartialResponseType: String(baseResults/rerankedResults) (Optional)
+     *     @search.semanticQueryRewritesResultType: String(originalQueryOnly) (Optional)
+     * }
+     * }
+     * 
+ * + * @param indexName The name of the index. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. * @return response containing search results from an index along with {@link Response} on successful completion of * {@link Mono}. */ @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> searchPostWithResponseAsync(SearchRequest searchRequest, - RequestOptions requestOptions) { - return FluxUtil.withContext(context -> searchPostWithResponseAsync(searchRequest, requestOptions, context)); + public Mono> searchGetWithResponseAsync(String indexName, RequestOptions requestOptions) { + final String accept = "application/json"; + return FluxUtil.withContext(context -> service.searchGet(this.client.getEndpoint(), + this.client.getServiceVersion().getVersion(), indexName, accept, requestOptions, context)); } /** * Searches for documents in the index. - * - * @param searchRequest The definition of the Search request. - * @param requestOptions Parameter group. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return response containing search results from an index along with {@link Response} on successful completion of - * {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> searchPostWithResponseAsync(SearchRequest searchRequest, - RequestOptions requestOptions, Context context) { - final String accept = "application/json; odata.metadata=none"; - UUID xMsClientRequestIdInternal = null; - if (requestOptions != null) { - xMsClientRequestIdInternal = requestOptions.getXMsClientRequestId(); - } - UUID xMsClientRequestId = xMsClientRequestIdInternal; - return service.searchPost(this.client.getEndpoint(), this.client.getIndexName(), this.client.getApiVersion(), - xMsClientRequestId, accept, searchRequest, context); - } - - /** - * Searches for documents in the index. - * - * @param searchRequest The definition of the Search request. - * @param requestOptions Parameter group. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return response containing search results from an index on successful completion of {@link Mono}. + *

Query Parameters

+ * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + *
Query Parameters
NameTypeRequiredDescription
searchStringNoA full-text search query expression; Use "*" or omit this + * parameter to match + * all documents.
$countBooleanNoA 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.
facetList<String>NoThe 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. Call {@link RequestOptions#addQueryParam} to add string to array.
$filterStringNoThe OData $filter expression to apply to the search + * query.
highlightList<String>NoThe list of field names to use for hit + * highlights. Only searchable fields can + * be used for hit highlighting. In the form of "," separated string.
highlightPostTagStringNoA string tag that is appended to hit highlights. Must + * be set with + * highlightPreTag. Default is &lt;/em&gt;.
highlightPreTagStringNoA string tag that is prepended to hit highlights. Must + * be set with + * highlightPostTag. Default is &lt;em&gt;.
minimumCoverageDoubleNoA 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.
$orderbyList<String>NoThe 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. In the form of "," separated string.
queryTypeStringNoA value that specifies the syntax of the search query. The + * default is 'simple'. + * Use 'full' if your query uses the Lucene query syntax. Allowed values: "simple", "full", "semantic".
scoringParameterList<String>NoThe 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). Call + * {@link RequestOptions#addQueryParam} to add string to array.
scoringProfileStringNoThe name of a scoring profile to evaluate match scores + * for matching documents + * in order to sort the results.
searchFieldsList<String>NoThe 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. In the form of "," separated string.
searchModeStringNoA value that specifies whether any or all of the search + * terms must be matched + * in order to count the document as a match. Allowed values: "any", "all".
scoringStatisticsStringNoA value that specifies whether we want to calculate + * scoring statistics (such as + * document frequency) globally for more consistent scoring, or locally, for lower + * latency. Allowed values: "local", "global".
sessionIdStringNoA 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.
$selectList<String>NoThe list of fields to retrieve. If unspecified, all + * fields marked as + * retrievable in the schema are included. In the form of "," separated string.
$skipIntegerNoThe 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.
$topIntegerNoThe 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.
semanticConfigurationStringNoThe name of the semantic configuration that lists + * which fields should be used + * for semantic ranking, captions, highlights, and answers
semanticErrorHandlingStringNoAllows the user to choose whether a semantic call + * should fail completely, or to + * return partial results (default). Allowed values: "partial", "fail".
semanticMaxWaitInMillisecondsIntegerNoAllows the user to set an upper bound on + * the amount of time it takes for + * semantic enrichment to finish processing before the request fails.
answersStringNoThis 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-<number of answers>` 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-<confidence 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-<number of maximum character length>', + * such as 'extractive|maxcharlength-600'. Allowed values: "none", "extractive".
captionsStringNoThis 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-<true/false>` 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-<number of maximum + * character length>', such as 'extractive|maxcharlength-600'. Allowed values: "none", "extractive".
semanticQueryStringNoAllows 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.
queryRewritesStringNoWhen 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-<number of rewrites>` option, such as + * `generative|count-3`. Defaults to `None`. This parameter is only valid if the + * query type is `semantic`. Allowed values: "none", "generative".
debugStringNoEnables a debugging tool that can be used to further explore your + * search + * results. Allowed values: "disabled", "semantic", "vector", "queryRewrites", "all".
queryLanguageStringNoThe language of the query. Allowed values: "none", + * "en-us", "en-gb", "en-in", "en-ca", "en-au", "fr-fr", "fr-ca", "de-de", "es-es", "es-mx", "zh-cn", "zh-tw", + * "pt-br", "pt-pt", "it-it", "ja-jp", "ko-kr", "ru-ru", "cs-cz", "nl-be", "nl-nl", "hu-hu", "pl-pl", "sv-se", + * "tr-tr", "hi-in", "ar-sa", "ar-eg", "ar-ma", "ar-kw", "ar-jo", "da-dk", "no-no", "bg-bg", "hr-hr", "hr-ba", + * "ms-my", "ms-bn", "sl-sl", "ta-in", "vi-vn", "el-gr", "ro-ro", "is-is", "id-id", "th-th", "lt-lt", "uk-ua", + * "lv-lv", "et-ee", "ca-es", "fi-fi", "sr-ba", "sr-me", "sr-rs", "sk-sk", "nb-no", "hy-am", "bn-in", "eu-es", + * "gl-es", "gu-in", "he-il", "ga-ie", "kn-in", "ml-in", "mr-in", "fa-ae", "pa-in", "te-in", "ur-pk".
spellerStringNoImprove search recall by spell-correcting individual search + * query terms. Allowed values: "none", "lexicon".
semanticFieldsList<String>NoThe list of field names used for semantic + * ranking. In the form of "," separated string.
+ * You can add these to a request with {@link RequestOptions#addQueryParam} + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     @odata.count: Long (Optional)
+     *     @search.coverage: Double (Optional)
+     *     @search.facets (Optional): {
+     *         String (Required): [
+     *              (Required){
+     *                 count: Long (Optional)
+     *                 @search.facets (Optional): {
+     *                     String (Required): [
+     *                         (recursive schema, see above)
+     *                     ]
+     *                 }
+     *                 sum: Long (Optional)
+     *                  (Optional): {
+     *                     String: BinaryData (Required)
+     *                 }
+     *             }
+     *         ]
+     *     }
+     *     @search.answers (Optional): [
+     *          (Optional){
+     *             score: Double (Optional)
+     *             key: String (Optional)
+     *             text: String (Optional)
+     *             highlights: String (Optional)
+     *              (Optional): {
+     *                 String: BinaryData (Required)
+     *             }
+     *         }
+     *     ]
+     *     @search.debug (Optional): {
+     *         queryRewrites (Optional): {
+     *             text (Optional): {
+     *                 inputQuery: String (Optional)
+     *                 rewrites (Optional): [
+     *                     String (Optional)
+     *                 ]
+     *             }
+     *             vectors (Optional): [
+     *                 (recursive schema, see above)
+     *             ]
+     *         }
+     *     }
+     *     @search.nextPageParameters (Optional): {
+     *         count: Boolean (Optional)
+     *         facets (Optional): [
+     *             String (Optional)
+     *         ]
+     *         filter: String (Optional)
+     *         highlight: String (Optional)
+     *         highlightPostTag: String (Optional)
+     *         highlightPreTag: String (Optional)
+     *         minimumCoverage: Double (Optional)
+     *         orderby: String (Optional)
+     *         queryType: String(simple/full/semantic) (Optional)
+     *         scoringStatistics: String(local/global) (Optional)
+     *         sessionId: String (Optional)
+     *         scoringParameters (Optional): [
+     *             String (Optional)
+     *         ]
+     *         scoringProfile: String (Optional)
+     *         debug: String(disabled/semantic/vector/queryRewrites/all) (Optional)
+     *         search: String (Optional)
+     *         searchFields: String (Optional)
+     *         searchMode: String(any/all) (Optional)
+     *         queryLanguage: String(none/en-us/en-gb/en-in/en-ca/en-au/fr-fr/fr-ca/de-de/es-es/es-mx/zh-cn/zh-tw/pt-br/pt-pt/it-it/ja-jp/ko-kr/ru-ru/cs-cz/nl-be/nl-nl/hu-hu/pl-pl/sv-se/tr-tr/hi-in/ar-sa/ar-eg/ar-ma/ar-kw/ar-jo/da-dk/no-no/bg-bg/hr-hr/hr-ba/ms-my/ms-bn/sl-sl/ta-in/vi-vn/el-gr/ro-ro/is-is/id-id/th-th/lt-lt/uk-ua/lv-lv/et-ee/ca-es/fi-fi/sr-ba/sr-me/sr-rs/sk-sk/nb-no/hy-am/bn-in/eu-es/gl-es/gu-in/he-il/ga-ie/kn-in/ml-in/mr-in/fa-ae/pa-in/te-in/ur-pk) (Optional)
+     *         speller: String(none/lexicon) (Optional)
+     *         select: String (Optional)
+     *         skip: Integer (Optional)
+     *         top: Integer (Optional)
+     *         semanticConfiguration: String (Optional)
+     *         semanticErrorHandling: String(partial/fail) (Optional)
+     *         semanticMaxWaitInMilliseconds: Integer (Optional)
+     *         semanticQuery: String (Optional)
+     *         answers: String(none/extractive) (Optional)
+     *         captions: String(none/extractive) (Optional)
+     *         queryRewrites: String(none/generative) (Optional)
+     *         semanticFields: String (Optional)
+     *         vectorQueries (Optional): [
+     *              (Optional){
+     *                 kind: String(vector/text/imageUrl/imageBinary) (Required)
+     *                 k: Integer (Optional)
+     *                 fields: String (Optional)
+     *                 exhaustive: Boolean (Optional)
+     *                 oversampling: Double (Optional)
+     *                 weight: Double (Optional)
+     *                 threshold (Optional): {
+     *                     kind: String(vectorSimilarity/searchScore) (Required)
+     *                 }
+     *                 filterOverride: String (Optional)
+     *             }
+     *         ]
+     *         vectorFilterMode: String(postFilter/preFilter) (Optional)
+     *         hybridSearch (Optional): {
+     *             maxTextRecallSize: Integer (Optional)
+     *             countAndFacetMode: String(countRetrievableResults/countAllResults) (Optional)
+     *         }
+     *     }
+     *     value (Required): [
+     *          (Required){
+     *             @search.score: double (Required)
+     *             @search.rerankerScore: Double (Optional)
+     *             @search.highlights (Optional): {
+     *                 String (Required): [
+     *                     String (Required)
+     *                 ]
+     *             }
+     *             @search.captions (Optional): [
+     *                  (Optional){
+     *                     text: String (Optional)
+     *                     highlights: String (Optional)
+     *                      (Optional): {
+     *                         String: BinaryData (Required)
+     *                     }
+     *                 }
+     *             ]
+     *             @search.documentDebugInfo (Optional): [
+     *                  (Optional){
+     *                     semantic (Optional): {
+     *                         titleField (Optional): {
+     *                             name: String (Optional)
+     *                             state: String(used/unused/partial) (Optional)
+     *                         }
+     *                         contentFields (Optional): [
+     *                             (recursive schema, see above)
+     *                         ]
+     *                         keywordFields (Optional): [
+     *                             (recursive schema, see above)
+     *                         ]
+     *                         rerankerInput (Optional): {
+     *                             title: String (Optional)
+     *                             content: String (Optional)
+     *                             keywords: String (Optional)
+     *                         }
+     *                     }
+     *                     vectors (Optional): {
+     *                         subscores (Optional): {
+     *                             text (Optional): {
+     *                                 searchScore: Double (Optional)
+     *                             }
+     *                             vectors (Optional): [
+     *                                  (Optional){
+     *                                     String (Required): {
+     *                                         searchScore: Double (Optional)
+     *                                         vectorSimilarity: Double (Optional)
+     *                                     }
+     *                                 }
+     *                             ]
+     *                             documentBoost: Double (Optional)
+     *                         }
+     *                     }
+     *                 }
+     *             ]
+     *              (Optional): {
+     *                 String: BinaryData (Required)
+     *             }
+     *         }
+     *     ]
+     *     @odata.nextLink: String (Optional)
+     *     @search.semanticPartialResponseReason: String(maxWaitExceeded/capacityOverloaded/transient) (Optional)
+     *     @search.semanticPartialResponseType: String(baseResults/rerankedResults) (Optional)
+     *     @search.semanticQueryRewritesResultType: String(originalQueryOnly) (Optional)
+     * }
+     * }
+     * 
+ * + * @param indexName The name of the index. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return response containing search results from an index along with {@link Response}. */ @ServiceMethod(returns = ReturnType.SINGLE) - public Mono searchPostAsync(SearchRequest searchRequest, RequestOptions requestOptions) { - return searchPostWithResponseAsync(searchRequest, requestOptions) - .flatMap(res -> Mono.justOrEmpty(res.getValue())); + public Response searchGetWithResponse(String indexName, RequestOptions requestOptions) { + final String accept = "application/json"; + return service.searchGetSync(this.client.getEndpoint(), this.client.getServiceVersion().getVersion(), indexName, + accept, requestOptions, Context.NONE); } /** * Searches for documents in the index. - * + *

Request Body Schema

+ * + *
+     * {@code
+     * {
+     *     count: Boolean (Optional)
+     *     facets (Optional): [
+     *         String (Optional)
+     *     ]
+     *     filter: String (Optional)
+     *     highlight: String (Optional)
+     *     highlightPostTag: String (Optional)
+     *     highlightPreTag: String (Optional)
+     *     minimumCoverage: Double (Optional)
+     *     orderby: String (Optional)
+     *     queryType: String(simple/full/semantic) (Optional)
+     *     scoringStatistics: String(local/global) (Optional)
+     *     sessionId: String (Optional)
+     *     scoringParameters (Optional): [
+     *         String (Optional)
+     *     ]
+     *     scoringProfile: String (Optional)
+     *     debug: String(disabled/semantic/vector/queryRewrites/all) (Optional)
+     *     search: String (Optional)
+     *     searchFields: String (Optional)
+     *     searchMode: String(any/all) (Optional)
+     *     queryLanguage: String(none/en-us/en-gb/en-in/en-ca/en-au/fr-fr/fr-ca/de-de/es-es/es-mx/zh-cn/zh-tw/pt-br/pt-pt/it-it/ja-jp/ko-kr/ru-ru/cs-cz/nl-be/nl-nl/hu-hu/pl-pl/sv-se/tr-tr/hi-in/ar-sa/ar-eg/ar-ma/ar-kw/ar-jo/da-dk/no-no/bg-bg/hr-hr/hr-ba/ms-my/ms-bn/sl-sl/ta-in/vi-vn/el-gr/ro-ro/is-is/id-id/th-th/lt-lt/uk-ua/lv-lv/et-ee/ca-es/fi-fi/sr-ba/sr-me/sr-rs/sk-sk/nb-no/hy-am/bn-in/eu-es/gl-es/gu-in/he-il/ga-ie/kn-in/ml-in/mr-in/fa-ae/pa-in/te-in/ur-pk) (Optional)
+     *     speller: String(none/lexicon) (Optional)
+     *     select: String (Optional)
+     *     skip: Integer (Optional)
+     *     top: Integer (Optional)
+     *     semanticConfiguration: String (Optional)
+     *     semanticErrorHandling: String(partial/fail) (Optional)
+     *     semanticMaxWaitInMilliseconds: Integer (Optional)
+     *     semanticQuery: String (Optional)
+     *     answers: String(none/extractive) (Optional)
+     *     captions: String(none/extractive) (Optional)
+     *     queryRewrites: String(none/generative) (Optional)
+     *     semanticFields: String (Optional)
+     *     vectorQueries (Optional): [
+     *          (Optional){
+     *             kind: String(vector/text/imageUrl/imageBinary) (Required)
+     *             k: Integer (Optional)
+     *             fields: String (Optional)
+     *             exhaustive: Boolean (Optional)
+     *             oversampling: Double (Optional)
+     *             weight: Double (Optional)
+     *             threshold (Optional): {
+     *                 kind: String(vectorSimilarity/searchScore) (Required)
+     *             }
+     *             filterOverride: String (Optional)
+     *         }
+     *     ]
+     *     vectorFilterMode: String(postFilter/preFilter) (Optional)
+     *     hybridSearch (Optional): {
+     *         maxTextRecallSize: Integer (Optional)
+     *         countAndFacetMode: String(countRetrievableResults/countAllResults) (Optional)
+     *     }
+     * }
+     * }
+     * 
+ * + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     @odata.count: Long (Optional)
+     *     @search.coverage: Double (Optional)
+     *     @search.facets (Optional): {
+     *         String (Required): [
+     *              (Required){
+     *                 count: Long (Optional)
+     *                 @search.facets (Optional): {
+     *                     String (Required): [
+     *                         (recursive schema, see above)
+     *                     ]
+     *                 }
+     *                 sum: Long (Optional)
+     *                  (Optional): {
+     *                     String: BinaryData (Required)
+     *                 }
+     *             }
+     *         ]
+     *     }
+     *     @search.answers (Optional): [
+     *          (Optional){
+     *             score: Double (Optional)
+     *             key: String (Optional)
+     *             text: String (Optional)
+     *             highlights: String (Optional)
+     *              (Optional): {
+     *                 String: BinaryData (Required)
+     *             }
+     *         }
+     *     ]
+     *     @search.debug (Optional): {
+     *         queryRewrites (Optional): {
+     *             text (Optional): {
+     *                 inputQuery: String (Optional)
+     *                 rewrites (Optional): [
+     *                     String (Optional)
+     *                 ]
+     *             }
+     *             vectors (Optional): [
+     *                 (recursive schema, see above)
+     *             ]
+     *         }
+     *     }
+     *     @search.nextPageParameters (Optional): {
+     *         count: Boolean (Optional)
+     *         facets (Optional): [
+     *             String (Optional)
+     *         ]
+     *         filter: String (Optional)
+     *         highlight: String (Optional)
+     *         highlightPostTag: String (Optional)
+     *         highlightPreTag: String (Optional)
+     *         minimumCoverage: Double (Optional)
+     *         orderby: String (Optional)
+     *         queryType: String(simple/full/semantic) (Optional)
+     *         scoringStatistics: String(local/global) (Optional)
+     *         sessionId: String (Optional)
+     *         scoringParameters (Optional): [
+     *             String (Optional)
+     *         ]
+     *         scoringProfile: String (Optional)
+     *         debug: String(disabled/semantic/vector/queryRewrites/all) (Optional)
+     *         search: String (Optional)
+     *         searchFields: String (Optional)
+     *         searchMode: String(any/all) (Optional)
+     *         queryLanguage: String(none/en-us/en-gb/en-in/en-ca/en-au/fr-fr/fr-ca/de-de/es-es/es-mx/zh-cn/zh-tw/pt-br/pt-pt/it-it/ja-jp/ko-kr/ru-ru/cs-cz/nl-be/nl-nl/hu-hu/pl-pl/sv-se/tr-tr/hi-in/ar-sa/ar-eg/ar-ma/ar-kw/ar-jo/da-dk/no-no/bg-bg/hr-hr/hr-ba/ms-my/ms-bn/sl-sl/ta-in/vi-vn/el-gr/ro-ro/is-is/id-id/th-th/lt-lt/uk-ua/lv-lv/et-ee/ca-es/fi-fi/sr-ba/sr-me/sr-rs/sk-sk/nb-no/hy-am/bn-in/eu-es/gl-es/gu-in/he-il/ga-ie/kn-in/ml-in/mr-in/fa-ae/pa-in/te-in/ur-pk) (Optional)
+     *         speller: String(none/lexicon) (Optional)
+     *         select: String (Optional)
+     *         skip: Integer (Optional)
+     *         top: Integer (Optional)
+     *         semanticConfiguration: String (Optional)
+     *         semanticErrorHandling: String(partial/fail) (Optional)
+     *         semanticMaxWaitInMilliseconds: Integer (Optional)
+     *         semanticQuery: String (Optional)
+     *         answers: String(none/extractive) (Optional)
+     *         captions: String(none/extractive) (Optional)
+     *         queryRewrites: String(none/generative) (Optional)
+     *         semanticFields: String (Optional)
+     *         vectorQueries (Optional): [
+     *              (Optional){
+     *                 kind: String(vector/text/imageUrl/imageBinary) (Required)
+     *                 k: Integer (Optional)
+     *                 fields: String (Optional)
+     *                 exhaustive: Boolean (Optional)
+     *                 oversampling: Double (Optional)
+     *                 weight: Double (Optional)
+     *                 threshold (Optional): {
+     *                     kind: String(vectorSimilarity/searchScore) (Required)
+     *                 }
+     *                 filterOverride: String (Optional)
+     *             }
+     *         ]
+     *         vectorFilterMode: String(postFilter/preFilter) (Optional)
+     *         hybridSearch (Optional): {
+     *             maxTextRecallSize: Integer (Optional)
+     *             countAndFacetMode: String(countRetrievableResults/countAllResults) (Optional)
+     *         }
+     *     }
+     *     value (Required): [
+     *          (Required){
+     *             @search.score: double (Required)
+     *             @search.rerankerScore: Double (Optional)
+     *             @search.highlights (Optional): {
+     *                 String (Required): [
+     *                     String (Required)
+     *                 ]
+     *             }
+     *             @search.captions (Optional): [
+     *                  (Optional){
+     *                     text: String (Optional)
+     *                     highlights: String (Optional)
+     *                      (Optional): {
+     *                         String: BinaryData (Required)
+     *                     }
+     *                 }
+     *             ]
+     *             @search.documentDebugInfo (Optional): [
+     *                  (Optional){
+     *                     semantic (Optional): {
+     *                         titleField (Optional): {
+     *                             name: String (Optional)
+     *                             state: String(used/unused/partial) (Optional)
+     *                         }
+     *                         contentFields (Optional): [
+     *                             (recursive schema, see above)
+     *                         ]
+     *                         keywordFields (Optional): [
+     *                             (recursive schema, see above)
+     *                         ]
+     *                         rerankerInput (Optional): {
+     *                             title: String (Optional)
+     *                             content: String (Optional)
+     *                             keywords: String (Optional)
+     *                         }
+     *                     }
+     *                     vectors (Optional): {
+     *                         subscores (Optional): {
+     *                             text (Optional): {
+     *                                 searchScore: Double (Optional)
+     *                             }
+     *                             vectors (Optional): [
+     *                                  (Optional){
+     *                                     String (Required): {
+     *                                         searchScore: Double (Optional)
+     *                                         vectorSimilarity: Double (Optional)
+     *                                     }
+     *                                 }
+     *                             ]
+     *                             documentBoost: Double (Optional)
+     *                         }
+     *                     }
+     *                 }
+     *             ]
+     *              (Optional): {
+     *                 String: BinaryData (Required)
+     *             }
+     *         }
+     *     ]
+     *     @odata.nextLink: String (Optional)
+     *     @search.semanticPartialResponseReason: String(maxWaitExceeded/capacityOverloaded/transient) (Optional)
+     *     @search.semanticPartialResponseType: String(baseResults/rerankedResults) (Optional)
+     *     @search.semanticQueryRewritesResultType: String(originalQueryOnly) (Optional)
+     * }
+     * }
+     * 
+ * + * @param indexName The name of the index. * @param searchRequest The definition of the Search request. - * @param requestOptions Parameter group. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return response containing search results from an index on successful completion of {@link Mono}. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return response containing search results from an index along with {@link Response} on successful completion of + * {@link Mono}. */ @ServiceMethod(returns = ReturnType.SINGLE) - public Mono searchPostAsync(SearchRequest searchRequest, RequestOptions requestOptions, - Context context) { - return searchPostWithResponseAsync(searchRequest, requestOptions, context) - .flatMap(res -> Mono.justOrEmpty(res.getValue())); + public Mono> searchPostWithResponseAsync(String indexName, BinaryData searchRequest, + RequestOptions requestOptions) { + final String contentType = "application/json"; + final String accept = "application/json"; + return FluxUtil.withContext( + context -> service.searchPost(this.client.getEndpoint(), this.client.getServiceVersion().getVersion(), + indexName, contentType, accept, searchRequest, requestOptions, context)); } /** * Searches for documents in the index. - * + *

Request Body Schema

+ * + *
+     * {@code
+     * {
+     *     count: Boolean (Optional)
+     *     facets (Optional): [
+     *         String (Optional)
+     *     ]
+     *     filter: String (Optional)
+     *     highlight: String (Optional)
+     *     highlightPostTag: String (Optional)
+     *     highlightPreTag: String (Optional)
+     *     minimumCoverage: Double (Optional)
+     *     orderby: String (Optional)
+     *     queryType: String(simple/full/semantic) (Optional)
+     *     scoringStatistics: String(local/global) (Optional)
+     *     sessionId: String (Optional)
+     *     scoringParameters (Optional): [
+     *         String (Optional)
+     *     ]
+     *     scoringProfile: String (Optional)
+     *     debug: String(disabled/semantic/vector/queryRewrites/all) (Optional)
+     *     search: String (Optional)
+     *     searchFields: String (Optional)
+     *     searchMode: String(any/all) (Optional)
+     *     queryLanguage: String(none/en-us/en-gb/en-in/en-ca/en-au/fr-fr/fr-ca/de-de/es-es/es-mx/zh-cn/zh-tw/pt-br/pt-pt/it-it/ja-jp/ko-kr/ru-ru/cs-cz/nl-be/nl-nl/hu-hu/pl-pl/sv-se/tr-tr/hi-in/ar-sa/ar-eg/ar-ma/ar-kw/ar-jo/da-dk/no-no/bg-bg/hr-hr/hr-ba/ms-my/ms-bn/sl-sl/ta-in/vi-vn/el-gr/ro-ro/is-is/id-id/th-th/lt-lt/uk-ua/lv-lv/et-ee/ca-es/fi-fi/sr-ba/sr-me/sr-rs/sk-sk/nb-no/hy-am/bn-in/eu-es/gl-es/gu-in/he-il/ga-ie/kn-in/ml-in/mr-in/fa-ae/pa-in/te-in/ur-pk) (Optional)
+     *     speller: String(none/lexicon) (Optional)
+     *     select: String (Optional)
+     *     skip: Integer (Optional)
+     *     top: Integer (Optional)
+     *     semanticConfiguration: String (Optional)
+     *     semanticErrorHandling: String(partial/fail) (Optional)
+     *     semanticMaxWaitInMilliseconds: Integer (Optional)
+     *     semanticQuery: String (Optional)
+     *     answers: String(none/extractive) (Optional)
+     *     captions: String(none/extractive) (Optional)
+     *     queryRewrites: String(none/generative) (Optional)
+     *     semanticFields: String (Optional)
+     *     vectorQueries (Optional): [
+     *          (Optional){
+     *             kind: String(vector/text/imageUrl/imageBinary) (Required)
+     *             k: Integer (Optional)
+     *             fields: String (Optional)
+     *             exhaustive: Boolean (Optional)
+     *             oversampling: Double (Optional)
+     *             weight: Double (Optional)
+     *             threshold (Optional): {
+     *                 kind: String(vectorSimilarity/searchScore) (Required)
+     *             }
+     *             filterOverride: String (Optional)
+     *         }
+     *     ]
+     *     vectorFilterMode: String(postFilter/preFilter) (Optional)
+     *     hybridSearch (Optional): {
+     *         maxTextRecallSize: Integer (Optional)
+     *         countAndFacetMode: String(countRetrievableResults/countAllResults) (Optional)
+     *     }
+     * }
+     * }
+     * 
+ * + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     @odata.count: Long (Optional)
+     *     @search.coverage: Double (Optional)
+     *     @search.facets (Optional): {
+     *         String (Required): [
+     *              (Required){
+     *                 count: Long (Optional)
+     *                 @search.facets (Optional): {
+     *                     String (Required): [
+     *                         (recursive schema, see above)
+     *                     ]
+     *                 }
+     *                 sum: Long (Optional)
+     *                  (Optional): {
+     *                     String: BinaryData (Required)
+     *                 }
+     *             }
+     *         ]
+     *     }
+     *     @search.answers (Optional): [
+     *          (Optional){
+     *             score: Double (Optional)
+     *             key: String (Optional)
+     *             text: String (Optional)
+     *             highlights: String (Optional)
+     *              (Optional): {
+     *                 String: BinaryData (Required)
+     *             }
+     *         }
+     *     ]
+     *     @search.debug (Optional): {
+     *         queryRewrites (Optional): {
+     *             text (Optional): {
+     *                 inputQuery: String (Optional)
+     *                 rewrites (Optional): [
+     *                     String (Optional)
+     *                 ]
+     *             }
+     *             vectors (Optional): [
+     *                 (recursive schema, see above)
+     *             ]
+     *         }
+     *     }
+     *     @search.nextPageParameters (Optional): {
+     *         count: Boolean (Optional)
+     *         facets (Optional): [
+     *             String (Optional)
+     *         ]
+     *         filter: String (Optional)
+     *         highlight: String (Optional)
+     *         highlightPostTag: String (Optional)
+     *         highlightPreTag: String (Optional)
+     *         minimumCoverage: Double (Optional)
+     *         orderby: String (Optional)
+     *         queryType: String(simple/full/semantic) (Optional)
+     *         scoringStatistics: String(local/global) (Optional)
+     *         sessionId: String (Optional)
+     *         scoringParameters (Optional): [
+     *             String (Optional)
+     *         ]
+     *         scoringProfile: String (Optional)
+     *         debug: String(disabled/semantic/vector/queryRewrites/all) (Optional)
+     *         search: String (Optional)
+     *         searchFields: String (Optional)
+     *         searchMode: String(any/all) (Optional)
+     *         queryLanguage: String(none/en-us/en-gb/en-in/en-ca/en-au/fr-fr/fr-ca/de-de/es-es/es-mx/zh-cn/zh-tw/pt-br/pt-pt/it-it/ja-jp/ko-kr/ru-ru/cs-cz/nl-be/nl-nl/hu-hu/pl-pl/sv-se/tr-tr/hi-in/ar-sa/ar-eg/ar-ma/ar-kw/ar-jo/da-dk/no-no/bg-bg/hr-hr/hr-ba/ms-my/ms-bn/sl-sl/ta-in/vi-vn/el-gr/ro-ro/is-is/id-id/th-th/lt-lt/uk-ua/lv-lv/et-ee/ca-es/fi-fi/sr-ba/sr-me/sr-rs/sk-sk/nb-no/hy-am/bn-in/eu-es/gl-es/gu-in/he-il/ga-ie/kn-in/ml-in/mr-in/fa-ae/pa-in/te-in/ur-pk) (Optional)
+     *         speller: String(none/lexicon) (Optional)
+     *         select: String (Optional)
+     *         skip: Integer (Optional)
+     *         top: Integer (Optional)
+     *         semanticConfiguration: String (Optional)
+     *         semanticErrorHandling: String(partial/fail) (Optional)
+     *         semanticMaxWaitInMilliseconds: Integer (Optional)
+     *         semanticQuery: String (Optional)
+     *         answers: String(none/extractive) (Optional)
+     *         captions: String(none/extractive) (Optional)
+     *         queryRewrites: String(none/generative) (Optional)
+     *         semanticFields: String (Optional)
+     *         vectorQueries (Optional): [
+     *              (Optional){
+     *                 kind: String(vector/text/imageUrl/imageBinary) (Required)
+     *                 k: Integer (Optional)
+     *                 fields: String (Optional)
+     *                 exhaustive: Boolean (Optional)
+     *                 oversampling: Double (Optional)
+     *                 weight: Double (Optional)
+     *                 threshold (Optional): {
+     *                     kind: String(vectorSimilarity/searchScore) (Required)
+     *                 }
+     *                 filterOverride: String (Optional)
+     *             }
+     *         ]
+     *         vectorFilterMode: String(postFilter/preFilter) (Optional)
+     *         hybridSearch (Optional): {
+     *             maxTextRecallSize: Integer (Optional)
+     *             countAndFacetMode: String(countRetrievableResults/countAllResults) (Optional)
+     *         }
+     *     }
+     *     value (Required): [
+     *          (Required){
+     *             @search.score: double (Required)
+     *             @search.rerankerScore: Double (Optional)
+     *             @search.highlights (Optional): {
+     *                 String (Required): [
+     *                     String (Required)
+     *                 ]
+     *             }
+     *             @search.captions (Optional): [
+     *                  (Optional){
+     *                     text: String (Optional)
+     *                     highlights: String (Optional)
+     *                      (Optional): {
+     *                         String: BinaryData (Required)
+     *                     }
+     *                 }
+     *             ]
+     *             @search.documentDebugInfo (Optional): [
+     *                  (Optional){
+     *                     semantic (Optional): {
+     *                         titleField (Optional): {
+     *                             name: String (Optional)
+     *                             state: String(used/unused/partial) (Optional)
+     *                         }
+     *                         contentFields (Optional): [
+     *                             (recursive schema, see above)
+     *                         ]
+     *                         keywordFields (Optional): [
+     *                             (recursive schema, see above)
+     *                         ]
+     *                         rerankerInput (Optional): {
+     *                             title: String (Optional)
+     *                             content: String (Optional)
+     *                             keywords: String (Optional)
+     *                         }
+     *                     }
+     *                     vectors (Optional): {
+     *                         subscores (Optional): {
+     *                             text (Optional): {
+     *                                 searchScore: Double (Optional)
+     *                             }
+     *                             vectors (Optional): [
+     *                                  (Optional){
+     *                                     String (Required): {
+     *                                         searchScore: Double (Optional)
+     *                                         vectorSimilarity: Double (Optional)
+     *                                     }
+     *                                 }
+     *                             ]
+     *                             documentBoost: Double (Optional)
+     *                         }
+     *                     }
+     *                 }
+     *             ]
+     *              (Optional): {
+     *                 String: BinaryData (Required)
+     *             }
+     *         }
+     *     ]
+     *     @odata.nextLink: String (Optional)
+     *     @search.semanticPartialResponseReason: String(maxWaitExceeded/capacityOverloaded/transient) (Optional)
+     *     @search.semanticPartialResponseType: String(baseResults/rerankedResults) (Optional)
+     *     @search.semanticQueryRewritesResultType: String(originalQueryOnly) (Optional)
+     * }
+     * }
+     * 
+ * + * @param indexName The name of the index. * @param searchRequest The definition of the Search request. - * @param requestOptions Parameter group. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. * @return response containing search results from an index along with {@link Response}. */ @ServiceMethod(returns = ReturnType.SINGLE) - public Response searchPostWithResponse(SearchRequest searchRequest, - RequestOptions requestOptions, Context context) { - final String accept = "application/json; odata.metadata=none"; - UUID xMsClientRequestIdInternal = null; - if (requestOptions != null) { - xMsClientRequestIdInternal = requestOptions.getXMsClientRequestId(); - } - UUID xMsClientRequestId = xMsClientRequestIdInternal; - return service.searchPostSync(this.client.getEndpoint(), this.client.getIndexName(), - this.client.getApiVersion(), xMsClientRequestId, accept, searchRequest, context); - } - - /** - * Searches for documents in the index. - * - * @param searchRequest The definition of the Search request. - * @param requestOptions Parameter group. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return response containing search results from an index. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public SearchDocumentsResult searchPost(SearchRequest searchRequest, RequestOptions requestOptions) { - return searchPostWithResponse(searchRequest, requestOptions, Context.NONE).getValue(); - } - - /** - * Retrieves a document from the index. - * - * @param key The key of the document to retrieve. - * @param selectedFields List of field names to retrieve for the document; Any field not retrieved will be missing - * from the returned document. - * @param requestOptions Parameter group. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a document retrieved via a document lookup operation along with {@link Response} on successful completion - * of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono>> getWithResponseAsync(String key, List selectedFields, + public Response searchPostWithResponse(String indexName, BinaryData searchRequest, RequestOptions requestOptions) { - return FluxUtil.withContext(context -> getWithResponseAsync(key, selectedFields, requestOptions, context)); + final String contentType = "application/json"; + final String accept = "application/json"; + return service.searchPostSync(this.client.getEndpoint(), this.client.getServiceVersion().getVersion(), + indexName, contentType, accept, searchRequest, requestOptions, Context.NONE); } /** * Retrieves a document from the index. - * + *

Query Parameters

+ * + * + * + * + *
Query Parameters
NameTypeRequiredDescription
$selectList<String>NoList of field names to retrieve for the document; + * Any field not retrieved will + * be missing from the returned document. In the form of "," separated string.
+ * You can add these to a request with {@link RequestOptions#addQueryParam} + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *      (Optional): {
+     *         String: BinaryData (Required)
+     *     }
+     * }
+     * }
+     * 
+ * * @param key The key of the document to retrieve. - * @param selectedFields List of field names to retrieve for the document; Any field not retrieved will be missing - * from the returned document. - * @param requestOptions Parameter group. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @param indexName The name of the index. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. * @return a document retrieved via a document lookup operation along with {@link Response} on successful completion * of {@link Mono}. */ @ServiceMethod(returns = ReturnType.SINGLE) - public Mono>> getWithResponseAsync(String key, List selectedFields, - RequestOptions requestOptions, Context context) { - final String accept = "application/json; odata.metadata=none"; - UUID xMsClientRequestIdInternal = null; - if (requestOptions != null) { - xMsClientRequestIdInternal = requestOptions.getXMsClientRequestId(); - } - UUID xMsClientRequestId = xMsClientRequestIdInternal; - String selectedFieldsConverted = (selectedFields == null) - ? null - : selectedFields.stream() - .map(paramItemValue -> Objects.toString(paramItemValue, "")) - .collect(Collectors.joining(",")); - return service.get(this.client.getEndpoint(), this.client.getIndexName(), key, selectedFieldsConverted, - this.client.getApiVersion(), xMsClientRequestId, accept, context); - } - - /** - * Retrieves a document from the index. - * - * @param key The key of the document to retrieve. - * @param selectedFields List of field names to retrieve for the document; Any field not retrieved will be missing - * from the returned document. - * @param requestOptions Parameter group. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a document retrieved via a document lookup operation on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> getAsync(String key, List selectedFields, RequestOptions requestOptions) { - return getWithResponseAsync(key, selectedFields, requestOptions) - .flatMap(res -> Mono.justOrEmpty(res.getValue())); - } - - /** - * Retrieves a document from the index. - * - * @param key The key of the document to retrieve. - * @param selectedFields List of field names to retrieve for the document; Any field not retrieved will be missing - * from the returned document. - * @param requestOptions Parameter group. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a document retrieved via a document lookup operation on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> getAsync(String key, List selectedFields, RequestOptions requestOptions, - Context context) { - return getWithResponseAsync(key, selectedFields, requestOptions, context) - .flatMap(res -> Mono.justOrEmpty(res.getValue())); + public Mono> getWithResponseAsync(String key, String indexName, + RequestOptions requestOptions) { + final String accept = "application/json"; + return FluxUtil.withContext(context -> service.get(this.client.getEndpoint(), + this.client.getServiceVersion().getVersion(), key, indexName, accept, requestOptions, context)); } /** * Retrieves a document from the index. - * + *

Query Parameters

+ * + * + * + * + *
Query Parameters
NameTypeRequiredDescription
$selectList<String>NoList of field names to retrieve for the document; + * Any field not retrieved will + * be missing from the returned document. In the form of "," separated string.
+ * You can add these to a request with {@link RequestOptions#addQueryParam} + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *      (Optional): {
+     *         String: BinaryData (Required)
+     *     }
+     * }
+     * }
+     * 
+ * * @param key The key of the document to retrieve. - * @param selectedFields List of field names to retrieve for the document; Any field not retrieved will be missing - * from the returned document. - * @param requestOptions Parameter group. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @param indexName The name of the index. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. * @return a document retrieved via a document lookup operation along with {@link Response}. */ @ServiceMethod(returns = ReturnType.SINGLE) - public Response> getWithResponse(String key, List selectedFields, - RequestOptions requestOptions, Context context) { - final String accept = "application/json; odata.metadata=none"; - UUID xMsClientRequestIdInternal = null; - if (requestOptions != null) { - xMsClientRequestIdInternal = requestOptions.getXMsClientRequestId(); - } - UUID xMsClientRequestId = xMsClientRequestIdInternal; - String selectedFieldsConverted = (selectedFields == null) - ? null - : selectedFields.stream() - .map(paramItemValue -> Objects.toString(paramItemValue, "")) - .collect(Collectors.joining(",")); - return service.getSync(this.client.getEndpoint(), this.client.getIndexName(), key, selectedFieldsConverted, - this.client.getApiVersion(), xMsClientRequestId, accept, context); - } - - /** - * Retrieves a document from the index. - * - * @param key The key of the document to retrieve. - * @param selectedFields List of field names to retrieve for the document; Any field not retrieved will be missing - * from the returned document. - * @param requestOptions Parameter group. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a document retrieved via a document lookup operation. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Map get(String key, List selectedFields, RequestOptions requestOptions) { - return getWithResponse(key, selectedFields, requestOptions, Context.NONE).getValue(); + public Response getWithResponse(String key, String indexName, RequestOptions requestOptions) { + final String accept = "application/json"; + return service.getSync(this.client.getEndpoint(), this.client.getServiceVersion().getVersion(), key, indexName, + accept, requestOptions, Context.NONE); } /** * Suggests documents in the index that match the given partial query text. - * - * @param suggestRequest The Suggest request. - * @param requestOptions Parameter group. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return response containing suggestion query results from an index along with {@link Response} on successful - * completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> suggestPostWithResponseAsync(SuggestRequest suggestRequest, - RequestOptions requestOptions) { - return FluxUtil.withContext(context -> suggestPostWithResponseAsync(suggestRequest, requestOptions, context)); - } - - /** - * Suggests documents in the index that match the given partial query text. - * - * @param suggestRequest The Suggest request. - * @param requestOptions Parameter group. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + *

Query Parameters

+ * + * + * + * + * + * + * + * + * + * + * + * + *
Query Parameters
NameTypeRequiredDescription
$filterStringNoAn OData expression that filters the documents considered for + * suggestions.
fuzzyBooleanNoA 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.
highlightPostTagStringNoA string tag that is appended to hit highlights. Must + * be set with + * highlightPreTag. If omitted, hit highlighting of suggestions is disabled.
highlightPreTagStringNoA string tag that is prepended to hit highlights. Must + * be set with + * highlightPostTag. If omitted, hit highlighting of suggestions is disabled.
minimumCoverageDoubleNoA 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.
$orderbyList<String>NoThe 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. In the form of "," separated string.
searchFieldsList<String>NoThe list of field names to search for the + * specified search text. Target fields + * must be included in the specified suggester. In the form of "," separated string.
$selectList<String>NoThe list of fields to retrieve. If unspecified, + * only the key field will be + * included in the results. In the form of "," separated string.
$topIntegerNoThe number of suggestions to retrieve. The value must be a number + * between 1 and + * 100. The default is 5.
+ * You can add these to a request with {@link RequestOptions#addQueryParam} + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     value (Required): [
+     *          (Required){
+     *             @search.text: String (Required)
+     *              (Optional): {
+     *                 String: BinaryData (Required)
+     *             }
+     *         }
+     *     ]
+     *     @search.coverage: Double (Optional)
+     * }
+     * }
+     * 
+ * + * @param searchText The search text to use to suggest documents. Must be at least 1 character, and + * no more than 100 characters. + * @param suggesterName The name of the suggester as specified in the suggesters collection that's part + * of the index definition. + * @param indexName The name of the index. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. * @return response containing suggestion query results from an index along with {@link Response} on successful * completion of {@link Mono}. */ @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> suggestPostWithResponseAsync(SuggestRequest suggestRequest, - RequestOptions requestOptions, Context context) { - final String accept = "application/json; odata.metadata=none"; - UUID xMsClientRequestIdInternal = null; - if (requestOptions != null) { - xMsClientRequestIdInternal = requestOptions.getXMsClientRequestId(); - } - UUID xMsClientRequestId = xMsClientRequestIdInternal; - return service.suggestPost(this.client.getEndpoint(), this.client.getIndexName(), this.client.getApiVersion(), - xMsClientRequestId, accept, suggestRequest, context); + public Mono> suggestGetWithResponseAsync(String searchText, String suggesterName, + String indexName, RequestOptions requestOptions) { + final String accept = "application/json"; + return FluxUtil.withContext( + context -> service.suggestGet(this.client.getEndpoint(), this.client.getServiceVersion().getVersion(), + searchText, suggesterName, indexName, accept, requestOptions, context)); } /** * Suggests documents in the index that match the given partial query text. - * - * @param suggestRequest The Suggest request. - * @param requestOptions Parameter group. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return response containing suggestion query results from an index on successful completion of {@link Mono}. + *

Query Parameters

+ * + * + * + * + * + * + * + * + * + * + * + * + *
Query Parameters
NameTypeRequiredDescription
$filterStringNoAn OData expression that filters the documents considered for + * suggestions.
fuzzyBooleanNoA 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.
highlightPostTagStringNoA string tag that is appended to hit highlights. Must + * be set with + * highlightPreTag. If omitted, hit highlighting of suggestions is disabled.
highlightPreTagStringNoA string tag that is prepended to hit highlights. Must + * be set with + * highlightPostTag. If omitted, hit highlighting of suggestions is disabled.
minimumCoverageDoubleNoA 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.
$orderbyList<String>NoThe 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. In the form of "," separated string.
searchFieldsList<String>NoThe list of field names to search for the + * specified search text. Target fields + * must be included in the specified suggester. In the form of "," separated string.
$selectList<String>NoThe list of fields to retrieve. If unspecified, + * only the key field will be + * included in the results. In the form of "," separated string.
$topIntegerNoThe number of suggestions to retrieve. The value must be a number + * between 1 and + * 100. The default is 5.
+ * You can add these to a request with {@link RequestOptions#addQueryParam} + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     value (Required): [
+     *          (Required){
+     *             @search.text: String (Required)
+     *              (Optional): {
+     *                 String: BinaryData (Required)
+     *             }
+     *         }
+     *     ]
+     *     @search.coverage: Double (Optional)
+     * }
+     * }
+     * 
+ * + * @param searchText The search text to use to suggest documents. Must be at least 1 character, and + * no more than 100 characters. + * @param suggesterName The name of the suggester as specified in the suggesters collection that's part + * of the index definition. + * @param indexName The name of the index. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return response containing suggestion query results from an index along with {@link Response}. */ @ServiceMethod(returns = ReturnType.SINGLE) - public Mono suggestPostAsync(SuggestRequest suggestRequest, RequestOptions requestOptions) { - return suggestPostWithResponseAsync(suggestRequest, requestOptions) - .flatMap(res -> Mono.justOrEmpty(res.getValue())); + public Response suggestGetWithResponse(String searchText, String suggesterName, String indexName, + RequestOptions requestOptions) { + final String accept = "application/json"; + return service.suggestGetSync(this.client.getEndpoint(), this.client.getServiceVersion().getVersion(), + searchText, suggesterName, indexName, accept, requestOptions, Context.NONE); } /** * Suggests documents in the index that match the given partial query text. - * + *

Request Body Schema

+ * + *
+     * {@code
+     * {
+     *     filter: String (Optional)
+     *     fuzzy: Boolean (Optional)
+     *     highlightPostTag: String (Optional)
+     *     highlightPreTag: String (Optional)
+     *     minimumCoverage: Double (Optional)
+     *     orderby: String (Optional)
+     *     search: String (Required)
+     *     searchFields: String (Optional)
+     *     select: String (Optional)
+     *     suggesterName: String (Required)
+     *     top: Integer (Optional)
+     * }
+     * }
+     * 
+ * + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     value (Required): [
+     *          (Required){
+     *             @search.text: String (Required)
+     *              (Optional): {
+     *                 String: BinaryData (Required)
+     *             }
+     *         }
+     *     ]
+     *     @search.coverage: Double (Optional)
+     * }
+     * }
+     * 
+ * + * @param indexName The name of the index. * @param suggestRequest The Suggest request. - * @param requestOptions Parameter group. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return response containing suggestion query results from an index on successful completion of {@link Mono}. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return response containing suggestion query results from an index along with {@link Response} on successful + * completion of {@link Mono}. */ @ServiceMethod(returns = ReturnType.SINGLE) - public Mono suggestPostAsync(SuggestRequest suggestRequest, RequestOptions requestOptions, - Context context) { - return suggestPostWithResponseAsync(suggestRequest, requestOptions, context) - .flatMap(res -> Mono.justOrEmpty(res.getValue())); + public Mono> suggestPostWithResponseAsync(String indexName, BinaryData suggestRequest, + RequestOptions requestOptions) { + final String contentType = "application/json"; + final String accept = "application/json"; + return FluxUtil.withContext( + context -> service.suggestPost(this.client.getEndpoint(), this.client.getServiceVersion().getVersion(), + indexName, contentType, accept, suggestRequest, requestOptions, context)); } /** * Suggests documents in the index that match the given partial query text. - * + *

Request Body Schema

+ * + *
+     * {@code
+     * {
+     *     filter: String (Optional)
+     *     fuzzy: Boolean (Optional)
+     *     highlightPostTag: String (Optional)
+     *     highlightPreTag: String (Optional)
+     *     minimumCoverage: Double (Optional)
+     *     orderby: String (Optional)
+     *     search: String (Required)
+     *     searchFields: String (Optional)
+     *     select: String (Optional)
+     *     suggesterName: String (Required)
+     *     top: Integer (Optional)
+     * }
+     * }
+     * 
+ * + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     value (Required): [
+     *          (Required){
+     *             @search.text: String (Required)
+     *              (Optional): {
+     *                 String: BinaryData (Required)
+     *             }
+     *         }
+     *     ]
+     *     @search.coverage: Double (Optional)
+     * }
+     * }
+     * 
+ * + * @param indexName The name of the index. * @param suggestRequest The Suggest request. - * @param requestOptions Parameter group. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. * @return response containing suggestion query results from an index along with {@link Response}. */ @ServiceMethod(returns = ReturnType.SINGLE) - public Response suggestPostWithResponse(SuggestRequest suggestRequest, - RequestOptions requestOptions, Context context) { - final String accept = "application/json; odata.metadata=none"; - UUID xMsClientRequestIdInternal = null; - if (requestOptions != null) { - xMsClientRequestIdInternal = requestOptions.getXMsClientRequestId(); - } - UUID xMsClientRequestId = xMsClientRequestIdInternal; - return service.suggestPostSync(this.client.getEndpoint(), this.client.getIndexName(), - this.client.getApiVersion(), xMsClientRequestId, accept, suggestRequest, context); - } - - /** - * Suggests documents in the index that match the given partial query text. - * - * @param suggestRequest The Suggest request. - * @param requestOptions Parameter group. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return response containing suggestion query results from an index. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public SuggestDocumentsResult suggestPost(SuggestRequest suggestRequest, RequestOptions requestOptions) { - return suggestPostWithResponse(suggestRequest, requestOptions, Context.NONE).getValue(); - } - - /** - * Sends a batch of document write actions to the index. - * - * @param batch The batch of index actions. - * @param requestOptions Parameter group. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return response containing the status of operations for all documents in the indexing request along with - * {@link Response} on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> indexWithResponseAsync(IndexBatch batch, + public Response suggestPostWithResponse(String indexName, BinaryData suggestRequest, RequestOptions requestOptions) { - return FluxUtil.withContext(context -> indexWithResponseAsync(batch, requestOptions, context)); - } - - /** - * Sends a batch of document write actions to the index. - * - * @param batch The batch of index actions. - * @param requestOptions Parameter group. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return response containing the status of operations for all documents in the indexing request along with - * {@link Response} on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> indexWithResponseAsync(IndexBatch batch, RequestOptions requestOptions, - Context context) { - final String accept = "application/json; odata.metadata=none"; - UUID xMsClientRequestIdInternal = null; - if (requestOptions != null) { - xMsClientRequestIdInternal = requestOptions.getXMsClientRequestId(); - } - UUID xMsClientRequestId = xMsClientRequestIdInternal; - return service.index(this.client.getEndpoint(), this.client.getIndexName(), this.client.getApiVersion(), - xMsClientRequestId, accept, batch, context); - } - - /** - * Sends a batch of document write actions to the index. - * - * @param batch The batch of index actions. - * @param requestOptions Parameter group. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return response containing the status of operations for all documents in the indexing request on successful - * completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono indexAsync(IndexBatch batch, RequestOptions requestOptions) { - return indexWithResponseAsync(batch, requestOptions).flatMap(res -> Mono.justOrEmpty(res.getValue())); - } - - /** - * Sends a batch of document write actions to the index. - * - * @param batch The batch of index actions. - * @param requestOptions Parameter group. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return response containing the status of operations for all documents in the indexing request on successful - * completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono indexAsync(IndexBatch batch, RequestOptions requestOptions, Context context) { - return indexWithResponseAsync(batch, requestOptions, context).flatMap(res -> Mono.justOrEmpty(res.getValue())); + final String contentType = "application/json"; + final String accept = "application/json"; + return service.suggestPostSync(this.client.getEndpoint(), this.client.getServiceVersion().getVersion(), + indexName, contentType, accept, suggestRequest, requestOptions, Context.NONE); } /** * Sends a batch of document write actions to the index. - * + *

Request Body Schema

+ * + *
+     * {@code
+     * {
+     *     value (Required): [
+     *          (Required){
+     *             @search.action: String(upload/merge/mergeOrUpload/delete) (Optional)
+     *              (Optional): {
+     *                 String: BinaryData (Required)
+     *             }
+     *         }
+     *     ]
+     * }
+     * }
+     * 
+ * + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     value (Required): [
+     *          (Required){
+     *             key: String (Required)
+     *             errorMessage: String (Optional)
+     *             status: boolean (Required)
+     *             statusCode: int (Required)
+     *         }
+     *     ]
+     * }
+     * }
+     * 
+ * + * @param indexName The name of the index. * @param batch The batch of index actions. - * @param requestOptions Parameter group. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return response containing the status of operations for all documents in the indexing request along with - * {@link Response}. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return response containing the status of operations for all documents in the indexing + * request along with {@link Response} on successful completion of {@link Mono}. */ @ServiceMethod(returns = ReturnType.SINGLE) - public Response indexWithResponse(IndexBatch batch, RequestOptions requestOptions, - Context context) { - final String accept = "application/json; odata.metadata=none"; - UUID xMsClientRequestIdInternal = null; - if (requestOptions != null) { - xMsClientRequestIdInternal = requestOptions.getXMsClientRequestId(); - } - UUID xMsClientRequestId = xMsClientRequestIdInternal; - return service.indexSync(this.client.getEndpoint(), this.client.getIndexName(), this.client.getApiVersion(), - xMsClientRequestId, accept, batch, context); + public Mono> indexWithResponseAsync(String indexName, BinaryData batch, + RequestOptions requestOptions) { + final String contentType = "application/json"; + final String accept = "application/json"; + return FluxUtil.withContext( + context -> service.index(this.client.getEndpoint(), this.client.getServiceVersion().getVersion(), indexName, + contentType, accept, batch, requestOptions, context)); } /** * Sends a batch of document write actions to the index. - * + *

Request Body Schema

+ * + *
+     * {@code
+     * {
+     *     value (Required): [
+     *          (Required){
+     *             @search.action: String(upload/merge/mergeOrUpload/delete) (Optional)
+     *              (Optional): {
+     *                 String: BinaryData (Required)
+     *             }
+     *         }
+     *     ]
+     * }
+     * }
+     * 
+ * + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     value (Required): [
+     *          (Required){
+     *             key: String (Required)
+     *             errorMessage: String (Optional)
+     *             status: boolean (Required)
+     *             statusCode: int (Required)
+     *         }
+     *     ]
+     * }
+     * }
+     * 
+ * + * @param indexName The name of the index. * @param batch The batch of index actions. - * @param requestOptions Parameter group. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return response containing the status of operations for all documents in the indexing request. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return response containing the status of operations for all documents in the indexing + * request along with {@link Response}. */ @ServiceMethod(returns = ReturnType.SINGLE) - public IndexDocumentsResult index(IndexBatch batch, RequestOptions requestOptions) { - return indexWithResponse(batch, requestOptions, Context.NONE).getValue(); + public Response indexWithResponse(String indexName, BinaryData batch, RequestOptions requestOptions) { + final String contentType = "application/json"; + final String accept = "application/json"; + return service.indexSync(this.client.getEndpoint(), this.client.getServiceVersion().getVersion(), indexName, + contentType, accept, batch, requestOptions, Context.NONE); } /** - * Autocompletes incomplete query terms based on input text and matching terms in the index. - * - * @param autocompleteRequest The definition of the Autocomplete request. - * @param requestOptions Parameter group. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the result of Autocomplete query along with {@link Response} on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> autocompletePostWithResponseAsync(AutocompleteRequest autocompleteRequest, - RequestOptions requestOptions) { - return FluxUtil - .withContext(context -> autocompletePostWithResponseAsync(autocompleteRequest, requestOptions, context)); - } - - /** - * Autocompletes incomplete query terms based on input text and matching terms in the index. - * - * @param autocompleteRequest The definition of the Autocomplete request. - * @param requestOptions Parameter group. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * Autocompletes incomplete query terms based on input text and matching terms in + * the index. + *

Query Parameters

+ * + * + * + * + * + * + * + * + * + * + * + *
Query Parameters
NameTypeRequiredDescription
autocompleteModeStringNoSpecifies 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. Allowed values: "oneTerm", "twoTerms", "oneTermWithContext".
$filterStringNoAn OData expression that filters the documents used to produce + * completed terms + * for the Autocomplete result.
fuzzyBooleanNoA 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.
highlightPostTagStringNoA string tag that is appended to hit highlights. Must + * be set with + * highlightPreTag. If omitted, hit highlighting is disabled.
highlightPreTagStringNoA string tag that is prepended to hit highlights. Must + * be set with + * highlightPostTag. If omitted, hit highlighting is disabled.
minimumCoverageDoubleNoA 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.
searchFieldsList<String>NoThe list of field names to consider when + * querying for auto-completed terms. + * Target fields must be included in the specified suggester. In the form of "," separated string.
$topIntegerNoThe number of auto-completed terms to retrieve. This must be a + * value between 1 + * and 100. The default is 5.
+ * You can add these to a request with {@link RequestOptions#addQueryParam} + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     @search.coverage: Double (Optional)
+     *     value (Required): [
+     *          (Required){
+     *             text: String (Required)
+     *             queryPlusText: String (Required)
+     *         }
+     *     ]
+     * }
+     * }
+     * 
+ * + * @param searchText The incomplete term which should be auto-completed. + * @param suggesterName The name of the suggester as specified in the suggesters collection that's part + * of the index definition. + * @param indexName The name of the index. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. * @return the result of Autocomplete query along with {@link Response} on successful completion of {@link Mono}. */ @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> autocompletePostWithResponseAsync(AutocompleteRequest autocompleteRequest, - RequestOptions requestOptions, Context context) { - final String accept = "application/json; odata.metadata=none"; - UUID xMsClientRequestIdInternal = null; - if (requestOptions != null) { - xMsClientRequestIdInternal = requestOptions.getXMsClientRequestId(); - } - UUID xMsClientRequestId = xMsClientRequestIdInternal; - return service.autocompletePost(this.client.getEndpoint(), this.client.getIndexName(), xMsClientRequestId, - this.client.getApiVersion(), accept, autocompleteRequest, context); + public Mono> autocompleteGetWithResponseAsync(String searchText, String suggesterName, + String indexName, RequestOptions requestOptions) { + final String accept = "application/json"; + return FluxUtil.withContext( + context -> service.autocompleteGet(this.client.getEndpoint(), this.client.getServiceVersion().getVersion(), + searchText, suggesterName, indexName, accept, requestOptions, context)); } /** - * Autocompletes incomplete query terms based on input text and matching terms in the index. - * - * @param autocompleteRequest The definition of the Autocomplete request. - * @param requestOptions Parameter group. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the result of Autocomplete query on successful completion of {@link Mono}. + * Autocompletes incomplete query terms based on input text and matching terms in + * the index. + *

Query Parameters

+ * + * + * + * + * + * + * + * + * + * + * + *
Query Parameters
NameTypeRequiredDescription
autocompleteModeStringNoSpecifies 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. Allowed values: "oneTerm", "twoTerms", "oneTermWithContext".
$filterStringNoAn OData expression that filters the documents used to produce + * completed terms + * for the Autocomplete result.
fuzzyBooleanNoA 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.
highlightPostTagStringNoA string tag that is appended to hit highlights. Must + * be set with + * highlightPreTag. If omitted, hit highlighting is disabled.
highlightPreTagStringNoA string tag that is prepended to hit highlights. Must + * be set with + * highlightPostTag. If omitted, hit highlighting is disabled.
minimumCoverageDoubleNoA 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.
searchFieldsList<String>NoThe list of field names to consider when + * querying for auto-completed terms. + * Target fields must be included in the specified suggester. In the form of "," separated string.
$topIntegerNoThe number of auto-completed terms to retrieve. This must be a + * value between 1 + * and 100. The default is 5.
+ * You can add these to a request with {@link RequestOptions#addQueryParam} + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     @search.coverage: Double (Optional)
+     *     value (Required): [
+     *          (Required){
+     *             text: String (Required)
+     *             queryPlusText: String (Required)
+     *         }
+     *     ]
+     * }
+     * }
+     * 
+ * + * @param searchText The incomplete term which should be auto-completed. + * @param suggesterName The name of the suggester as specified in the suggesters collection that's part + * of the index definition. + * @param indexName The name of the index. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return the result of Autocomplete query along with {@link Response}. */ @ServiceMethod(returns = ReturnType.SINGLE) - public Mono autocompletePostAsync(AutocompleteRequest autocompleteRequest, + public Response autocompleteGetWithResponse(String searchText, String suggesterName, String indexName, RequestOptions requestOptions) { - return autocompletePostWithResponseAsync(autocompleteRequest, requestOptions) - .flatMap(res -> Mono.justOrEmpty(res.getValue())); + final String accept = "application/json"; + return service.autocompleteGetSync(this.client.getEndpoint(), this.client.getServiceVersion().getVersion(), + searchText, suggesterName, indexName, accept, requestOptions, Context.NONE); } /** - * Autocompletes incomplete query terms based on input text and matching terms in the index. - * + * Autocompletes incomplete query terms based on input text and matching terms in + * the index. + *

Request Body Schema

+ * + *
+     * {@code
+     * {
+     *     search: String (Required)
+     *     autocompleteMode: String(oneTerm/twoTerms/oneTermWithContext) (Optional)
+     *     filter: String (Optional)
+     *     fuzzy: Boolean (Optional)
+     *     highlightPostTag: String (Optional)
+     *     highlightPreTag: String (Optional)
+     *     minimumCoverage: Double (Optional)
+     *     searchFields: String (Optional)
+     *     suggesterName: String (Required)
+     *     top: Integer (Optional)
+     * }
+     * }
+     * 
+ * + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     @search.coverage: Double (Optional)
+     *     value (Required): [
+     *          (Required){
+     *             text: String (Required)
+     *             queryPlusText: String (Required)
+     *         }
+     *     ]
+     * }
+     * }
+     * 
+ * + * @param indexName The name of the index. * @param autocompleteRequest The definition of the Autocomplete request. - * @param requestOptions Parameter group. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the result of Autocomplete query on successful completion of {@link Mono}. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return the result of Autocomplete query along with {@link Response} on successful completion of {@link Mono}. */ @ServiceMethod(returns = ReturnType.SINGLE) - public Mono autocompletePostAsync(AutocompleteRequest autocompleteRequest, - RequestOptions requestOptions, Context context) { - return autocompletePostWithResponseAsync(autocompleteRequest, requestOptions, context) - .flatMap(res -> Mono.justOrEmpty(res.getValue())); + public Mono> autocompletePostWithResponseAsync(String indexName, + BinaryData autocompleteRequest, RequestOptions requestOptions) { + final String contentType = "application/json"; + final String accept = "application/json"; + return FluxUtil.withContext( + context -> service.autocompletePost(this.client.getEndpoint(), this.client.getServiceVersion().getVersion(), + indexName, contentType, accept, autocompleteRequest, requestOptions, context)); } /** - * Autocompletes incomplete query terms based on input text and matching terms in the index. - * + * Autocompletes incomplete query terms based on input text and matching terms in + * the index. + *

Request Body Schema

+ * + *
+     * {@code
+     * {
+     *     search: String (Required)
+     *     autocompleteMode: String(oneTerm/twoTerms/oneTermWithContext) (Optional)
+     *     filter: String (Optional)
+     *     fuzzy: Boolean (Optional)
+     *     highlightPostTag: String (Optional)
+     *     highlightPreTag: String (Optional)
+     *     minimumCoverage: Double (Optional)
+     *     searchFields: String (Optional)
+     *     suggesterName: String (Required)
+     *     top: Integer (Optional)
+     * }
+     * }
+     * 
+ * + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     @search.coverage: Double (Optional)
+     *     value (Required): [
+     *          (Required){
+     *             text: String (Required)
+     *             queryPlusText: String (Required)
+     *         }
+     *     ]
+     * }
+     * }
+     * 
+ * + * @param indexName The name of the index. * @param autocompleteRequest The definition of the Autocomplete request. - * @param requestOptions Parameter group. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. * @return the result of Autocomplete query along with {@link Response}. */ @ServiceMethod(returns = ReturnType.SINGLE) - public Response autocompletePostWithResponse(AutocompleteRequest autocompleteRequest, - RequestOptions requestOptions, Context context) { - final String accept = "application/json; odata.metadata=none"; - UUID xMsClientRequestIdInternal = null; - if (requestOptions != null) { - xMsClientRequestIdInternal = requestOptions.getXMsClientRequestId(); - } - UUID xMsClientRequestId = xMsClientRequestIdInternal; - return service.autocompletePostSync(this.client.getEndpoint(), this.client.getIndexName(), xMsClientRequestId, - this.client.getApiVersion(), accept, autocompleteRequest, context); - } - - /** - * Autocompletes incomplete query terms based on input text and matching terms in the index. - * - * @param autocompleteRequest The definition of the Autocomplete request. - * @param requestOptions Parameter group. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the result of Autocomplete query. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public AutocompleteResult autocompletePost(AutocompleteRequest autocompleteRequest, RequestOptions requestOptions) { - return autocompletePostWithResponse(autocompleteRequest, requestOptions, Context.NONE).getValue(); + public Response autocompletePostWithResponse(String indexName, BinaryData autocompleteRequest, + RequestOptions requestOptions) { + final String contentType = "application/json"; + final String accept = "application/json"; + return service.autocompletePostSync(this.client.getEndpoint(), this.client.getServiceVersion().getVersion(), + indexName, contentType, accept, autocompleteRequest, requestOptions, Context.NONE); } } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/implementation/IndexersImpl.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/implementation/IndexersImpl.java new file mode 100644 index 000000000000..873e2b9b306a --- /dev/null +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/implementation/IndexersImpl.java @@ -0,0 +1,1837 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.search.documents.implementation; + +import com.azure.core.annotation.BodyParam; +import com.azure.core.annotation.Delete; +import com.azure.core.annotation.ExpectedResponses; +import com.azure.core.annotation.Get; +import com.azure.core.annotation.HeaderParam; +import com.azure.core.annotation.Host; +import com.azure.core.annotation.HostParam; +import com.azure.core.annotation.PathParam; +import com.azure.core.annotation.Post; +import com.azure.core.annotation.Put; +import com.azure.core.annotation.QueryParam; +import com.azure.core.annotation.ReturnType; +import com.azure.core.annotation.ServiceInterface; +import com.azure.core.annotation.ServiceMethod; +import com.azure.core.annotation.UnexpectedResponseExceptionType; +import com.azure.core.exception.ClientAuthenticationException; +import com.azure.core.exception.HttpResponseException; +import com.azure.core.exception.ResourceModifiedException; +import com.azure.core.exception.ResourceNotFoundException; +import com.azure.core.http.HttpHeaderName; +import com.azure.core.http.rest.RequestOptions; +import com.azure.core.http.rest.Response; +import com.azure.core.http.rest.RestProxy; +import com.azure.core.util.BinaryData; +import com.azure.core.util.Context; +import com.azure.core.util.FluxUtil; +import com.azure.search.documents.SearchServiceVersion; +import reactor.core.publisher.Mono; + +/** + * An instance of this class provides access to all the operations defined in Indexers. + */ +public final class IndexersImpl { + /** + * The proxy service used to perform REST calls. + */ + private final IndexersService service; + + /** + * The service client containing this operation class. + */ + private final SearchClientImpl client; + + /** + * Initializes an instance of IndexersImpl. + * + * @param client the instance of the service client containing this operation class. + */ + IndexersImpl(SearchClientImpl client) { + this.service = RestProxy.create(IndexersService.class, client.getHttpPipeline(), client.getSerializerAdapter()); + this.client = client; + } + + /** + * Gets Service version. + * + * @return the serviceVersion value. + */ + public SearchServiceVersion getServiceVersion() { + return client.getServiceVersion(); + } + + /** + * The interface defining all the services for SearchClientIndexers to be used by the proxy service to perform REST + * calls. + */ + @Host("{endpoint}") + @ServiceInterface(name = "SearchClientIndexers") + public interface IndexersService { + @Post("/indexers('{indexerName}')/search.reset") + @ExpectedResponses({ 204 }) + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Mono> reset(@HostParam("endpoint") String endpoint, @QueryParam("api-version") String apiVersion, + @PathParam("indexerName") String indexerName, @HeaderParam("Accept") String accept, + RequestOptions requestOptions, Context context); + + @Post("/indexers('{indexerName}')/search.reset") + @ExpectedResponses({ 204 }) + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Response resetSync(@HostParam("endpoint") String endpoint, @QueryParam("api-version") String apiVersion, + @PathParam("indexerName") String indexerName, @HeaderParam("Accept") String accept, + RequestOptions requestOptions, Context context); + + @Post("/indexers('{indexerName}')/search.resetdocs") + @ExpectedResponses({ 204 }) + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Mono> resetDocs(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @PathParam("indexerName") String indexerName, + @HeaderParam("Accept") String accept, RequestOptions requestOptions, Context context); + + @Post("/indexers('{indexerName}')/search.resetdocs") + @ExpectedResponses({ 204 }) + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Response resetDocsSync(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @PathParam("indexerName") String indexerName, + @HeaderParam("Accept") String accept, RequestOptions requestOptions, Context context); + + @Post("/indexers('{indexerName}')/search.run") + @ExpectedResponses({ 202 }) + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Mono> run(@HostParam("endpoint") String endpoint, @QueryParam("api-version") String apiVersion, + @PathParam("indexerName") String indexerName, @HeaderParam("Accept") String accept, + RequestOptions requestOptions, Context context); + + @Post("/indexers('{indexerName}')/search.run") + @ExpectedResponses({ 202 }) + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Response runSync(@HostParam("endpoint") String endpoint, @QueryParam("api-version") String apiVersion, + @PathParam("indexerName") String indexerName, @HeaderParam("Accept") String accept, + RequestOptions requestOptions, Context context); + + @Put("/indexers('{indexerName}')") + @ExpectedResponses({ 200, 201 }) + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Mono> createOrUpdate(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @HeaderParam("Prefer") String prefer, + @PathParam("indexerName") String indexerName, @HeaderParam("Content-Type") String contentType, + @HeaderParam("Accept") String accept, @BodyParam("application/json") BinaryData indexer, + RequestOptions requestOptions, Context context); + + @Put("/indexers('{indexerName}')") + @ExpectedResponses({ 200, 201 }) + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Response createOrUpdateSync(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @HeaderParam("Prefer") String prefer, + @PathParam("indexerName") String indexerName, @HeaderParam("Content-Type") String contentType, + @HeaderParam("Accept") String accept, @BodyParam("application/json") BinaryData indexer, + RequestOptions requestOptions, Context context); + + @Delete("/indexers('{indexerName}')") + @ExpectedResponses({ 204, 404 }) + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Mono> delete(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @PathParam("indexerName") String indexerName, + @HeaderParam("Accept") String accept, RequestOptions requestOptions, Context context); + + @Delete("/indexers('{indexerName}')") + @ExpectedResponses({ 204, 404 }) + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Response deleteSync(@HostParam("endpoint") String endpoint, @QueryParam("api-version") String apiVersion, + @PathParam("indexerName") String indexerName, @HeaderParam("Accept") String accept, + RequestOptions requestOptions, Context context); + + @Get("/indexers('{indexerName}')") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Mono> get(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @PathParam("indexerName") String indexerName, + @HeaderParam("Accept") String accept, RequestOptions requestOptions, Context context); + + @Get("/indexers('{indexerName}')") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Response getSync(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @PathParam("indexerName") String indexerName, + @HeaderParam("Accept") String accept, RequestOptions requestOptions, Context context); + + @Get("/indexers") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Mono> list(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, + RequestOptions requestOptions, Context context); + + @Get("/indexers") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Response listSync(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, + RequestOptions requestOptions, Context context); + + @Post("/indexers") + @ExpectedResponses({ 201 }) + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Mono> create(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @HeaderParam("Content-Type") String contentType, + @HeaderParam("Accept") String accept, @BodyParam("application/json") BinaryData indexer, + RequestOptions requestOptions, Context context); + + @Post("/indexers") + @ExpectedResponses({ 201 }) + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Response createSync(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @HeaderParam("Content-Type") String contentType, + @HeaderParam("Accept") String accept, @BodyParam("application/json") BinaryData indexer, + RequestOptions requestOptions, Context context); + + @Get("/indexers('{indexerName}')/search.status") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Mono> getStatus(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @PathParam("indexerName") String indexerName, + @HeaderParam("Accept") String accept, RequestOptions requestOptions, Context context); + + @Get("/indexers('{indexerName}')/search.status") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Response getStatusSync(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @PathParam("indexerName") String indexerName, + @HeaderParam("Accept") String accept, RequestOptions requestOptions, Context context); + } + + /** + * Resets the change tracking state associated with an indexer. + * + * @param indexerName The name of the indexer. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return the {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono> resetWithResponseAsync(String indexerName, RequestOptions requestOptions) { + final String accept = "application/json"; + return FluxUtil.withContext(context -> service.reset(this.client.getEndpoint(), + this.client.getServiceVersion().getVersion(), indexerName, accept, requestOptions, context)); + } + + /** + * Resets the change tracking state associated with an indexer. + * + * @param indexerName The name of the indexer. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return the {@link Response}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Response resetWithResponse(String indexerName, RequestOptions requestOptions) { + final String accept = "application/json"; + return service.resetSync(this.client.getEndpoint(), this.client.getServiceVersion().getVersion(), indexerName, + accept, requestOptions, Context.NONE); + } + + /** + * Resets specific documents in the datasource to be selectively re-ingested by + * the indexer. + *

Query Parameters

+ * + * + * + * + *
Query Parameters
NameTypeRequiredDescription
overwriteBooleanNoIf 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.
+ * You can add these to a request with {@link RequestOptions#addQueryParam} + *

Header Parameters

+ * + * + * + * + *
Header Parameters
NameTypeRequiredDescription
Content-TypeStringNoThe content type. Allowed values: + * "application/json".
+ * You can add these to a request with {@link RequestOptions#addHeader} + *

Request Body Schema

+ * + *
+     * {@code
+     * {
+     *     documentKeys (Optional): [
+     *         String (Optional)
+     *     ]
+     *     datasourceDocumentIds (Optional): [
+     *         String (Optional)
+     *     ]
+     * }
+     * }
+     * 
+ * + * @param indexerName The name of the indexer. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return the {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono> resetDocsWithResponseAsync(String indexerName, RequestOptions requestOptions) { + final String accept = "application/json"; + RequestOptions requestOptionsLocal = requestOptions == null ? new RequestOptions() : requestOptions; + requestOptionsLocal.addRequestCallback(requestLocal -> { + if (requestLocal.getBody() != null && requestLocal.getHeaders().get(HttpHeaderName.CONTENT_TYPE) == null) { + requestLocal.getHeaders().set(HttpHeaderName.CONTENT_TYPE, "application/json"); + } + }); + return FluxUtil.withContext(context -> service.resetDocs(this.client.getEndpoint(), + this.client.getServiceVersion().getVersion(), indexerName, accept, requestOptionsLocal, context)); + } + + /** + * Resets specific documents in the datasource to be selectively re-ingested by + * the indexer. + *

Query Parameters

+ * + * + * + * + *
Query Parameters
NameTypeRequiredDescription
overwriteBooleanNoIf 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.
+ * You can add these to a request with {@link RequestOptions#addQueryParam} + *

Header Parameters

+ * + * + * + * + *
Header Parameters
NameTypeRequiredDescription
Content-TypeStringNoThe content type. Allowed values: + * "application/json".
+ * You can add these to a request with {@link RequestOptions#addHeader} + *

Request Body Schema

+ * + *
+     * {@code
+     * {
+     *     documentKeys (Optional): [
+     *         String (Optional)
+     *     ]
+     *     datasourceDocumentIds (Optional): [
+     *         String (Optional)
+     *     ]
+     * }
+     * }
+     * 
+ * + * @param indexerName The name of the indexer. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return the {@link Response}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Response resetDocsWithResponse(String indexerName, RequestOptions requestOptions) { + final String accept = "application/json"; + RequestOptions requestOptionsLocal = requestOptions == null ? new RequestOptions() : requestOptions; + requestOptionsLocal.addRequestCallback(requestLocal -> { + if (requestLocal.getBody() != null && requestLocal.getHeaders().get(HttpHeaderName.CONTENT_TYPE) == null) { + requestLocal.getHeaders().set(HttpHeaderName.CONTENT_TYPE, "application/json"); + } + }); + return service.resetDocsSync(this.client.getEndpoint(), this.client.getServiceVersion().getVersion(), + indexerName, accept, requestOptionsLocal, Context.NONE); + } + + /** + * Runs an indexer on-demand. + * + * @param indexerName The name of the indexer. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return the {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono> runWithResponseAsync(String indexerName, RequestOptions requestOptions) { + final String accept = "application/json"; + return FluxUtil.withContext(context -> service.run(this.client.getEndpoint(), + this.client.getServiceVersion().getVersion(), indexerName, accept, requestOptions, context)); + } + + /** + * Runs an indexer on-demand. + * + * @param indexerName The name of the indexer. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return the {@link Response}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Response runWithResponse(String indexerName, RequestOptions requestOptions) { + final String accept = "application/json"; + return service.runSync(this.client.getEndpoint(), this.client.getServiceVersion().getVersion(), indexerName, + accept, requestOptions, Context.NONE); + } + + /** + * Creates a new indexer or updates an indexer if it already exists. + *

Query Parameters

+ * + * + * + * + * + *
Query Parameters
NameTypeRequiredDescription
ignoreResetRequirementsBooleanNoIgnores cache reset requirements.
disableCacheReprocessingChangeDetectionBooleanNoDisables cache reprocessing + * change detection.
+ * You can add these to a request with {@link RequestOptions#addQueryParam} + *

Header Parameters

+ * + * + * + * + * + *
Header Parameters
NameTypeRequiredDescription
If-MatchStringNoDefines the If-Match condition. The operation will be + * performed only if the ETag on the server matches this value.
If-None-MatchStringNoDefines the If-None-Match condition. The operation will + * be performed only if the ETag on the server does not match this value.
+ * You can add these to a request with {@link RequestOptions#addHeader} + *

Request Body Schema

+ * + *
+     * {@code
+     * {
+     *     name: String (Required)
+     *     description: String (Optional)
+     *     dataSourceName: String (Required)
+     *     skillsetName: String (Optional)
+     *     targetIndexName: String (Required)
+     *     schedule (Optional): {
+     *         interval: Duration (Required)
+     *         startTime: OffsetDateTime (Optional)
+     *     }
+     *     parameters (Optional): {
+     *         batchSize: Integer (Optional)
+     *         maxFailedItems: Integer (Optional)
+     *         maxFailedItemsPerBatch: Integer (Optional)
+     *         configuration (Optional): {
+     *             parsingMode: String(default/text/delimitedText/json/jsonArray/jsonLines/markdown) (Optional)
+     *             excludedFileNameExtensions: String (Optional)
+     *             indexedFileNameExtensions: String (Optional)
+     *             failOnUnsupportedContentType: Boolean (Optional)
+     *             failOnUnprocessableDocument: Boolean (Optional)
+     *             indexStorageMetadataOnlyForOversizedDocuments: Boolean (Optional)
+     *             delimitedTextHeaders: String (Optional)
+     *             delimitedTextDelimiter: String (Optional)
+     *             firstLineContainsHeaders: Boolean (Optional)
+     *             markdownParsingSubmode: String(oneToMany/oneToOne) (Optional)
+     *             markdownHeaderDepth: String(h1/h2/h3/h4/h5/h6) (Optional)
+     *             documentRoot: String (Optional)
+     *             dataToExtract: String(storageMetadata/allMetadata/contentAndMetadata) (Optional)
+     *             imageAction: String(none/generateNormalizedImages/generateNormalizedImagePerPage) (Optional)
+     *             allowSkillsetToReadFileData: Boolean (Optional)
+     *             pdfTextRotationAlgorithm: String(none/detectAngles) (Optional)
+     *             executionEnvironment: String(standard/private) (Optional)
+     *             queryTimeout: String (Optional)
+     *              (Optional): {
+     *                 String: BinaryData (Required)
+     *             }
+     *         }
+     *     }
+     *     fieldMappings (Optional): [
+     *          (Optional){
+     *             sourceFieldName: String (Required)
+     *             targetFieldName: String (Optional)
+     *             mappingFunction (Optional): {
+     *                 name: String (Required)
+     *                 parameters (Optional): {
+     *                     String: BinaryData (Required)
+     *                 }
+     *             }
+     *         }
+     *     ]
+     *     outputFieldMappings (Optional): [
+     *         (recursive schema, see above)
+     *     ]
+     *     disabled: Boolean (Optional)
+     *     @odata.etag: String (Optional)
+     *     encryptionKey (Optional): {
+     *         keyVaultKeyName: String (Required)
+     *         keyVaultKeyVersion: String (Optional)
+     *         keyVaultUri: String (Required)
+     *         accessCredentials (Optional): {
+     *             applicationId: String (Required)
+     *             applicationSecret: String (Optional)
+     *         }
+     *         identity (Optional): {
+     *             @odata.type: String (Required)
+     *         }
+     *     }
+     *     cache (Optional): {
+     *         storageConnectionString: String (Optional)
+     *         enableReprocessing: Boolean (Optional)
+     *         identity (Optional): (recursive schema, see identity above)
+     *         id: String (Optional)
+     *     }
+     * }
+     * }
+     * 
+ * + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     name: String (Required)
+     *     description: String (Optional)
+     *     dataSourceName: String (Required)
+     *     skillsetName: String (Optional)
+     *     targetIndexName: String (Required)
+     *     schedule (Optional): {
+     *         interval: Duration (Required)
+     *         startTime: OffsetDateTime (Optional)
+     *     }
+     *     parameters (Optional): {
+     *         batchSize: Integer (Optional)
+     *         maxFailedItems: Integer (Optional)
+     *         maxFailedItemsPerBatch: Integer (Optional)
+     *         configuration (Optional): {
+     *             parsingMode: String(default/text/delimitedText/json/jsonArray/jsonLines/markdown) (Optional)
+     *             excludedFileNameExtensions: String (Optional)
+     *             indexedFileNameExtensions: String (Optional)
+     *             failOnUnsupportedContentType: Boolean (Optional)
+     *             failOnUnprocessableDocument: Boolean (Optional)
+     *             indexStorageMetadataOnlyForOversizedDocuments: Boolean (Optional)
+     *             delimitedTextHeaders: String (Optional)
+     *             delimitedTextDelimiter: String (Optional)
+     *             firstLineContainsHeaders: Boolean (Optional)
+     *             markdownParsingSubmode: String(oneToMany/oneToOne) (Optional)
+     *             markdownHeaderDepth: String(h1/h2/h3/h4/h5/h6) (Optional)
+     *             documentRoot: String (Optional)
+     *             dataToExtract: String(storageMetadata/allMetadata/contentAndMetadata) (Optional)
+     *             imageAction: String(none/generateNormalizedImages/generateNormalizedImagePerPage) (Optional)
+     *             allowSkillsetToReadFileData: Boolean (Optional)
+     *             pdfTextRotationAlgorithm: String(none/detectAngles) (Optional)
+     *             executionEnvironment: String(standard/private) (Optional)
+     *             queryTimeout: String (Optional)
+     *              (Optional): {
+     *                 String: BinaryData (Required)
+     *             }
+     *         }
+     *     }
+     *     fieldMappings (Optional): [
+     *          (Optional){
+     *             sourceFieldName: String (Required)
+     *             targetFieldName: String (Optional)
+     *             mappingFunction (Optional): {
+     *                 name: String (Required)
+     *                 parameters (Optional): {
+     *                     String: BinaryData (Required)
+     *                 }
+     *             }
+     *         }
+     *     ]
+     *     outputFieldMappings (Optional): [
+     *         (recursive schema, see above)
+     *     ]
+     *     disabled: Boolean (Optional)
+     *     @odata.etag: String (Optional)
+     *     encryptionKey (Optional): {
+     *         keyVaultKeyName: String (Required)
+     *         keyVaultKeyVersion: String (Optional)
+     *         keyVaultUri: String (Required)
+     *         accessCredentials (Optional): {
+     *             applicationId: String (Required)
+     *             applicationSecret: String (Optional)
+     *         }
+     *         identity (Optional): {
+     *             @odata.type: String (Required)
+     *         }
+     *     }
+     *     cache (Optional): {
+     *         storageConnectionString: String (Optional)
+     *         enableReprocessing: Boolean (Optional)
+     *         identity (Optional): (recursive schema, see identity above)
+     *         id: String (Optional)
+     *     }
+     * }
+     * }
+     * 
+ * + * @param indexerName The name of the indexer. + * @param indexer The definition of the indexer to create or update. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return represents an indexer along with {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono> createOrUpdateWithResponseAsync(String indexerName, BinaryData indexer, + RequestOptions requestOptions) { + final String prefer = "return=representation"; + final String contentType = "application/json"; + final String accept = "application/json"; + return FluxUtil.withContext( + context -> service.createOrUpdate(this.client.getEndpoint(), this.client.getServiceVersion().getVersion(), + prefer, indexerName, contentType, accept, indexer, requestOptions, context)); + } + + /** + * Creates a new indexer or updates an indexer if it already exists. + *

Query Parameters

+ * + * + * + * + * + *
Query Parameters
NameTypeRequiredDescription
ignoreResetRequirementsBooleanNoIgnores cache reset requirements.
disableCacheReprocessingChangeDetectionBooleanNoDisables cache reprocessing + * change detection.
+ * You can add these to a request with {@link RequestOptions#addQueryParam} + *

Header Parameters

+ * + * + * + * + * + *
Header Parameters
NameTypeRequiredDescription
If-MatchStringNoDefines the If-Match condition. The operation will be + * performed only if the ETag on the server matches this value.
If-None-MatchStringNoDefines the If-None-Match condition. The operation will + * be performed only if the ETag on the server does not match this value.
+ * You can add these to a request with {@link RequestOptions#addHeader} + *

Request Body Schema

+ * + *
+     * {@code
+     * {
+     *     name: String (Required)
+     *     description: String (Optional)
+     *     dataSourceName: String (Required)
+     *     skillsetName: String (Optional)
+     *     targetIndexName: String (Required)
+     *     schedule (Optional): {
+     *         interval: Duration (Required)
+     *         startTime: OffsetDateTime (Optional)
+     *     }
+     *     parameters (Optional): {
+     *         batchSize: Integer (Optional)
+     *         maxFailedItems: Integer (Optional)
+     *         maxFailedItemsPerBatch: Integer (Optional)
+     *         configuration (Optional): {
+     *             parsingMode: String(default/text/delimitedText/json/jsonArray/jsonLines/markdown) (Optional)
+     *             excludedFileNameExtensions: String (Optional)
+     *             indexedFileNameExtensions: String (Optional)
+     *             failOnUnsupportedContentType: Boolean (Optional)
+     *             failOnUnprocessableDocument: Boolean (Optional)
+     *             indexStorageMetadataOnlyForOversizedDocuments: Boolean (Optional)
+     *             delimitedTextHeaders: String (Optional)
+     *             delimitedTextDelimiter: String (Optional)
+     *             firstLineContainsHeaders: Boolean (Optional)
+     *             markdownParsingSubmode: String(oneToMany/oneToOne) (Optional)
+     *             markdownHeaderDepth: String(h1/h2/h3/h4/h5/h6) (Optional)
+     *             documentRoot: String (Optional)
+     *             dataToExtract: String(storageMetadata/allMetadata/contentAndMetadata) (Optional)
+     *             imageAction: String(none/generateNormalizedImages/generateNormalizedImagePerPage) (Optional)
+     *             allowSkillsetToReadFileData: Boolean (Optional)
+     *             pdfTextRotationAlgorithm: String(none/detectAngles) (Optional)
+     *             executionEnvironment: String(standard/private) (Optional)
+     *             queryTimeout: String (Optional)
+     *              (Optional): {
+     *                 String: BinaryData (Required)
+     *             }
+     *         }
+     *     }
+     *     fieldMappings (Optional): [
+     *          (Optional){
+     *             sourceFieldName: String (Required)
+     *             targetFieldName: String (Optional)
+     *             mappingFunction (Optional): {
+     *                 name: String (Required)
+     *                 parameters (Optional): {
+     *                     String: BinaryData (Required)
+     *                 }
+     *             }
+     *         }
+     *     ]
+     *     outputFieldMappings (Optional): [
+     *         (recursive schema, see above)
+     *     ]
+     *     disabled: Boolean (Optional)
+     *     @odata.etag: String (Optional)
+     *     encryptionKey (Optional): {
+     *         keyVaultKeyName: String (Required)
+     *         keyVaultKeyVersion: String (Optional)
+     *         keyVaultUri: String (Required)
+     *         accessCredentials (Optional): {
+     *             applicationId: String (Required)
+     *             applicationSecret: String (Optional)
+     *         }
+     *         identity (Optional): {
+     *             @odata.type: String (Required)
+     *         }
+     *     }
+     *     cache (Optional): {
+     *         storageConnectionString: String (Optional)
+     *         enableReprocessing: Boolean (Optional)
+     *         identity (Optional): (recursive schema, see identity above)
+     *         id: String (Optional)
+     *     }
+     * }
+     * }
+     * 
+ * + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     name: String (Required)
+     *     description: String (Optional)
+     *     dataSourceName: String (Required)
+     *     skillsetName: String (Optional)
+     *     targetIndexName: String (Required)
+     *     schedule (Optional): {
+     *         interval: Duration (Required)
+     *         startTime: OffsetDateTime (Optional)
+     *     }
+     *     parameters (Optional): {
+     *         batchSize: Integer (Optional)
+     *         maxFailedItems: Integer (Optional)
+     *         maxFailedItemsPerBatch: Integer (Optional)
+     *         configuration (Optional): {
+     *             parsingMode: String(default/text/delimitedText/json/jsonArray/jsonLines/markdown) (Optional)
+     *             excludedFileNameExtensions: String (Optional)
+     *             indexedFileNameExtensions: String (Optional)
+     *             failOnUnsupportedContentType: Boolean (Optional)
+     *             failOnUnprocessableDocument: Boolean (Optional)
+     *             indexStorageMetadataOnlyForOversizedDocuments: Boolean (Optional)
+     *             delimitedTextHeaders: String (Optional)
+     *             delimitedTextDelimiter: String (Optional)
+     *             firstLineContainsHeaders: Boolean (Optional)
+     *             markdownParsingSubmode: String(oneToMany/oneToOne) (Optional)
+     *             markdownHeaderDepth: String(h1/h2/h3/h4/h5/h6) (Optional)
+     *             documentRoot: String (Optional)
+     *             dataToExtract: String(storageMetadata/allMetadata/contentAndMetadata) (Optional)
+     *             imageAction: String(none/generateNormalizedImages/generateNormalizedImagePerPage) (Optional)
+     *             allowSkillsetToReadFileData: Boolean (Optional)
+     *             pdfTextRotationAlgorithm: String(none/detectAngles) (Optional)
+     *             executionEnvironment: String(standard/private) (Optional)
+     *             queryTimeout: String (Optional)
+     *              (Optional): {
+     *                 String: BinaryData (Required)
+     *             }
+     *         }
+     *     }
+     *     fieldMappings (Optional): [
+     *          (Optional){
+     *             sourceFieldName: String (Required)
+     *             targetFieldName: String (Optional)
+     *             mappingFunction (Optional): {
+     *                 name: String (Required)
+     *                 parameters (Optional): {
+     *                     String: BinaryData (Required)
+     *                 }
+     *             }
+     *         }
+     *     ]
+     *     outputFieldMappings (Optional): [
+     *         (recursive schema, see above)
+     *     ]
+     *     disabled: Boolean (Optional)
+     *     @odata.etag: String (Optional)
+     *     encryptionKey (Optional): {
+     *         keyVaultKeyName: String (Required)
+     *         keyVaultKeyVersion: String (Optional)
+     *         keyVaultUri: String (Required)
+     *         accessCredentials (Optional): {
+     *             applicationId: String (Required)
+     *             applicationSecret: String (Optional)
+     *         }
+     *         identity (Optional): {
+     *             @odata.type: String (Required)
+     *         }
+     *     }
+     *     cache (Optional): {
+     *         storageConnectionString: String (Optional)
+     *         enableReprocessing: Boolean (Optional)
+     *         identity (Optional): (recursive schema, see identity above)
+     *         id: String (Optional)
+     *     }
+     * }
+     * }
+     * 
+ * + * @param indexerName The name of the indexer. + * @param indexer The definition of the indexer to create or update. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return represents an indexer along with {@link Response}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Response createOrUpdateWithResponse(String indexerName, BinaryData indexer, + RequestOptions requestOptions) { + final String prefer = "return=representation"; + final String contentType = "application/json"; + final String accept = "application/json"; + return service.createOrUpdateSync(this.client.getEndpoint(), this.client.getServiceVersion().getVersion(), + prefer, indexerName, contentType, accept, indexer, requestOptions, Context.NONE); + } + + /** + * Deletes an indexer. + *

Header Parameters

+ * + * + * + * + * + *
Header Parameters
NameTypeRequiredDescription
If-MatchStringNoDefines the If-Match condition. The operation will be + * performed only if the ETag on the server matches this value.
If-None-MatchStringNoDefines the If-None-Match condition. The operation will + * be performed only if the ETag on the server does not match this value.
+ * You can add these to a request with {@link RequestOptions#addHeader} + * + * @param indexerName The name of the indexer. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return the {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono> deleteWithResponseAsync(String indexerName, RequestOptions requestOptions) { + final String accept = "application/json"; + return FluxUtil.withContext(context -> service.delete(this.client.getEndpoint(), + this.client.getServiceVersion().getVersion(), indexerName, accept, requestOptions, context)); + } + + /** + * Deletes an indexer. + *

Header Parameters

+ * + * + * + * + * + *
Header Parameters
NameTypeRequiredDescription
If-MatchStringNoDefines the If-Match condition. The operation will be + * performed only if the ETag on the server matches this value.
If-None-MatchStringNoDefines the If-None-Match condition. The operation will + * be performed only if the ETag on the server does not match this value.
+ * You can add these to a request with {@link RequestOptions#addHeader} + * + * @param indexerName The name of the indexer. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return the {@link Response}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Response deleteWithResponse(String indexerName, RequestOptions requestOptions) { + final String accept = "application/json"; + return service.deleteSync(this.client.getEndpoint(), this.client.getServiceVersion().getVersion(), indexerName, + accept, requestOptions, Context.NONE); + } + + /** + * Retrieves an indexer definition. + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     name: String (Required)
+     *     description: String (Optional)
+     *     dataSourceName: String (Required)
+     *     skillsetName: String (Optional)
+     *     targetIndexName: String (Required)
+     *     schedule (Optional): {
+     *         interval: Duration (Required)
+     *         startTime: OffsetDateTime (Optional)
+     *     }
+     *     parameters (Optional): {
+     *         batchSize: Integer (Optional)
+     *         maxFailedItems: Integer (Optional)
+     *         maxFailedItemsPerBatch: Integer (Optional)
+     *         configuration (Optional): {
+     *             parsingMode: String(default/text/delimitedText/json/jsonArray/jsonLines/markdown) (Optional)
+     *             excludedFileNameExtensions: String (Optional)
+     *             indexedFileNameExtensions: String (Optional)
+     *             failOnUnsupportedContentType: Boolean (Optional)
+     *             failOnUnprocessableDocument: Boolean (Optional)
+     *             indexStorageMetadataOnlyForOversizedDocuments: Boolean (Optional)
+     *             delimitedTextHeaders: String (Optional)
+     *             delimitedTextDelimiter: String (Optional)
+     *             firstLineContainsHeaders: Boolean (Optional)
+     *             markdownParsingSubmode: String(oneToMany/oneToOne) (Optional)
+     *             markdownHeaderDepth: String(h1/h2/h3/h4/h5/h6) (Optional)
+     *             documentRoot: String (Optional)
+     *             dataToExtract: String(storageMetadata/allMetadata/contentAndMetadata) (Optional)
+     *             imageAction: String(none/generateNormalizedImages/generateNormalizedImagePerPage) (Optional)
+     *             allowSkillsetToReadFileData: Boolean (Optional)
+     *             pdfTextRotationAlgorithm: String(none/detectAngles) (Optional)
+     *             executionEnvironment: String(standard/private) (Optional)
+     *             queryTimeout: String (Optional)
+     *              (Optional): {
+     *                 String: BinaryData (Required)
+     *             }
+     *         }
+     *     }
+     *     fieldMappings (Optional): [
+     *          (Optional){
+     *             sourceFieldName: String (Required)
+     *             targetFieldName: String (Optional)
+     *             mappingFunction (Optional): {
+     *                 name: String (Required)
+     *                 parameters (Optional): {
+     *                     String: BinaryData (Required)
+     *                 }
+     *             }
+     *         }
+     *     ]
+     *     outputFieldMappings (Optional): [
+     *         (recursive schema, see above)
+     *     ]
+     *     disabled: Boolean (Optional)
+     *     @odata.etag: String (Optional)
+     *     encryptionKey (Optional): {
+     *         keyVaultKeyName: String (Required)
+     *         keyVaultKeyVersion: String (Optional)
+     *         keyVaultUri: String (Required)
+     *         accessCredentials (Optional): {
+     *             applicationId: String (Required)
+     *             applicationSecret: String (Optional)
+     *         }
+     *         identity (Optional): {
+     *             @odata.type: String (Required)
+     *         }
+     *     }
+     *     cache (Optional): {
+     *         storageConnectionString: String (Optional)
+     *         enableReprocessing: Boolean (Optional)
+     *         identity (Optional): (recursive schema, see identity above)
+     *         id: String (Optional)
+     *     }
+     * }
+     * }
+     * 
+ * + * @param indexerName The name of the indexer. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return represents an indexer along with {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono> getWithResponseAsync(String indexerName, RequestOptions requestOptions) { + final String accept = "application/json"; + return FluxUtil.withContext(context -> service.get(this.client.getEndpoint(), + this.client.getServiceVersion().getVersion(), indexerName, accept, requestOptions, context)); + } + + /** + * Retrieves an indexer definition. + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     name: String (Required)
+     *     description: String (Optional)
+     *     dataSourceName: String (Required)
+     *     skillsetName: String (Optional)
+     *     targetIndexName: String (Required)
+     *     schedule (Optional): {
+     *         interval: Duration (Required)
+     *         startTime: OffsetDateTime (Optional)
+     *     }
+     *     parameters (Optional): {
+     *         batchSize: Integer (Optional)
+     *         maxFailedItems: Integer (Optional)
+     *         maxFailedItemsPerBatch: Integer (Optional)
+     *         configuration (Optional): {
+     *             parsingMode: String(default/text/delimitedText/json/jsonArray/jsonLines/markdown) (Optional)
+     *             excludedFileNameExtensions: String (Optional)
+     *             indexedFileNameExtensions: String (Optional)
+     *             failOnUnsupportedContentType: Boolean (Optional)
+     *             failOnUnprocessableDocument: Boolean (Optional)
+     *             indexStorageMetadataOnlyForOversizedDocuments: Boolean (Optional)
+     *             delimitedTextHeaders: String (Optional)
+     *             delimitedTextDelimiter: String (Optional)
+     *             firstLineContainsHeaders: Boolean (Optional)
+     *             markdownParsingSubmode: String(oneToMany/oneToOne) (Optional)
+     *             markdownHeaderDepth: String(h1/h2/h3/h4/h5/h6) (Optional)
+     *             documentRoot: String (Optional)
+     *             dataToExtract: String(storageMetadata/allMetadata/contentAndMetadata) (Optional)
+     *             imageAction: String(none/generateNormalizedImages/generateNormalizedImagePerPage) (Optional)
+     *             allowSkillsetToReadFileData: Boolean (Optional)
+     *             pdfTextRotationAlgorithm: String(none/detectAngles) (Optional)
+     *             executionEnvironment: String(standard/private) (Optional)
+     *             queryTimeout: String (Optional)
+     *              (Optional): {
+     *                 String: BinaryData (Required)
+     *             }
+     *         }
+     *     }
+     *     fieldMappings (Optional): [
+     *          (Optional){
+     *             sourceFieldName: String (Required)
+     *             targetFieldName: String (Optional)
+     *             mappingFunction (Optional): {
+     *                 name: String (Required)
+     *                 parameters (Optional): {
+     *                     String: BinaryData (Required)
+     *                 }
+     *             }
+     *         }
+     *     ]
+     *     outputFieldMappings (Optional): [
+     *         (recursive schema, see above)
+     *     ]
+     *     disabled: Boolean (Optional)
+     *     @odata.etag: String (Optional)
+     *     encryptionKey (Optional): {
+     *         keyVaultKeyName: String (Required)
+     *         keyVaultKeyVersion: String (Optional)
+     *         keyVaultUri: String (Required)
+     *         accessCredentials (Optional): {
+     *             applicationId: String (Required)
+     *             applicationSecret: String (Optional)
+     *         }
+     *         identity (Optional): {
+     *             @odata.type: String (Required)
+     *         }
+     *     }
+     *     cache (Optional): {
+     *         storageConnectionString: String (Optional)
+     *         enableReprocessing: Boolean (Optional)
+     *         identity (Optional): (recursive schema, see identity above)
+     *         id: String (Optional)
+     *     }
+     * }
+     * }
+     * 
+ * + * @param indexerName The name of the indexer. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return represents an indexer along with {@link Response}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Response getWithResponse(String indexerName, RequestOptions requestOptions) { + final String accept = "application/json"; + return service.getSync(this.client.getEndpoint(), this.client.getServiceVersion().getVersion(), indexerName, + accept, requestOptions, Context.NONE); + } + + /** + * Lists all indexers available for a search service. + *

Query Parameters

+ * + * + * + * + *
Query Parameters
NameTypeRequiredDescription
$selectStringNoSelects 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.
+ * You can add these to a request with {@link RequestOptions#addQueryParam} + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     value (Required): [
+     *          (Required){
+     *             name: String (Required)
+     *             description: String (Optional)
+     *             dataSourceName: String (Required)
+     *             skillsetName: String (Optional)
+     *             targetIndexName: String (Required)
+     *             schedule (Optional): {
+     *                 interval: Duration (Required)
+     *                 startTime: OffsetDateTime (Optional)
+     *             }
+     *             parameters (Optional): {
+     *                 batchSize: Integer (Optional)
+     *                 maxFailedItems: Integer (Optional)
+     *                 maxFailedItemsPerBatch: Integer (Optional)
+     *                 configuration (Optional): {
+     *                     parsingMode: String(default/text/delimitedText/json/jsonArray/jsonLines/markdown) (Optional)
+     *                     excludedFileNameExtensions: String (Optional)
+     *                     indexedFileNameExtensions: String (Optional)
+     *                     failOnUnsupportedContentType: Boolean (Optional)
+     *                     failOnUnprocessableDocument: Boolean (Optional)
+     *                     indexStorageMetadataOnlyForOversizedDocuments: Boolean (Optional)
+     *                     delimitedTextHeaders: String (Optional)
+     *                     delimitedTextDelimiter: String (Optional)
+     *                     firstLineContainsHeaders: Boolean (Optional)
+     *                     markdownParsingSubmode: String(oneToMany/oneToOne) (Optional)
+     *                     markdownHeaderDepth: String(h1/h2/h3/h4/h5/h6) (Optional)
+     *                     documentRoot: String (Optional)
+     *                     dataToExtract: String(storageMetadata/allMetadata/contentAndMetadata) (Optional)
+     *                     imageAction: String(none/generateNormalizedImages/generateNormalizedImagePerPage) (Optional)
+     *                     allowSkillsetToReadFileData: Boolean (Optional)
+     *                     pdfTextRotationAlgorithm: String(none/detectAngles) (Optional)
+     *                     executionEnvironment: String(standard/private) (Optional)
+     *                     queryTimeout: String (Optional)
+     *                      (Optional): {
+     *                         String: BinaryData (Required)
+     *                     }
+     *                 }
+     *             }
+     *             fieldMappings (Optional): [
+     *                  (Optional){
+     *                     sourceFieldName: String (Required)
+     *                     targetFieldName: String (Optional)
+     *                     mappingFunction (Optional): {
+     *                         name: String (Required)
+     *                         parameters (Optional): {
+     *                             String: BinaryData (Required)
+     *                         }
+     *                     }
+     *                 }
+     *             ]
+     *             outputFieldMappings (Optional): [
+     *                 (recursive schema, see above)
+     *             ]
+     *             disabled: Boolean (Optional)
+     *             @odata.etag: String (Optional)
+     *             encryptionKey (Optional): {
+     *                 keyVaultKeyName: String (Required)
+     *                 keyVaultKeyVersion: String (Optional)
+     *                 keyVaultUri: String (Required)
+     *                 accessCredentials (Optional): {
+     *                     applicationId: String (Required)
+     *                     applicationSecret: String (Optional)
+     *                 }
+     *                 identity (Optional): {
+     *                     @odata.type: String (Required)
+     *                 }
+     *             }
+     *             cache (Optional): {
+     *                 storageConnectionString: String (Optional)
+     *                 enableReprocessing: Boolean (Optional)
+     *                 identity (Optional): (recursive schema, see identity above)
+     *                 id: String (Optional)
+     *             }
+     *         }
+     *     ]
+     * }
+     * }
+     * 
+ * + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return response from a List Indexers request along with {@link Response} on successful completion of + * {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono> listWithResponseAsync(RequestOptions requestOptions) { + final String accept = "application/json"; + return FluxUtil.withContext(context -> service.list(this.client.getEndpoint(), + this.client.getServiceVersion().getVersion(), accept, requestOptions, context)); + } + + /** + * Lists all indexers available for a search service. + *

Query Parameters

+ * + * + * + * + *
Query Parameters
NameTypeRequiredDescription
$selectStringNoSelects 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.
+ * You can add these to a request with {@link RequestOptions#addQueryParam} + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     value (Required): [
+     *          (Required){
+     *             name: String (Required)
+     *             description: String (Optional)
+     *             dataSourceName: String (Required)
+     *             skillsetName: String (Optional)
+     *             targetIndexName: String (Required)
+     *             schedule (Optional): {
+     *                 interval: Duration (Required)
+     *                 startTime: OffsetDateTime (Optional)
+     *             }
+     *             parameters (Optional): {
+     *                 batchSize: Integer (Optional)
+     *                 maxFailedItems: Integer (Optional)
+     *                 maxFailedItemsPerBatch: Integer (Optional)
+     *                 configuration (Optional): {
+     *                     parsingMode: String(default/text/delimitedText/json/jsonArray/jsonLines/markdown) (Optional)
+     *                     excludedFileNameExtensions: String (Optional)
+     *                     indexedFileNameExtensions: String (Optional)
+     *                     failOnUnsupportedContentType: Boolean (Optional)
+     *                     failOnUnprocessableDocument: Boolean (Optional)
+     *                     indexStorageMetadataOnlyForOversizedDocuments: Boolean (Optional)
+     *                     delimitedTextHeaders: String (Optional)
+     *                     delimitedTextDelimiter: String (Optional)
+     *                     firstLineContainsHeaders: Boolean (Optional)
+     *                     markdownParsingSubmode: String(oneToMany/oneToOne) (Optional)
+     *                     markdownHeaderDepth: String(h1/h2/h3/h4/h5/h6) (Optional)
+     *                     documentRoot: String (Optional)
+     *                     dataToExtract: String(storageMetadata/allMetadata/contentAndMetadata) (Optional)
+     *                     imageAction: String(none/generateNormalizedImages/generateNormalizedImagePerPage) (Optional)
+     *                     allowSkillsetToReadFileData: Boolean (Optional)
+     *                     pdfTextRotationAlgorithm: String(none/detectAngles) (Optional)
+     *                     executionEnvironment: String(standard/private) (Optional)
+     *                     queryTimeout: String (Optional)
+     *                      (Optional): {
+     *                         String: BinaryData (Required)
+     *                     }
+     *                 }
+     *             }
+     *             fieldMappings (Optional): [
+     *                  (Optional){
+     *                     sourceFieldName: String (Required)
+     *                     targetFieldName: String (Optional)
+     *                     mappingFunction (Optional): {
+     *                         name: String (Required)
+     *                         parameters (Optional): {
+     *                             String: BinaryData (Required)
+     *                         }
+     *                     }
+     *                 }
+     *             ]
+     *             outputFieldMappings (Optional): [
+     *                 (recursive schema, see above)
+     *             ]
+     *             disabled: Boolean (Optional)
+     *             @odata.etag: String (Optional)
+     *             encryptionKey (Optional): {
+     *                 keyVaultKeyName: String (Required)
+     *                 keyVaultKeyVersion: String (Optional)
+     *                 keyVaultUri: String (Required)
+     *                 accessCredentials (Optional): {
+     *                     applicationId: String (Required)
+     *                     applicationSecret: String (Optional)
+     *                 }
+     *                 identity (Optional): {
+     *                     @odata.type: String (Required)
+     *                 }
+     *             }
+     *             cache (Optional): {
+     *                 storageConnectionString: String (Optional)
+     *                 enableReprocessing: Boolean (Optional)
+     *                 identity (Optional): (recursive schema, see identity above)
+     *                 id: String (Optional)
+     *             }
+     *         }
+     *     ]
+     * }
+     * }
+     * 
+ * + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return response from a List Indexers request along with {@link Response}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Response listWithResponse(RequestOptions requestOptions) { + final String accept = "application/json"; + return service.listSync(this.client.getEndpoint(), this.client.getServiceVersion().getVersion(), accept, + requestOptions, Context.NONE); + } + + /** + * Creates a new indexer. + *

Request Body Schema

+ * + *
+     * {@code
+     * {
+     *     name: String (Required)
+     *     description: String (Optional)
+     *     dataSourceName: String (Required)
+     *     skillsetName: String (Optional)
+     *     targetIndexName: String (Required)
+     *     schedule (Optional): {
+     *         interval: Duration (Required)
+     *         startTime: OffsetDateTime (Optional)
+     *     }
+     *     parameters (Optional): {
+     *         batchSize: Integer (Optional)
+     *         maxFailedItems: Integer (Optional)
+     *         maxFailedItemsPerBatch: Integer (Optional)
+     *         configuration (Optional): {
+     *             parsingMode: String(default/text/delimitedText/json/jsonArray/jsonLines/markdown) (Optional)
+     *             excludedFileNameExtensions: String (Optional)
+     *             indexedFileNameExtensions: String (Optional)
+     *             failOnUnsupportedContentType: Boolean (Optional)
+     *             failOnUnprocessableDocument: Boolean (Optional)
+     *             indexStorageMetadataOnlyForOversizedDocuments: Boolean (Optional)
+     *             delimitedTextHeaders: String (Optional)
+     *             delimitedTextDelimiter: String (Optional)
+     *             firstLineContainsHeaders: Boolean (Optional)
+     *             markdownParsingSubmode: String(oneToMany/oneToOne) (Optional)
+     *             markdownHeaderDepth: String(h1/h2/h3/h4/h5/h6) (Optional)
+     *             documentRoot: String (Optional)
+     *             dataToExtract: String(storageMetadata/allMetadata/contentAndMetadata) (Optional)
+     *             imageAction: String(none/generateNormalizedImages/generateNormalizedImagePerPage) (Optional)
+     *             allowSkillsetToReadFileData: Boolean (Optional)
+     *             pdfTextRotationAlgorithm: String(none/detectAngles) (Optional)
+     *             executionEnvironment: String(standard/private) (Optional)
+     *             queryTimeout: String (Optional)
+     *              (Optional): {
+     *                 String: BinaryData (Required)
+     *             }
+     *         }
+     *     }
+     *     fieldMappings (Optional): [
+     *          (Optional){
+     *             sourceFieldName: String (Required)
+     *             targetFieldName: String (Optional)
+     *             mappingFunction (Optional): {
+     *                 name: String (Required)
+     *                 parameters (Optional): {
+     *                     String: BinaryData (Required)
+     *                 }
+     *             }
+     *         }
+     *     ]
+     *     outputFieldMappings (Optional): [
+     *         (recursive schema, see above)
+     *     ]
+     *     disabled: Boolean (Optional)
+     *     @odata.etag: String (Optional)
+     *     encryptionKey (Optional): {
+     *         keyVaultKeyName: String (Required)
+     *         keyVaultKeyVersion: String (Optional)
+     *         keyVaultUri: String (Required)
+     *         accessCredentials (Optional): {
+     *             applicationId: String (Required)
+     *             applicationSecret: String (Optional)
+     *         }
+     *         identity (Optional): {
+     *             @odata.type: String (Required)
+     *         }
+     *     }
+     *     cache (Optional): {
+     *         storageConnectionString: String (Optional)
+     *         enableReprocessing: Boolean (Optional)
+     *         identity (Optional): (recursive schema, see identity above)
+     *         id: String (Optional)
+     *     }
+     * }
+     * }
+     * 
+ * + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     name: String (Required)
+     *     description: String (Optional)
+     *     dataSourceName: String (Required)
+     *     skillsetName: String (Optional)
+     *     targetIndexName: String (Required)
+     *     schedule (Optional): {
+     *         interval: Duration (Required)
+     *         startTime: OffsetDateTime (Optional)
+     *     }
+     *     parameters (Optional): {
+     *         batchSize: Integer (Optional)
+     *         maxFailedItems: Integer (Optional)
+     *         maxFailedItemsPerBatch: Integer (Optional)
+     *         configuration (Optional): {
+     *             parsingMode: String(default/text/delimitedText/json/jsonArray/jsonLines/markdown) (Optional)
+     *             excludedFileNameExtensions: String (Optional)
+     *             indexedFileNameExtensions: String (Optional)
+     *             failOnUnsupportedContentType: Boolean (Optional)
+     *             failOnUnprocessableDocument: Boolean (Optional)
+     *             indexStorageMetadataOnlyForOversizedDocuments: Boolean (Optional)
+     *             delimitedTextHeaders: String (Optional)
+     *             delimitedTextDelimiter: String (Optional)
+     *             firstLineContainsHeaders: Boolean (Optional)
+     *             markdownParsingSubmode: String(oneToMany/oneToOne) (Optional)
+     *             markdownHeaderDepth: String(h1/h2/h3/h4/h5/h6) (Optional)
+     *             documentRoot: String (Optional)
+     *             dataToExtract: String(storageMetadata/allMetadata/contentAndMetadata) (Optional)
+     *             imageAction: String(none/generateNormalizedImages/generateNormalizedImagePerPage) (Optional)
+     *             allowSkillsetToReadFileData: Boolean (Optional)
+     *             pdfTextRotationAlgorithm: String(none/detectAngles) (Optional)
+     *             executionEnvironment: String(standard/private) (Optional)
+     *             queryTimeout: String (Optional)
+     *              (Optional): {
+     *                 String: BinaryData (Required)
+     *             }
+     *         }
+     *     }
+     *     fieldMappings (Optional): [
+     *          (Optional){
+     *             sourceFieldName: String (Required)
+     *             targetFieldName: String (Optional)
+     *             mappingFunction (Optional): {
+     *                 name: String (Required)
+     *                 parameters (Optional): {
+     *                     String: BinaryData (Required)
+     *                 }
+     *             }
+     *         }
+     *     ]
+     *     outputFieldMappings (Optional): [
+     *         (recursive schema, see above)
+     *     ]
+     *     disabled: Boolean (Optional)
+     *     @odata.etag: String (Optional)
+     *     encryptionKey (Optional): {
+     *         keyVaultKeyName: String (Required)
+     *         keyVaultKeyVersion: String (Optional)
+     *         keyVaultUri: String (Required)
+     *         accessCredentials (Optional): {
+     *             applicationId: String (Required)
+     *             applicationSecret: String (Optional)
+     *         }
+     *         identity (Optional): {
+     *             @odata.type: String (Required)
+     *         }
+     *     }
+     *     cache (Optional): {
+     *         storageConnectionString: String (Optional)
+     *         enableReprocessing: Boolean (Optional)
+     *         identity (Optional): (recursive schema, see identity above)
+     *         id: String (Optional)
+     *     }
+     * }
+     * }
+     * 
+ * + * @param indexer The definition of the indexer to create. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return represents an indexer along with {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono> createWithResponseAsync(BinaryData indexer, RequestOptions requestOptions) { + final String contentType = "application/json"; + final String accept = "application/json"; + return FluxUtil.withContext(context -> service.create(this.client.getEndpoint(), + this.client.getServiceVersion().getVersion(), contentType, accept, indexer, requestOptions, context)); + } + + /** + * Creates a new indexer. + *

Request Body Schema

+ * + *
+     * {@code
+     * {
+     *     name: String (Required)
+     *     description: String (Optional)
+     *     dataSourceName: String (Required)
+     *     skillsetName: String (Optional)
+     *     targetIndexName: String (Required)
+     *     schedule (Optional): {
+     *         interval: Duration (Required)
+     *         startTime: OffsetDateTime (Optional)
+     *     }
+     *     parameters (Optional): {
+     *         batchSize: Integer (Optional)
+     *         maxFailedItems: Integer (Optional)
+     *         maxFailedItemsPerBatch: Integer (Optional)
+     *         configuration (Optional): {
+     *             parsingMode: String(default/text/delimitedText/json/jsonArray/jsonLines/markdown) (Optional)
+     *             excludedFileNameExtensions: String (Optional)
+     *             indexedFileNameExtensions: String (Optional)
+     *             failOnUnsupportedContentType: Boolean (Optional)
+     *             failOnUnprocessableDocument: Boolean (Optional)
+     *             indexStorageMetadataOnlyForOversizedDocuments: Boolean (Optional)
+     *             delimitedTextHeaders: String (Optional)
+     *             delimitedTextDelimiter: String (Optional)
+     *             firstLineContainsHeaders: Boolean (Optional)
+     *             markdownParsingSubmode: String(oneToMany/oneToOne) (Optional)
+     *             markdownHeaderDepth: String(h1/h2/h3/h4/h5/h6) (Optional)
+     *             documentRoot: String (Optional)
+     *             dataToExtract: String(storageMetadata/allMetadata/contentAndMetadata) (Optional)
+     *             imageAction: String(none/generateNormalizedImages/generateNormalizedImagePerPage) (Optional)
+     *             allowSkillsetToReadFileData: Boolean (Optional)
+     *             pdfTextRotationAlgorithm: String(none/detectAngles) (Optional)
+     *             executionEnvironment: String(standard/private) (Optional)
+     *             queryTimeout: String (Optional)
+     *              (Optional): {
+     *                 String: BinaryData (Required)
+     *             }
+     *         }
+     *     }
+     *     fieldMappings (Optional): [
+     *          (Optional){
+     *             sourceFieldName: String (Required)
+     *             targetFieldName: String (Optional)
+     *             mappingFunction (Optional): {
+     *                 name: String (Required)
+     *                 parameters (Optional): {
+     *                     String: BinaryData (Required)
+     *                 }
+     *             }
+     *         }
+     *     ]
+     *     outputFieldMappings (Optional): [
+     *         (recursive schema, see above)
+     *     ]
+     *     disabled: Boolean (Optional)
+     *     @odata.etag: String (Optional)
+     *     encryptionKey (Optional): {
+     *         keyVaultKeyName: String (Required)
+     *         keyVaultKeyVersion: String (Optional)
+     *         keyVaultUri: String (Required)
+     *         accessCredentials (Optional): {
+     *             applicationId: String (Required)
+     *             applicationSecret: String (Optional)
+     *         }
+     *         identity (Optional): {
+     *             @odata.type: String (Required)
+     *         }
+     *     }
+     *     cache (Optional): {
+     *         storageConnectionString: String (Optional)
+     *         enableReprocessing: Boolean (Optional)
+     *         identity (Optional): (recursive schema, see identity above)
+     *         id: String (Optional)
+     *     }
+     * }
+     * }
+     * 
+ * + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     name: String (Required)
+     *     description: String (Optional)
+     *     dataSourceName: String (Required)
+     *     skillsetName: String (Optional)
+     *     targetIndexName: String (Required)
+     *     schedule (Optional): {
+     *         interval: Duration (Required)
+     *         startTime: OffsetDateTime (Optional)
+     *     }
+     *     parameters (Optional): {
+     *         batchSize: Integer (Optional)
+     *         maxFailedItems: Integer (Optional)
+     *         maxFailedItemsPerBatch: Integer (Optional)
+     *         configuration (Optional): {
+     *             parsingMode: String(default/text/delimitedText/json/jsonArray/jsonLines/markdown) (Optional)
+     *             excludedFileNameExtensions: String (Optional)
+     *             indexedFileNameExtensions: String (Optional)
+     *             failOnUnsupportedContentType: Boolean (Optional)
+     *             failOnUnprocessableDocument: Boolean (Optional)
+     *             indexStorageMetadataOnlyForOversizedDocuments: Boolean (Optional)
+     *             delimitedTextHeaders: String (Optional)
+     *             delimitedTextDelimiter: String (Optional)
+     *             firstLineContainsHeaders: Boolean (Optional)
+     *             markdownParsingSubmode: String(oneToMany/oneToOne) (Optional)
+     *             markdownHeaderDepth: String(h1/h2/h3/h4/h5/h6) (Optional)
+     *             documentRoot: String (Optional)
+     *             dataToExtract: String(storageMetadata/allMetadata/contentAndMetadata) (Optional)
+     *             imageAction: String(none/generateNormalizedImages/generateNormalizedImagePerPage) (Optional)
+     *             allowSkillsetToReadFileData: Boolean (Optional)
+     *             pdfTextRotationAlgorithm: String(none/detectAngles) (Optional)
+     *             executionEnvironment: String(standard/private) (Optional)
+     *             queryTimeout: String (Optional)
+     *              (Optional): {
+     *                 String: BinaryData (Required)
+     *             }
+     *         }
+     *     }
+     *     fieldMappings (Optional): [
+     *          (Optional){
+     *             sourceFieldName: String (Required)
+     *             targetFieldName: String (Optional)
+     *             mappingFunction (Optional): {
+     *                 name: String (Required)
+     *                 parameters (Optional): {
+     *                     String: BinaryData (Required)
+     *                 }
+     *             }
+     *         }
+     *     ]
+     *     outputFieldMappings (Optional): [
+     *         (recursive schema, see above)
+     *     ]
+     *     disabled: Boolean (Optional)
+     *     @odata.etag: String (Optional)
+     *     encryptionKey (Optional): {
+     *         keyVaultKeyName: String (Required)
+     *         keyVaultKeyVersion: String (Optional)
+     *         keyVaultUri: String (Required)
+     *         accessCredentials (Optional): {
+     *             applicationId: String (Required)
+     *             applicationSecret: String (Optional)
+     *         }
+     *         identity (Optional): {
+     *             @odata.type: String (Required)
+     *         }
+     *     }
+     *     cache (Optional): {
+     *         storageConnectionString: String (Optional)
+     *         enableReprocessing: Boolean (Optional)
+     *         identity (Optional): (recursive schema, see identity above)
+     *         id: String (Optional)
+     *     }
+     * }
+     * }
+     * 
+ * + * @param indexer The definition of the indexer to create. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return represents an indexer along with {@link Response}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Response createWithResponse(BinaryData indexer, RequestOptions requestOptions) { + final String contentType = "application/json"; + final String accept = "application/json"; + return service.createSync(this.client.getEndpoint(), this.client.getServiceVersion().getVersion(), contentType, + accept, indexer, requestOptions, Context.NONE); + } + + /** + * Returns the current status and execution history of an indexer. + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     status: String(unknown/error/running) (Required)
+     *     lastResult (Optional): {
+     *         status: String(transientFailure/success/inProgress/reset) (Required)
+     *         statusDetail: String(resetDocs) (Optional)
+     *         currentState (Optional): {
+     *             mode: String(indexingAllDocs/indexingResetDocs) (Optional)
+     *             allDocsInitialChangeTrackingState: String (Optional)
+     *             allDocsFinalChangeTrackingState: String (Optional)
+     *             resetDocsInitialChangeTrackingState: String (Optional)
+     *             resetDocsFinalChangeTrackingState: String (Optional)
+     *             resetDocumentKeys (Optional): [
+     *                 String (Optional)
+     *             ]
+     *             resetDatasourceDocumentIds (Optional): [
+     *                 String (Optional)
+     *             ]
+     *         }
+     *         errorMessage: String (Optional)
+     *         startTime: OffsetDateTime (Optional)
+     *         endTime: OffsetDateTime (Optional)
+     *         errors (Required): [
+     *              (Required){
+     *                 key: String (Optional)
+     *                 errorMessage: String (Required)
+     *                 statusCode: int (Required)
+     *                 name: String (Optional)
+     *                 details: String (Optional)
+     *                 documentationLink: String (Optional)
+     *             }
+     *         ]
+     *         warnings (Required): [
+     *              (Required){
+     *                 key: String (Optional)
+     *                 message: String (Required)
+     *                 name: String (Optional)
+     *                 details: String (Optional)
+     *                 documentationLink: String (Optional)
+     *             }
+     *         ]
+     *         itemsProcessed: int (Required)
+     *         itemsFailed: int (Required)
+     *         initialTrackingState: String (Optional)
+     *         finalTrackingState: String (Optional)
+     *     }
+     *     executionHistory (Required): [
+     *         (recursive schema, see above)
+     *     ]
+     *     limits (Required): {
+     *         maxRunTime: Duration (Optional)
+     *         maxDocumentExtractionSize: Long (Optional)
+     *         maxDocumentContentCharactersToExtract: Long (Optional)
+     *     }
+     * }
+     * }
+     * 
+ * + * @param indexerName The name of the indexer. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return represents the current status and execution history of an indexer along with {@link Response} on + * successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono> getStatusWithResponseAsync(String indexerName, RequestOptions requestOptions) { + final String accept = "application/json"; + return FluxUtil.withContext(context -> service.getStatus(this.client.getEndpoint(), + this.client.getServiceVersion().getVersion(), indexerName, accept, requestOptions, context)); + } + + /** + * Returns the current status and execution history of an indexer. + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     status: String(unknown/error/running) (Required)
+     *     lastResult (Optional): {
+     *         status: String(transientFailure/success/inProgress/reset) (Required)
+     *         statusDetail: String(resetDocs) (Optional)
+     *         currentState (Optional): {
+     *             mode: String(indexingAllDocs/indexingResetDocs) (Optional)
+     *             allDocsInitialChangeTrackingState: String (Optional)
+     *             allDocsFinalChangeTrackingState: String (Optional)
+     *             resetDocsInitialChangeTrackingState: String (Optional)
+     *             resetDocsFinalChangeTrackingState: String (Optional)
+     *             resetDocumentKeys (Optional): [
+     *                 String (Optional)
+     *             ]
+     *             resetDatasourceDocumentIds (Optional): [
+     *                 String (Optional)
+     *             ]
+     *         }
+     *         errorMessage: String (Optional)
+     *         startTime: OffsetDateTime (Optional)
+     *         endTime: OffsetDateTime (Optional)
+     *         errors (Required): [
+     *              (Required){
+     *                 key: String (Optional)
+     *                 errorMessage: String (Required)
+     *                 statusCode: int (Required)
+     *                 name: String (Optional)
+     *                 details: String (Optional)
+     *                 documentationLink: String (Optional)
+     *             }
+     *         ]
+     *         warnings (Required): [
+     *              (Required){
+     *                 key: String (Optional)
+     *                 message: String (Required)
+     *                 name: String (Optional)
+     *                 details: String (Optional)
+     *                 documentationLink: String (Optional)
+     *             }
+     *         ]
+     *         itemsProcessed: int (Required)
+     *         itemsFailed: int (Required)
+     *         initialTrackingState: String (Optional)
+     *         finalTrackingState: String (Optional)
+     *     }
+     *     executionHistory (Required): [
+     *         (recursive schema, see above)
+     *     ]
+     *     limits (Required): {
+     *         maxRunTime: Duration (Optional)
+     *         maxDocumentExtractionSize: Long (Optional)
+     *         maxDocumentContentCharactersToExtract: Long (Optional)
+     *     }
+     * }
+     * }
+     * 
+ * + * @param indexerName The name of the indexer. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return represents the current status and execution history of an indexer along with {@link Response}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Response getStatusWithResponse(String indexerName, RequestOptions requestOptions) { + final String accept = "application/json"; + return service.getStatusSync(this.client.getEndpoint(), this.client.getServiceVersion().getVersion(), + indexerName, accept, requestOptions, Context.NONE); + } +} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/implementation/IndexesImpl.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/implementation/IndexesImpl.java new file mode 100644 index 000000000000..f4e6ea5ebf1c --- /dev/null +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/implementation/IndexesImpl.java @@ -0,0 +1,3168 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.search.documents.implementation; + +import com.azure.core.annotation.BodyParam; +import com.azure.core.annotation.Delete; +import com.azure.core.annotation.ExpectedResponses; +import com.azure.core.annotation.Get; +import com.azure.core.annotation.HeaderParam; +import com.azure.core.annotation.Host; +import com.azure.core.annotation.HostParam; +import com.azure.core.annotation.PathParam; +import com.azure.core.annotation.Post; +import com.azure.core.annotation.Put; +import com.azure.core.annotation.QueryParam; +import com.azure.core.annotation.ReturnType; +import com.azure.core.annotation.ServiceInterface; +import com.azure.core.annotation.ServiceMethod; +import com.azure.core.annotation.UnexpectedResponseExceptionType; +import com.azure.core.exception.ClientAuthenticationException; +import com.azure.core.exception.HttpResponseException; +import com.azure.core.exception.ResourceModifiedException; +import com.azure.core.exception.ResourceNotFoundException; +import com.azure.core.http.rest.PagedFlux; +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.http.rest.PagedResponse; +import com.azure.core.http.rest.PagedResponseBase; +import com.azure.core.http.rest.RequestOptions; +import com.azure.core.http.rest.Response; +import com.azure.core.http.rest.RestProxy; +import com.azure.core.util.BinaryData; +import com.azure.core.util.Context; +import com.azure.core.util.FluxUtil; +import com.azure.search.documents.SearchServiceVersion; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; +import reactor.core.publisher.Mono; + +/** + * An instance of this class provides access to all the operations defined in Indexes. + */ +public final class IndexesImpl { + /** + * The proxy service used to perform REST calls. + */ + private final IndexesService service; + + /** + * The service client containing this operation class. + */ + private final SearchClientImpl client; + + /** + * Initializes an instance of IndexesImpl. + * + * @param client the instance of the service client containing this operation class. + */ + IndexesImpl(SearchClientImpl client) { + this.service = RestProxy.create(IndexesService.class, client.getHttpPipeline(), client.getSerializerAdapter()); + this.client = client; + } + + /** + * Gets Service version. + * + * @return the serviceVersion value. + */ + public SearchServiceVersion getServiceVersion() { + return client.getServiceVersion(); + } + + /** + * The interface defining all the services for SearchClientIndexes to be used by the proxy service to perform REST + * calls. + */ + @Host("{endpoint}") + @ServiceInterface(name = "SearchClientIndexes") + public interface IndexesService { + @Post("/indexes") + @ExpectedResponses({ 201 }) + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Mono> create(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @HeaderParam("Content-Type") String contentType, + @HeaderParam("Accept") String accept, @BodyParam("application/json") BinaryData index, + RequestOptions requestOptions, Context context); + + @Post("/indexes") + @ExpectedResponses({ 201 }) + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Response createSync(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @HeaderParam("Content-Type") String contentType, + @HeaderParam("Accept") String accept, @BodyParam("application/json") BinaryData index, + RequestOptions requestOptions, Context context); + + @Get("/indexes") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Mono> list(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, + RequestOptions requestOptions, Context context); + + @Get("/indexes") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Response listSync(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, + RequestOptions requestOptions, Context context); + + @Put("/indexes('{indexName}')") + @ExpectedResponses({ 200, 201 }) + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Mono> createOrUpdate(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @HeaderParam("Prefer") String prefer, + @PathParam("indexName") String indexName, @HeaderParam("Content-Type") String contentType, + @HeaderParam("Accept") String accept, @BodyParam("application/json") BinaryData index, + RequestOptions requestOptions, Context context); + + @Put("/indexes('{indexName}')") + @ExpectedResponses({ 200, 201 }) + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Response createOrUpdateSync(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @HeaderParam("Prefer") String prefer, + @PathParam("indexName") String indexName, @HeaderParam("Content-Type") String contentType, + @HeaderParam("Accept") String accept, @BodyParam("application/json") BinaryData index, + RequestOptions requestOptions, Context context); + + @Delete("/indexes('{indexName}')") + @ExpectedResponses({ 204, 404 }) + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Mono> delete(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @PathParam("indexName") String indexName, + @HeaderParam("Accept") String accept, RequestOptions requestOptions, Context context); + + @Delete("/indexes('{indexName}')") + @ExpectedResponses({ 204, 404 }) + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Response deleteSync(@HostParam("endpoint") String endpoint, @QueryParam("api-version") String apiVersion, + @PathParam("indexName") String indexName, @HeaderParam("Accept") String accept, + RequestOptions requestOptions, Context context); + + @Get("/indexes('{indexName}')") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Mono> get(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @PathParam("indexName") String indexName, + @HeaderParam("Accept") String accept, RequestOptions requestOptions, Context context); + + @Get("/indexes('{indexName}')") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Response getSync(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @PathParam("indexName") String indexName, + @HeaderParam("Accept") String accept, RequestOptions requestOptions, Context context); + + @Get("/indexes('{indexName}')/search.stats") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Mono> getStatistics(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @PathParam("indexName") String indexName, + @HeaderParam("Accept") String accept, RequestOptions requestOptions, Context context); + + @Get("/indexes('{indexName}')/search.stats") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Response getStatisticsSync(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @PathParam("indexName") String indexName, + @HeaderParam("Accept") String accept, RequestOptions requestOptions, Context context); + + @Post("/indexes('{indexName}')/search.analyze") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Mono> analyze(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @PathParam("indexName") String indexName, + @HeaderParam("Content-Type") String contentType, @HeaderParam("Accept") String accept, + @BodyParam("application/json") BinaryData request, RequestOptions requestOptions, Context context); + + @Post("/indexes('{indexName}')/search.analyze") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Response analyzeSync(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @PathParam("indexName") String indexName, + @HeaderParam("Content-Type") String contentType, @HeaderParam("Accept") String accept, + @BodyParam("application/json") BinaryData request, RequestOptions requestOptions, Context context); + } + + /** + * Creates a new search index. + *

Request Body Schema

+ * + *
+     * {@code
+     * {
+     *     name: String (Required)
+     *     fields (Required): [
+     *          (Required){
+     *             name: String (Required)
+     *             type: String(Edm.String/Edm.Int32/Edm.Int64/Edm.Double/Edm.Boolean/Edm.DateTimeOffset/Edm.GeographyPoint/Edm.ComplexType/Edm.Single/Edm.Half/Edm.Int16/Edm.SByte/Edm.Byte) (Required)
+     *             key: Boolean (Optional)
+     *             retrievable: Boolean (Optional)
+     *             stored: Boolean (Optional)
+     *             searchable: Boolean (Optional)
+     *             filterable: Boolean (Optional)
+     *             sortable: Boolean (Optional)
+     *             facetable: Boolean (Optional)
+     *             analyzer: String(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) (Optional)
+     *             searchAnalyzer: String(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) (Optional)
+     *             indexAnalyzer: String(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) (Optional)
+     *             normalizer: String(asciifolding/elision/lowercase/standard/uppercase) (Optional)
+     *             dimensions: Integer (Optional)
+     *             vectorSearchProfile: String (Optional)
+     *             vectorEncoding: String(packedBit) (Optional)
+     *             synonymMaps (Optional): [
+     *                 String (Optional)
+     *             ]
+     *             fields (Optional): [
+     *                 (recursive schema, see above)
+     *             ]
+     *         }
+     *     ]
+     *     scoringProfiles (Optional): [
+     *          (Optional){
+     *             name: String (Required)
+     *             text (Optional): {
+     *                 weights (Required): {
+     *                     String: double (Required)
+     *                 }
+     *             }
+     *             functions (Optional): [
+     *                  (Optional){
+     *                     type: String (Required)
+     *                     fieldName: String (Required)
+     *                     boost: double (Required)
+     *                     interpolation: String(linear/constant/quadratic/logarithmic) (Optional)
+     *                 }
+     *             ]
+     *             functionAggregation: String(sum/average/minimum/maximum/firstMatching) (Optional)
+     *         }
+     *     ]
+     *     defaultScoringProfile: String (Optional)
+     *     corsOptions (Optional): {
+     *         allowedOrigins (Required): [
+     *             String (Required)
+     *         ]
+     *         maxAgeInSeconds: Long (Optional)
+     *     }
+     *     suggesters (Optional): [
+     *          (Optional){
+     *             name: String (Required)
+     *             searchMode: String (Required)
+     *             sourceFields (Required): [
+     *                 String (Required)
+     *             ]
+     *         }
+     *     ]
+     *     analyzers (Optional): [
+     *          (Optional){
+     *             @odata.type: String (Required)
+     *             name: String (Required)
+     *         }
+     *     ]
+     *     tokenizers (Optional): [
+     *          (Optional){
+     *             @odata.type: String (Required)
+     *             name: String (Required)
+     *         }
+     *     ]
+     *     tokenFilters (Optional): [
+     *          (Optional){
+     *             @odata.type: String (Required)
+     *             name: String (Required)
+     *         }
+     *     ]
+     *     charFilters (Optional): [
+     *          (Optional){
+     *             @odata.type: String (Required)
+     *             name: String (Required)
+     *         }
+     *     ]
+     *     normalizers (Optional): [
+     *          (Optional){
+     *             @odata.type: String (Required)
+     *             name: String (Required)
+     *         }
+     *     ]
+     *     encryptionKey (Optional): {
+     *         keyVaultKeyName: String (Required)
+     *         keyVaultKeyVersion: String (Optional)
+     *         keyVaultUri: String (Required)
+     *         accessCredentials (Optional): {
+     *             applicationId: String (Required)
+     *             applicationSecret: String (Optional)
+     *         }
+     *         identity (Optional): {
+     *             @odata.type: String (Required)
+     *         }
+     *     }
+     *     similarity (Optional): {
+     *         @odata.type: String (Required)
+     *     }
+     *     semantic (Optional): {
+     *         defaultConfiguration: String (Optional)
+     *         configurations (Optional): [
+     *              (Optional){
+     *                 name: String (Required)
+     *                 prioritizedFields (Required): {
+     *                     titleField (Optional): {
+     *                         fieldName: String (Required)
+     *                     }
+     *                     prioritizedContentFields (Optional): [
+     *                         (recursive schema, see above)
+     *                     ]
+     *                     prioritizedKeywordsFields (Optional): [
+     *                         (recursive schema, see above)
+     *                     ]
+     *                 }
+     *                 flightingOptIn: Boolean (Optional)
+     *             }
+     *         ]
+     *     }
+     *     vectorSearch (Optional): {
+     *         profiles (Optional): [
+     *              (Optional){
+     *                 name: String (Required)
+     *                 algorithm: String (Required)
+     *                 vectorizer: String (Optional)
+     *                 compression: String (Optional)
+     *             }
+     *         ]
+     *         algorithms (Optional): [
+     *              (Optional){
+     *                 kind: String(hnsw/exhaustiveKnn) (Required)
+     *                 name: String (Required)
+     *             }
+     *         ]
+     *         vectorizers (Optional): [
+     *              (Optional){
+     *                 kind: String(azureOpenAI/customWebApi/aiServicesVision/aml) (Required)
+     *                 name: String (Required)
+     *             }
+     *         ]
+     *         compressions (Optional): [
+     *              (Optional){
+     *                 kind: String(scalarQuantization/binaryQuantization) (Required)
+     *                 name: String (Required)
+     *                 rerankWithOriginalVectors: Boolean (Optional)
+     *                 defaultOversampling: Double (Optional)
+     *                 rescoringOptions (Optional): {
+     *                     enableRescoring: Boolean (Optional)
+     *                     defaultOversampling: Double (Optional)
+     *                     rescoreStorageMethod: String(preserveOriginals/discardOriginals) (Optional)
+     *                 }
+     *                 truncationDimension: Integer (Optional)
+     *             }
+     *         ]
+     *     }
+     *     @odata.etag: String (Optional)
+     * }
+     * }
+     * 
+ * + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     name: String (Required)
+     *     fields (Required): [
+     *          (Required){
+     *             name: String (Required)
+     *             type: String(Edm.String/Edm.Int32/Edm.Int64/Edm.Double/Edm.Boolean/Edm.DateTimeOffset/Edm.GeographyPoint/Edm.ComplexType/Edm.Single/Edm.Half/Edm.Int16/Edm.SByte/Edm.Byte) (Required)
+     *             key: Boolean (Optional)
+     *             retrievable: Boolean (Optional)
+     *             stored: Boolean (Optional)
+     *             searchable: Boolean (Optional)
+     *             filterable: Boolean (Optional)
+     *             sortable: Boolean (Optional)
+     *             facetable: Boolean (Optional)
+     *             analyzer: String(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) (Optional)
+     *             searchAnalyzer: String(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) (Optional)
+     *             indexAnalyzer: String(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) (Optional)
+     *             normalizer: String(asciifolding/elision/lowercase/standard/uppercase) (Optional)
+     *             dimensions: Integer (Optional)
+     *             vectorSearchProfile: String (Optional)
+     *             vectorEncoding: String(packedBit) (Optional)
+     *             synonymMaps (Optional): [
+     *                 String (Optional)
+     *             ]
+     *             fields (Optional): [
+     *                 (recursive schema, see above)
+     *             ]
+     *         }
+     *     ]
+     *     scoringProfiles (Optional): [
+     *          (Optional){
+     *             name: String (Required)
+     *             text (Optional): {
+     *                 weights (Required): {
+     *                     String: double (Required)
+     *                 }
+     *             }
+     *             functions (Optional): [
+     *                  (Optional){
+     *                     type: String (Required)
+     *                     fieldName: String (Required)
+     *                     boost: double (Required)
+     *                     interpolation: String(linear/constant/quadratic/logarithmic) (Optional)
+     *                 }
+     *             ]
+     *             functionAggregation: String(sum/average/minimum/maximum/firstMatching) (Optional)
+     *         }
+     *     ]
+     *     defaultScoringProfile: String (Optional)
+     *     corsOptions (Optional): {
+     *         allowedOrigins (Required): [
+     *             String (Required)
+     *         ]
+     *         maxAgeInSeconds: Long (Optional)
+     *     }
+     *     suggesters (Optional): [
+     *          (Optional){
+     *             name: String (Required)
+     *             searchMode: String (Required)
+     *             sourceFields (Required): [
+     *                 String (Required)
+     *             ]
+     *         }
+     *     ]
+     *     analyzers (Optional): [
+     *          (Optional){
+     *             @odata.type: String (Required)
+     *             name: String (Required)
+     *         }
+     *     ]
+     *     tokenizers (Optional): [
+     *          (Optional){
+     *             @odata.type: String (Required)
+     *             name: String (Required)
+     *         }
+     *     ]
+     *     tokenFilters (Optional): [
+     *          (Optional){
+     *             @odata.type: String (Required)
+     *             name: String (Required)
+     *         }
+     *     ]
+     *     charFilters (Optional): [
+     *          (Optional){
+     *             @odata.type: String (Required)
+     *             name: String (Required)
+     *         }
+     *     ]
+     *     normalizers (Optional): [
+     *          (Optional){
+     *             @odata.type: String (Required)
+     *             name: String (Required)
+     *         }
+     *     ]
+     *     encryptionKey (Optional): {
+     *         keyVaultKeyName: String (Required)
+     *         keyVaultKeyVersion: String (Optional)
+     *         keyVaultUri: String (Required)
+     *         accessCredentials (Optional): {
+     *             applicationId: String (Required)
+     *             applicationSecret: String (Optional)
+     *         }
+     *         identity (Optional): {
+     *             @odata.type: String (Required)
+     *         }
+     *     }
+     *     similarity (Optional): {
+     *         @odata.type: String (Required)
+     *     }
+     *     semantic (Optional): {
+     *         defaultConfiguration: String (Optional)
+     *         configurations (Optional): [
+     *              (Optional){
+     *                 name: String (Required)
+     *                 prioritizedFields (Required): {
+     *                     titleField (Optional): {
+     *                         fieldName: String (Required)
+     *                     }
+     *                     prioritizedContentFields (Optional): [
+     *                         (recursive schema, see above)
+     *                     ]
+     *                     prioritizedKeywordsFields (Optional): [
+     *                         (recursive schema, see above)
+     *                     ]
+     *                 }
+     *                 flightingOptIn: Boolean (Optional)
+     *             }
+     *         ]
+     *     }
+     *     vectorSearch (Optional): {
+     *         profiles (Optional): [
+     *              (Optional){
+     *                 name: String (Required)
+     *                 algorithm: String (Required)
+     *                 vectorizer: String (Optional)
+     *                 compression: String (Optional)
+     *             }
+     *         ]
+     *         algorithms (Optional): [
+     *              (Optional){
+     *                 kind: String(hnsw/exhaustiveKnn) (Required)
+     *                 name: String (Required)
+     *             }
+     *         ]
+     *         vectorizers (Optional): [
+     *              (Optional){
+     *                 kind: String(azureOpenAI/customWebApi/aiServicesVision/aml) (Required)
+     *                 name: String (Required)
+     *             }
+     *         ]
+     *         compressions (Optional): [
+     *              (Optional){
+     *                 kind: String(scalarQuantization/binaryQuantization) (Required)
+     *                 name: String (Required)
+     *                 rerankWithOriginalVectors: Boolean (Optional)
+     *                 defaultOversampling: Double (Optional)
+     *                 rescoringOptions (Optional): {
+     *                     enableRescoring: Boolean (Optional)
+     *                     defaultOversampling: Double (Optional)
+     *                     rescoreStorageMethod: String(preserveOriginals/discardOriginals) (Optional)
+     *                 }
+     *                 truncationDimension: Integer (Optional)
+     *             }
+     *         ]
+     *     }
+     *     @odata.etag: String (Optional)
+     * }
+     * }
+     * 
+ * + * @param index The definition of the index to create. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return represents a search index definition, which describes the fields and search + * behavior of an index along with {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono> createWithResponseAsync(BinaryData index, RequestOptions requestOptions) { + final String contentType = "application/json"; + final String accept = "application/json"; + return FluxUtil.withContext(context -> service.create(this.client.getEndpoint(), + this.client.getServiceVersion().getVersion(), contentType, accept, index, requestOptions, context)); + } + + /** + * Creates a new search index. + *

Request Body Schema

+ * + *
+     * {@code
+     * {
+     *     name: String (Required)
+     *     fields (Required): [
+     *          (Required){
+     *             name: String (Required)
+     *             type: String(Edm.String/Edm.Int32/Edm.Int64/Edm.Double/Edm.Boolean/Edm.DateTimeOffset/Edm.GeographyPoint/Edm.ComplexType/Edm.Single/Edm.Half/Edm.Int16/Edm.SByte/Edm.Byte) (Required)
+     *             key: Boolean (Optional)
+     *             retrievable: Boolean (Optional)
+     *             stored: Boolean (Optional)
+     *             searchable: Boolean (Optional)
+     *             filterable: Boolean (Optional)
+     *             sortable: Boolean (Optional)
+     *             facetable: Boolean (Optional)
+     *             analyzer: String(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) (Optional)
+     *             searchAnalyzer: String(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) (Optional)
+     *             indexAnalyzer: String(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) (Optional)
+     *             normalizer: String(asciifolding/elision/lowercase/standard/uppercase) (Optional)
+     *             dimensions: Integer (Optional)
+     *             vectorSearchProfile: String (Optional)
+     *             vectorEncoding: String(packedBit) (Optional)
+     *             synonymMaps (Optional): [
+     *                 String (Optional)
+     *             ]
+     *             fields (Optional): [
+     *                 (recursive schema, see above)
+     *             ]
+     *         }
+     *     ]
+     *     scoringProfiles (Optional): [
+     *          (Optional){
+     *             name: String (Required)
+     *             text (Optional): {
+     *                 weights (Required): {
+     *                     String: double (Required)
+     *                 }
+     *             }
+     *             functions (Optional): [
+     *                  (Optional){
+     *                     type: String (Required)
+     *                     fieldName: String (Required)
+     *                     boost: double (Required)
+     *                     interpolation: String(linear/constant/quadratic/logarithmic) (Optional)
+     *                 }
+     *             ]
+     *             functionAggregation: String(sum/average/minimum/maximum/firstMatching) (Optional)
+     *         }
+     *     ]
+     *     defaultScoringProfile: String (Optional)
+     *     corsOptions (Optional): {
+     *         allowedOrigins (Required): [
+     *             String (Required)
+     *         ]
+     *         maxAgeInSeconds: Long (Optional)
+     *     }
+     *     suggesters (Optional): [
+     *          (Optional){
+     *             name: String (Required)
+     *             searchMode: String (Required)
+     *             sourceFields (Required): [
+     *                 String (Required)
+     *             ]
+     *         }
+     *     ]
+     *     analyzers (Optional): [
+     *          (Optional){
+     *             @odata.type: String (Required)
+     *             name: String (Required)
+     *         }
+     *     ]
+     *     tokenizers (Optional): [
+     *          (Optional){
+     *             @odata.type: String (Required)
+     *             name: String (Required)
+     *         }
+     *     ]
+     *     tokenFilters (Optional): [
+     *          (Optional){
+     *             @odata.type: String (Required)
+     *             name: String (Required)
+     *         }
+     *     ]
+     *     charFilters (Optional): [
+     *          (Optional){
+     *             @odata.type: String (Required)
+     *             name: String (Required)
+     *         }
+     *     ]
+     *     normalizers (Optional): [
+     *          (Optional){
+     *             @odata.type: String (Required)
+     *             name: String (Required)
+     *         }
+     *     ]
+     *     encryptionKey (Optional): {
+     *         keyVaultKeyName: String (Required)
+     *         keyVaultKeyVersion: String (Optional)
+     *         keyVaultUri: String (Required)
+     *         accessCredentials (Optional): {
+     *             applicationId: String (Required)
+     *             applicationSecret: String (Optional)
+     *         }
+     *         identity (Optional): {
+     *             @odata.type: String (Required)
+     *         }
+     *     }
+     *     similarity (Optional): {
+     *         @odata.type: String (Required)
+     *     }
+     *     semantic (Optional): {
+     *         defaultConfiguration: String (Optional)
+     *         configurations (Optional): [
+     *              (Optional){
+     *                 name: String (Required)
+     *                 prioritizedFields (Required): {
+     *                     titleField (Optional): {
+     *                         fieldName: String (Required)
+     *                     }
+     *                     prioritizedContentFields (Optional): [
+     *                         (recursive schema, see above)
+     *                     ]
+     *                     prioritizedKeywordsFields (Optional): [
+     *                         (recursive schema, see above)
+     *                     ]
+     *                 }
+     *                 flightingOptIn: Boolean (Optional)
+     *             }
+     *         ]
+     *     }
+     *     vectorSearch (Optional): {
+     *         profiles (Optional): [
+     *              (Optional){
+     *                 name: String (Required)
+     *                 algorithm: String (Required)
+     *                 vectorizer: String (Optional)
+     *                 compression: String (Optional)
+     *             }
+     *         ]
+     *         algorithms (Optional): [
+     *              (Optional){
+     *                 kind: String(hnsw/exhaustiveKnn) (Required)
+     *                 name: String (Required)
+     *             }
+     *         ]
+     *         vectorizers (Optional): [
+     *              (Optional){
+     *                 kind: String(azureOpenAI/customWebApi/aiServicesVision/aml) (Required)
+     *                 name: String (Required)
+     *             }
+     *         ]
+     *         compressions (Optional): [
+     *              (Optional){
+     *                 kind: String(scalarQuantization/binaryQuantization) (Required)
+     *                 name: String (Required)
+     *                 rerankWithOriginalVectors: Boolean (Optional)
+     *                 defaultOversampling: Double (Optional)
+     *                 rescoringOptions (Optional): {
+     *                     enableRescoring: Boolean (Optional)
+     *                     defaultOversampling: Double (Optional)
+     *                     rescoreStorageMethod: String(preserveOriginals/discardOriginals) (Optional)
+     *                 }
+     *                 truncationDimension: Integer (Optional)
+     *             }
+     *         ]
+     *     }
+     *     @odata.etag: String (Optional)
+     * }
+     * }
+     * 
+ * + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     name: String (Required)
+     *     fields (Required): [
+     *          (Required){
+     *             name: String (Required)
+     *             type: String(Edm.String/Edm.Int32/Edm.Int64/Edm.Double/Edm.Boolean/Edm.DateTimeOffset/Edm.GeographyPoint/Edm.ComplexType/Edm.Single/Edm.Half/Edm.Int16/Edm.SByte/Edm.Byte) (Required)
+     *             key: Boolean (Optional)
+     *             retrievable: Boolean (Optional)
+     *             stored: Boolean (Optional)
+     *             searchable: Boolean (Optional)
+     *             filterable: Boolean (Optional)
+     *             sortable: Boolean (Optional)
+     *             facetable: Boolean (Optional)
+     *             analyzer: String(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) (Optional)
+     *             searchAnalyzer: String(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) (Optional)
+     *             indexAnalyzer: String(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) (Optional)
+     *             normalizer: String(asciifolding/elision/lowercase/standard/uppercase) (Optional)
+     *             dimensions: Integer (Optional)
+     *             vectorSearchProfile: String (Optional)
+     *             vectorEncoding: String(packedBit) (Optional)
+     *             synonymMaps (Optional): [
+     *                 String (Optional)
+     *             ]
+     *             fields (Optional): [
+     *                 (recursive schema, see above)
+     *             ]
+     *         }
+     *     ]
+     *     scoringProfiles (Optional): [
+     *          (Optional){
+     *             name: String (Required)
+     *             text (Optional): {
+     *                 weights (Required): {
+     *                     String: double (Required)
+     *                 }
+     *             }
+     *             functions (Optional): [
+     *                  (Optional){
+     *                     type: String (Required)
+     *                     fieldName: String (Required)
+     *                     boost: double (Required)
+     *                     interpolation: String(linear/constant/quadratic/logarithmic) (Optional)
+     *                 }
+     *             ]
+     *             functionAggregation: String(sum/average/minimum/maximum/firstMatching) (Optional)
+     *         }
+     *     ]
+     *     defaultScoringProfile: String (Optional)
+     *     corsOptions (Optional): {
+     *         allowedOrigins (Required): [
+     *             String (Required)
+     *         ]
+     *         maxAgeInSeconds: Long (Optional)
+     *     }
+     *     suggesters (Optional): [
+     *          (Optional){
+     *             name: String (Required)
+     *             searchMode: String (Required)
+     *             sourceFields (Required): [
+     *                 String (Required)
+     *             ]
+     *         }
+     *     ]
+     *     analyzers (Optional): [
+     *          (Optional){
+     *             @odata.type: String (Required)
+     *             name: String (Required)
+     *         }
+     *     ]
+     *     tokenizers (Optional): [
+     *          (Optional){
+     *             @odata.type: String (Required)
+     *             name: String (Required)
+     *         }
+     *     ]
+     *     tokenFilters (Optional): [
+     *          (Optional){
+     *             @odata.type: String (Required)
+     *             name: String (Required)
+     *         }
+     *     ]
+     *     charFilters (Optional): [
+     *          (Optional){
+     *             @odata.type: String (Required)
+     *             name: String (Required)
+     *         }
+     *     ]
+     *     normalizers (Optional): [
+     *          (Optional){
+     *             @odata.type: String (Required)
+     *             name: String (Required)
+     *         }
+     *     ]
+     *     encryptionKey (Optional): {
+     *         keyVaultKeyName: String (Required)
+     *         keyVaultKeyVersion: String (Optional)
+     *         keyVaultUri: String (Required)
+     *         accessCredentials (Optional): {
+     *             applicationId: String (Required)
+     *             applicationSecret: String (Optional)
+     *         }
+     *         identity (Optional): {
+     *             @odata.type: String (Required)
+     *         }
+     *     }
+     *     similarity (Optional): {
+     *         @odata.type: String (Required)
+     *     }
+     *     semantic (Optional): {
+     *         defaultConfiguration: String (Optional)
+     *         configurations (Optional): [
+     *              (Optional){
+     *                 name: String (Required)
+     *                 prioritizedFields (Required): {
+     *                     titleField (Optional): {
+     *                         fieldName: String (Required)
+     *                     }
+     *                     prioritizedContentFields (Optional): [
+     *                         (recursive schema, see above)
+     *                     ]
+     *                     prioritizedKeywordsFields (Optional): [
+     *                         (recursive schema, see above)
+     *                     ]
+     *                 }
+     *                 flightingOptIn: Boolean (Optional)
+     *             }
+     *         ]
+     *     }
+     *     vectorSearch (Optional): {
+     *         profiles (Optional): [
+     *              (Optional){
+     *                 name: String (Required)
+     *                 algorithm: String (Required)
+     *                 vectorizer: String (Optional)
+     *                 compression: String (Optional)
+     *             }
+     *         ]
+     *         algorithms (Optional): [
+     *              (Optional){
+     *                 kind: String(hnsw/exhaustiveKnn) (Required)
+     *                 name: String (Required)
+     *             }
+     *         ]
+     *         vectorizers (Optional): [
+     *              (Optional){
+     *                 kind: String(azureOpenAI/customWebApi/aiServicesVision/aml) (Required)
+     *                 name: String (Required)
+     *             }
+     *         ]
+     *         compressions (Optional): [
+     *              (Optional){
+     *                 kind: String(scalarQuantization/binaryQuantization) (Required)
+     *                 name: String (Required)
+     *                 rerankWithOriginalVectors: Boolean (Optional)
+     *                 defaultOversampling: Double (Optional)
+     *                 rescoringOptions (Optional): {
+     *                     enableRescoring: Boolean (Optional)
+     *                     defaultOversampling: Double (Optional)
+     *                     rescoreStorageMethod: String(preserveOriginals/discardOriginals) (Optional)
+     *                 }
+     *                 truncationDimension: Integer (Optional)
+     *             }
+     *         ]
+     *     }
+     *     @odata.etag: String (Optional)
+     * }
+     * }
+     * 
+ * + * @param index The definition of the index to create. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return represents a search index definition, which describes the fields and search + * behavior of an index along with {@link Response}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Response createWithResponse(BinaryData index, RequestOptions requestOptions) { + final String contentType = "application/json"; + final String accept = "application/json"; + return service.createSync(this.client.getEndpoint(), this.client.getServiceVersion().getVersion(), contentType, + accept, index, requestOptions, Context.NONE); + } + + /** + * Lists all indexes available for a search service. + *

Query Parameters

+ * + * + * + * + *
Query Parameters
NameTypeRequiredDescription
$selectStringNoSelects 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.
+ * You can add these to a request with {@link RequestOptions#addQueryParam} + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     name: String (Required)
+     *     fields (Required): [
+     *          (Required){
+     *             name: String (Required)
+     *             type: String(Edm.String/Edm.Int32/Edm.Int64/Edm.Double/Edm.Boolean/Edm.DateTimeOffset/Edm.GeographyPoint/Edm.ComplexType/Edm.Single/Edm.Half/Edm.Int16/Edm.SByte/Edm.Byte) (Required)
+     *             key: Boolean (Optional)
+     *             retrievable: Boolean (Optional)
+     *             stored: Boolean (Optional)
+     *             searchable: Boolean (Optional)
+     *             filterable: Boolean (Optional)
+     *             sortable: Boolean (Optional)
+     *             facetable: Boolean (Optional)
+     *             analyzer: String(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) (Optional)
+     *             searchAnalyzer: String(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) (Optional)
+     *             indexAnalyzer: String(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) (Optional)
+     *             normalizer: String(asciifolding/elision/lowercase/standard/uppercase) (Optional)
+     *             dimensions: Integer (Optional)
+     *             vectorSearchProfile: String (Optional)
+     *             vectorEncoding: String(packedBit) (Optional)
+     *             synonymMaps (Optional): [
+     *                 String (Optional)
+     *             ]
+     *             fields (Optional): [
+     *                 (recursive schema, see above)
+     *             ]
+     *         }
+     *     ]
+     *     scoringProfiles (Optional): [
+     *          (Optional){
+     *             name: String (Required)
+     *             text (Optional): {
+     *                 weights (Required): {
+     *                     String: double (Required)
+     *                 }
+     *             }
+     *             functions (Optional): [
+     *                  (Optional){
+     *                     type: String (Required)
+     *                     fieldName: String (Required)
+     *                     boost: double (Required)
+     *                     interpolation: String(linear/constant/quadratic/logarithmic) (Optional)
+     *                 }
+     *             ]
+     *             functionAggregation: String(sum/average/minimum/maximum/firstMatching) (Optional)
+     *         }
+     *     ]
+     *     defaultScoringProfile: String (Optional)
+     *     corsOptions (Optional): {
+     *         allowedOrigins (Required): [
+     *             String (Required)
+     *         ]
+     *         maxAgeInSeconds: Long (Optional)
+     *     }
+     *     suggesters (Optional): [
+     *          (Optional){
+     *             name: String (Required)
+     *             searchMode: String (Required)
+     *             sourceFields (Required): [
+     *                 String (Required)
+     *             ]
+     *         }
+     *     ]
+     *     analyzers (Optional): [
+     *          (Optional){
+     *             @odata.type: String (Required)
+     *             name: String (Required)
+     *         }
+     *     ]
+     *     tokenizers (Optional): [
+     *          (Optional){
+     *             @odata.type: String (Required)
+     *             name: String (Required)
+     *         }
+     *     ]
+     *     tokenFilters (Optional): [
+     *          (Optional){
+     *             @odata.type: String (Required)
+     *             name: String (Required)
+     *         }
+     *     ]
+     *     charFilters (Optional): [
+     *          (Optional){
+     *             @odata.type: String (Required)
+     *             name: String (Required)
+     *         }
+     *     ]
+     *     normalizers (Optional): [
+     *          (Optional){
+     *             @odata.type: String (Required)
+     *             name: String (Required)
+     *         }
+     *     ]
+     *     encryptionKey (Optional): {
+     *         keyVaultKeyName: String (Required)
+     *         keyVaultKeyVersion: String (Optional)
+     *         keyVaultUri: String (Required)
+     *         accessCredentials (Optional): {
+     *             applicationId: String (Required)
+     *             applicationSecret: String (Optional)
+     *         }
+     *         identity (Optional): {
+     *             @odata.type: String (Required)
+     *         }
+     *     }
+     *     similarity (Optional): {
+     *         @odata.type: String (Required)
+     *     }
+     *     semantic (Optional): {
+     *         defaultConfiguration: String (Optional)
+     *         configurations (Optional): [
+     *              (Optional){
+     *                 name: String (Required)
+     *                 prioritizedFields (Required): {
+     *                     titleField (Optional): {
+     *                         fieldName: String (Required)
+     *                     }
+     *                     prioritizedContentFields (Optional): [
+     *                         (recursive schema, see above)
+     *                     ]
+     *                     prioritizedKeywordsFields (Optional): [
+     *                         (recursive schema, see above)
+     *                     ]
+     *                 }
+     *                 flightingOptIn: Boolean (Optional)
+     *             }
+     *         ]
+     *     }
+     *     vectorSearch (Optional): {
+     *         profiles (Optional): [
+     *              (Optional){
+     *                 name: String (Required)
+     *                 algorithm: String (Required)
+     *                 vectorizer: String (Optional)
+     *                 compression: String (Optional)
+     *             }
+     *         ]
+     *         algorithms (Optional): [
+     *              (Optional){
+     *                 kind: String(hnsw/exhaustiveKnn) (Required)
+     *                 name: String (Required)
+     *             }
+     *         ]
+     *         vectorizers (Optional): [
+     *              (Optional){
+     *                 kind: String(azureOpenAI/customWebApi/aiServicesVision/aml) (Required)
+     *                 name: String (Required)
+     *             }
+     *         ]
+     *         compressions (Optional): [
+     *              (Optional){
+     *                 kind: String(scalarQuantization/binaryQuantization) (Required)
+     *                 name: String (Required)
+     *                 rerankWithOriginalVectors: Boolean (Optional)
+     *                 defaultOversampling: Double (Optional)
+     *                 rescoringOptions (Optional): {
+     *                     enableRescoring: Boolean (Optional)
+     *                     defaultOversampling: Double (Optional)
+     *                     rescoreStorageMethod: String(preserveOriginals/discardOriginals) (Optional)
+     *                 }
+     *                 truncationDimension: Integer (Optional)
+     *             }
+     *         ]
+     *     }
+     *     @odata.etag: String (Optional)
+     * }
+     * }
+     * 
+ * + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return response from a List Indexes request along with {@link PagedResponse} on successful completion of + * {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> listSinglePageAsync(RequestOptions requestOptions) { + final String accept = "application/json"; + return FluxUtil + .withContext(context -> service.list(this.client.getEndpoint(), + this.client.getServiceVersion().getVersion(), accept, requestOptions, context)) + .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), + getValues(res.getValue(), "value"), null, null)); + } + + /** + * Lists all indexes available for a search service. + *

Query Parameters

+ * + * + * + * + *
Query Parameters
NameTypeRequiredDescription
$selectStringNoSelects 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.
+ * You can add these to a request with {@link RequestOptions#addQueryParam} + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     name: String (Required)
+     *     fields (Required): [
+     *          (Required){
+     *             name: String (Required)
+     *             type: String(Edm.String/Edm.Int32/Edm.Int64/Edm.Double/Edm.Boolean/Edm.DateTimeOffset/Edm.GeographyPoint/Edm.ComplexType/Edm.Single/Edm.Half/Edm.Int16/Edm.SByte/Edm.Byte) (Required)
+     *             key: Boolean (Optional)
+     *             retrievable: Boolean (Optional)
+     *             stored: Boolean (Optional)
+     *             searchable: Boolean (Optional)
+     *             filterable: Boolean (Optional)
+     *             sortable: Boolean (Optional)
+     *             facetable: Boolean (Optional)
+     *             analyzer: String(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) (Optional)
+     *             searchAnalyzer: String(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) (Optional)
+     *             indexAnalyzer: String(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) (Optional)
+     *             normalizer: String(asciifolding/elision/lowercase/standard/uppercase) (Optional)
+     *             dimensions: Integer (Optional)
+     *             vectorSearchProfile: String (Optional)
+     *             vectorEncoding: String(packedBit) (Optional)
+     *             synonymMaps (Optional): [
+     *                 String (Optional)
+     *             ]
+     *             fields (Optional): [
+     *                 (recursive schema, see above)
+     *             ]
+     *         }
+     *     ]
+     *     scoringProfiles (Optional): [
+     *          (Optional){
+     *             name: String (Required)
+     *             text (Optional): {
+     *                 weights (Required): {
+     *                     String: double (Required)
+     *                 }
+     *             }
+     *             functions (Optional): [
+     *                  (Optional){
+     *                     type: String (Required)
+     *                     fieldName: String (Required)
+     *                     boost: double (Required)
+     *                     interpolation: String(linear/constant/quadratic/logarithmic) (Optional)
+     *                 }
+     *             ]
+     *             functionAggregation: String(sum/average/minimum/maximum/firstMatching) (Optional)
+     *         }
+     *     ]
+     *     defaultScoringProfile: String (Optional)
+     *     corsOptions (Optional): {
+     *         allowedOrigins (Required): [
+     *             String (Required)
+     *         ]
+     *         maxAgeInSeconds: Long (Optional)
+     *     }
+     *     suggesters (Optional): [
+     *          (Optional){
+     *             name: String (Required)
+     *             searchMode: String (Required)
+     *             sourceFields (Required): [
+     *                 String (Required)
+     *             ]
+     *         }
+     *     ]
+     *     analyzers (Optional): [
+     *          (Optional){
+     *             @odata.type: String (Required)
+     *             name: String (Required)
+     *         }
+     *     ]
+     *     tokenizers (Optional): [
+     *          (Optional){
+     *             @odata.type: String (Required)
+     *             name: String (Required)
+     *         }
+     *     ]
+     *     tokenFilters (Optional): [
+     *          (Optional){
+     *             @odata.type: String (Required)
+     *             name: String (Required)
+     *         }
+     *     ]
+     *     charFilters (Optional): [
+     *          (Optional){
+     *             @odata.type: String (Required)
+     *             name: String (Required)
+     *         }
+     *     ]
+     *     normalizers (Optional): [
+     *          (Optional){
+     *             @odata.type: String (Required)
+     *             name: String (Required)
+     *         }
+     *     ]
+     *     encryptionKey (Optional): {
+     *         keyVaultKeyName: String (Required)
+     *         keyVaultKeyVersion: String (Optional)
+     *         keyVaultUri: String (Required)
+     *         accessCredentials (Optional): {
+     *             applicationId: String (Required)
+     *             applicationSecret: String (Optional)
+     *         }
+     *         identity (Optional): {
+     *             @odata.type: String (Required)
+     *         }
+     *     }
+     *     similarity (Optional): {
+     *         @odata.type: String (Required)
+     *     }
+     *     semantic (Optional): {
+     *         defaultConfiguration: String (Optional)
+     *         configurations (Optional): [
+     *              (Optional){
+     *                 name: String (Required)
+     *                 prioritizedFields (Required): {
+     *                     titleField (Optional): {
+     *                         fieldName: String (Required)
+     *                     }
+     *                     prioritizedContentFields (Optional): [
+     *                         (recursive schema, see above)
+     *                     ]
+     *                     prioritizedKeywordsFields (Optional): [
+     *                         (recursive schema, see above)
+     *                     ]
+     *                 }
+     *                 flightingOptIn: Boolean (Optional)
+     *             }
+     *         ]
+     *     }
+     *     vectorSearch (Optional): {
+     *         profiles (Optional): [
+     *              (Optional){
+     *                 name: String (Required)
+     *                 algorithm: String (Required)
+     *                 vectorizer: String (Optional)
+     *                 compression: String (Optional)
+     *             }
+     *         ]
+     *         algorithms (Optional): [
+     *              (Optional){
+     *                 kind: String(hnsw/exhaustiveKnn) (Required)
+     *                 name: String (Required)
+     *             }
+     *         ]
+     *         vectorizers (Optional): [
+     *              (Optional){
+     *                 kind: String(azureOpenAI/customWebApi/aiServicesVision/aml) (Required)
+     *                 name: String (Required)
+     *             }
+     *         ]
+     *         compressions (Optional): [
+     *              (Optional){
+     *                 kind: String(scalarQuantization/binaryQuantization) (Required)
+     *                 name: String (Required)
+     *                 rerankWithOriginalVectors: Boolean (Optional)
+     *                 defaultOversampling: Double (Optional)
+     *                 rescoringOptions (Optional): {
+     *                     enableRescoring: Boolean (Optional)
+     *                     defaultOversampling: Double (Optional)
+     *                     rescoreStorageMethod: String(preserveOriginals/discardOriginals) (Optional)
+     *                 }
+     *                 truncationDimension: Integer (Optional)
+     *             }
+     *         ]
+     *     }
+     *     @odata.etag: String (Optional)
+     * }
+     * }
+     * 
+ * + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return response from a List Indexes request as paginated response with {@link PagedFlux}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + public PagedFlux listAsync(RequestOptions requestOptions) { + return new PagedFlux<>(() -> listSinglePageAsync(requestOptions)); + } + + /** + * Lists all indexes available for a search service. + *

Query Parameters

+ * + * + * + * + *
Query Parameters
NameTypeRequiredDescription
$selectStringNoSelects 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.
+ * You can add these to a request with {@link RequestOptions#addQueryParam} + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     name: String (Required)
+     *     fields (Required): [
+     *          (Required){
+     *             name: String (Required)
+     *             type: String(Edm.String/Edm.Int32/Edm.Int64/Edm.Double/Edm.Boolean/Edm.DateTimeOffset/Edm.GeographyPoint/Edm.ComplexType/Edm.Single/Edm.Half/Edm.Int16/Edm.SByte/Edm.Byte) (Required)
+     *             key: Boolean (Optional)
+     *             retrievable: Boolean (Optional)
+     *             stored: Boolean (Optional)
+     *             searchable: Boolean (Optional)
+     *             filterable: Boolean (Optional)
+     *             sortable: Boolean (Optional)
+     *             facetable: Boolean (Optional)
+     *             analyzer: String(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) (Optional)
+     *             searchAnalyzer: String(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) (Optional)
+     *             indexAnalyzer: String(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) (Optional)
+     *             normalizer: String(asciifolding/elision/lowercase/standard/uppercase) (Optional)
+     *             dimensions: Integer (Optional)
+     *             vectorSearchProfile: String (Optional)
+     *             vectorEncoding: String(packedBit) (Optional)
+     *             synonymMaps (Optional): [
+     *                 String (Optional)
+     *             ]
+     *             fields (Optional): [
+     *                 (recursive schema, see above)
+     *             ]
+     *         }
+     *     ]
+     *     scoringProfiles (Optional): [
+     *          (Optional){
+     *             name: String (Required)
+     *             text (Optional): {
+     *                 weights (Required): {
+     *                     String: double (Required)
+     *                 }
+     *             }
+     *             functions (Optional): [
+     *                  (Optional){
+     *                     type: String (Required)
+     *                     fieldName: String (Required)
+     *                     boost: double (Required)
+     *                     interpolation: String(linear/constant/quadratic/logarithmic) (Optional)
+     *                 }
+     *             ]
+     *             functionAggregation: String(sum/average/minimum/maximum/firstMatching) (Optional)
+     *         }
+     *     ]
+     *     defaultScoringProfile: String (Optional)
+     *     corsOptions (Optional): {
+     *         allowedOrigins (Required): [
+     *             String (Required)
+     *         ]
+     *         maxAgeInSeconds: Long (Optional)
+     *     }
+     *     suggesters (Optional): [
+     *          (Optional){
+     *             name: String (Required)
+     *             searchMode: String (Required)
+     *             sourceFields (Required): [
+     *                 String (Required)
+     *             ]
+     *         }
+     *     ]
+     *     analyzers (Optional): [
+     *          (Optional){
+     *             @odata.type: String (Required)
+     *             name: String (Required)
+     *         }
+     *     ]
+     *     tokenizers (Optional): [
+     *          (Optional){
+     *             @odata.type: String (Required)
+     *             name: String (Required)
+     *         }
+     *     ]
+     *     tokenFilters (Optional): [
+     *          (Optional){
+     *             @odata.type: String (Required)
+     *             name: String (Required)
+     *         }
+     *     ]
+     *     charFilters (Optional): [
+     *          (Optional){
+     *             @odata.type: String (Required)
+     *             name: String (Required)
+     *         }
+     *     ]
+     *     normalizers (Optional): [
+     *          (Optional){
+     *             @odata.type: String (Required)
+     *             name: String (Required)
+     *         }
+     *     ]
+     *     encryptionKey (Optional): {
+     *         keyVaultKeyName: String (Required)
+     *         keyVaultKeyVersion: String (Optional)
+     *         keyVaultUri: String (Required)
+     *         accessCredentials (Optional): {
+     *             applicationId: String (Required)
+     *             applicationSecret: String (Optional)
+     *         }
+     *         identity (Optional): {
+     *             @odata.type: String (Required)
+     *         }
+     *     }
+     *     similarity (Optional): {
+     *         @odata.type: String (Required)
+     *     }
+     *     semantic (Optional): {
+     *         defaultConfiguration: String (Optional)
+     *         configurations (Optional): [
+     *              (Optional){
+     *                 name: String (Required)
+     *                 prioritizedFields (Required): {
+     *                     titleField (Optional): {
+     *                         fieldName: String (Required)
+     *                     }
+     *                     prioritizedContentFields (Optional): [
+     *                         (recursive schema, see above)
+     *                     ]
+     *                     prioritizedKeywordsFields (Optional): [
+     *                         (recursive schema, see above)
+     *                     ]
+     *                 }
+     *                 flightingOptIn: Boolean (Optional)
+     *             }
+     *         ]
+     *     }
+     *     vectorSearch (Optional): {
+     *         profiles (Optional): [
+     *              (Optional){
+     *                 name: String (Required)
+     *                 algorithm: String (Required)
+     *                 vectorizer: String (Optional)
+     *                 compression: String (Optional)
+     *             }
+     *         ]
+     *         algorithms (Optional): [
+     *              (Optional){
+     *                 kind: String(hnsw/exhaustiveKnn) (Required)
+     *                 name: String (Required)
+     *             }
+     *         ]
+     *         vectorizers (Optional): [
+     *              (Optional){
+     *                 kind: String(azureOpenAI/customWebApi/aiServicesVision/aml) (Required)
+     *                 name: String (Required)
+     *             }
+     *         ]
+     *         compressions (Optional): [
+     *              (Optional){
+     *                 kind: String(scalarQuantization/binaryQuantization) (Required)
+     *                 name: String (Required)
+     *                 rerankWithOriginalVectors: Boolean (Optional)
+     *                 defaultOversampling: Double (Optional)
+     *                 rescoringOptions (Optional): {
+     *                     enableRescoring: Boolean (Optional)
+     *                     defaultOversampling: Double (Optional)
+     *                     rescoreStorageMethod: String(preserveOriginals/discardOriginals) (Optional)
+     *                 }
+     *                 truncationDimension: Integer (Optional)
+     *             }
+     *         ]
+     *     }
+     *     @odata.etag: String (Optional)
+     * }
+     * }
+     * 
+ * + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return response from a List Indexes request along with {@link PagedResponse}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private PagedResponse listSinglePage(RequestOptions requestOptions) { + final String accept = "application/json"; + Response res = service.listSync(this.client.getEndpoint(), + this.client.getServiceVersion().getVersion(), accept, requestOptions, Context.NONE); + return new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), + getValues(res.getValue(), "value"), null, null); + } + + /** + * Lists all indexes available for a search service. + *

Query Parameters

+ * + * + * + * + *
Query Parameters
NameTypeRequiredDescription
$selectStringNoSelects 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.
+ * You can add these to a request with {@link RequestOptions#addQueryParam} + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     name: String (Required)
+     *     fields (Required): [
+     *          (Required){
+     *             name: String (Required)
+     *             type: String(Edm.String/Edm.Int32/Edm.Int64/Edm.Double/Edm.Boolean/Edm.DateTimeOffset/Edm.GeographyPoint/Edm.ComplexType/Edm.Single/Edm.Half/Edm.Int16/Edm.SByte/Edm.Byte) (Required)
+     *             key: Boolean (Optional)
+     *             retrievable: Boolean (Optional)
+     *             stored: Boolean (Optional)
+     *             searchable: Boolean (Optional)
+     *             filterable: Boolean (Optional)
+     *             sortable: Boolean (Optional)
+     *             facetable: Boolean (Optional)
+     *             analyzer: String(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) (Optional)
+     *             searchAnalyzer: String(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) (Optional)
+     *             indexAnalyzer: String(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) (Optional)
+     *             normalizer: String(asciifolding/elision/lowercase/standard/uppercase) (Optional)
+     *             dimensions: Integer (Optional)
+     *             vectorSearchProfile: String (Optional)
+     *             vectorEncoding: String(packedBit) (Optional)
+     *             synonymMaps (Optional): [
+     *                 String (Optional)
+     *             ]
+     *             fields (Optional): [
+     *                 (recursive schema, see above)
+     *             ]
+     *         }
+     *     ]
+     *     scoringProfiles (Optional): [
+     *          (Optional){
+     *             name: String (Required)
+     *             text (Optional): {
+     *                 weights (Required): {
+     *                     String: double (Required)
+     *                 }
+     *             }
+     *             functions (Optional): [
+     *                  (Optional){
+     *                     type: String (Required)
+     *                     fieldName: String (Required)
+     *                     boost: double (Required)
+     *                     interpolation: String(linear/constant/quadratic/logarithmic) (Optional)
+     *                 }
+     *             ]
+     *             functionAggregation: String(sum/average/minimum/maximum/firstMatching) (Optional)
+     *         }
+     *     ]
+     *     defaultScoringProfile: String (Optional)
+     *     corsOptions (Optional): {
+     *         allowedOrigins (Required): [
+     *             String (Required)
+     *         ]
+     *         maxAgeInSeconds: Long (Optional)
+     *     }
+     *     suggesters (Optional): [
+     *          (Optional){
+     *             name: String (Required)
+     *             searchMode: String (Required)
+     *             sourceFields (Required): [
+     *                 String (Required)
+     *             ]
+     *         }
+     *     ]
+     *     analyzers (Optional): [
+     *          (Optional){
+     *             @odata.type: String (Required)
+     *             name: String (Required)
+     *         }
+     *     ]
+     *     tokenizers (Optional): [
+     *          (Optional){
+     *             @odata.type: String (Required)
+     *             name: String (Required)
+     *         }
+     *     ]
+     *     tokenFilters (Optional): [
+     *          (Optional){
+     *             @odata.type: String (Required)
+     *             name: String (Required)
+     *         }
+     *     ]
+     *     charFilters (Optional): [
+     *          (Optional){
+     *             @odata.type: String (Required)
+     *             name: String (Required)
+     *         }
+     *     ]
+     *     normalizers (Optional): [
+     *          (Optional){
+     *             @odata.type: String (Required)
+     *             name: String (Required)
+     *         }
+     *     ]
+     *     encryptionKey (Optional): {
+     *         keyVaultKeyName: String (Required)
+     *         keyVaultKeyVersion: String (Optional)
+     *         keyVaultUri: String (Required)
+     *         accessCredentials (Optional): {
+     *             applicationId: String (Required)
+     *             applicationSecret: String (Optional)
+     *         }
+     *         identity (Optional): {
+     *             @odata.type: String (Required)
+     *         }
+     *     }
+     *     similarity (Optional): {
+     *         @odata.type: String (Required)
+     *     }
+     *     semantic (Optional): {
+     *         defaultConfiguration: String (Optional)
+     *         configurations (Optional): [
+     *              (Optional){
+     *                 name: String (Required)
+     *                 prioritizedFields (Required): {
+     *                     titleField (Optional): {
+     *                         fieldName: String (Required)
+     *                     }
+     *                     prioritizedContentFields (Optional): [
+     *                         (recursive schema, see above)
+     *                     ]
+     *                     prioritizedKeywordsFields (Optional): [
+     *                         (recursive schema, see above)
+     *                     ]
+     *                 }
+     *                 flightingOptIn: Boolean (Optional)
+     *             }
+     *         ]
+     *     }
+     *     vectorSearch (Optional): {
+     *         profiles (Optional): [
+     *              (Optional){
+     *                 name: String (Required)
+     *                 algorithm: String (Required)
+     *                 vectorizer: String (Optional)
+     *                 compression: String (Optional)
+     *             }
+     *         ]
+     *         algorithms (Optional): [
+     *              (Optional){
+     *                 kind: String(hnsw/exhaustiveKnn) (Required)
+     *                 name: String (Required)
+     *             }
+     *         ]
+     *         vectorizers (Optional): [
+     *              (Optional){
+     *                 kind: String(azureOpenAI/customWebApi/aiServicesVision/aml) (Required)
+     *                 name: String (Required)
+     *             }
+     *         ]
+     *         compressions (Optional): [
+     *              (Optional){
+     *                 kind: String(scalarQuantization/binaryQuantization) (Required)
+     *                 name: String (Required)
+     *                 rerankWithOriginalVectors: Boolean (Optional)
+     *                 defaultOversampling: Double (Optional)
+     *                 rescoringOptions (Optional): {
+     *                     enableRescoring: Boolean (Optional)
+     *                     defaultOversampling: Double (Optional)
+     *                     rescoreStorageMethod: String(preserveOriginals/discardOriginals) (Optional)
+     *                 }
+     *                 truncationDimension: Integer (Optional)
+     *             }
+     *         ]
+     *     }
+     *     @odata.etag: String (Optional)
+     * }
+     * }
+     * 
+ * + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return response from a List Indexes request as paginated response with {@link PagedIterable}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + public PagedIterable list(RequestOptions requestOptions) { + return new PagedIterable<>(() -> listSinglePage(requestOptions)); + } + + /** + * Creates a new search index or updates an index if it already exists. + *

Query Parameters

+ * + * + * + * + *
Query Parameters
NameTypeRequiredDescription
allowIndexDowntimeBooleanNoAllows 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.
+ * You can add these to a request with {@link RequestOptions#addQueryParam} + *

Header Parameters

+ * + * + * + * + * + *
Header Parameters
NameTypeRequiredDescription
If-MatchStringNoDefines the If-Match condition. The operation will be + * performed only if the ETag on the server matches this value.
If-None-MatchStringNoDefines the If-None-Match condition. The operation will + * be performed only if the ETag on the server does not match this value.
+ * You can add these to a request with {@link RequestOptions#addHeader} + *

Request Body Schema

+ * + *
+     * {@code
+     * {
+     *     name: String (Required)
+     *     fields (Required): [
+     *          (Required){
+     *             name: String (Required)
+     *             type: String(Edm.String/Edm.Int32/Edm.Int64/Edm.Double/Edm.Boolean/Edm.DateTimeOffset/Edm.GeographyPoint/Edm.ComplexType/Edm.Single/Edm.Half/Edm.Int16/Edm.SByte/Edm.Byte) (Required)
+     *             key: Boolean (Optional)
+     *             retrievable: Boolean (Optional)
+     *             stored: Boolean (Optional)
+     *             searchable: Boolean (Optional)
+     *             filterable: Boolean (Optional)
+     *             sortable: Boolean (Optional)
+     *             facetable: Boolean (Optional)
+     *             analyzer: String(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) (Optional)
+     *             searchAnalyzer: String(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) (Optional)
+     *             indexAnalyzer: String(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) (Optional)
+     *             normalizer: String(asciifolding/elision/lowercase/standard/uppercase) (Optional)
+     *             dimensions: Integer (Optional)
+     *             vectorSearchProfile: String (Optional)
+     *             vectorEncoding: String(packedBit) (Optional)
+     *             synonymMaps (Optional): [
+     *                 String (Optional)
+     *             ]
+     *             fields (Optional): [
+     *                 (recursive schema, see above)
+     *             ]
+     *         }
+     *     ]
+     *     scoringProfiles (Optional): [
+     *          (Optional){
+     *             name: String (Required)
+     *             text (Optional): {
+     *                 weights (Required): {
+     *                     String: double (Required)
+     *                 }
+     *             }
+     *             functions (Optional): [
+     *                  (Optional){
+     *                     type: String (Required)
+     *                     fieldName: String (Required)
+     *                     boost: double (Required)
+     *                     interpolation: String(linear/constant/quadratic/logarithmic) (Optional)
+     *                 }
+     *             ]
+     *             functionAggregation: String(sum/average/minimum/maximum/firstMatching) (Optional)
+     *         }
+     *     ]
+     *     defaultScoringProfile: String (Optional)
+     *     corsOptions (Optional): {
+     *         allowedOrigins (Required): [
+     *             String (Required)
+     *         ]
+     *         maxAgeInSeconds: Long (Optional)
+     *     }
+     *     suggesters (Optional): [
+     *          (Optional){
+     *             name: String (Required)
+     *             searchMode: String (Required)
+     *             sourceFields (Required): [
+     *                 String (Required)
+     *             ]
+     *         }
+     *     ]
+     *     analyzers (Optional): [
+     *          (Optional){
+     *             @odata.type: String (Required)
+     *             name: String (Required)
+     *         }
+     *     ]
+     *     tokenizers (Optional): [
+     *          (Optional){
+     *             @odata.type: String (Required)
+     *             name: String (Required)
+     *         }
+     *     ]
+     *     tokenFilters (Optional): [
+     *          (Optional){
+     *             @odata.type: String (Required)
+     *             name: String (Required)
+     *         }
+     *     ]
+     *     charFilters (Optional): [
+     *          (Optional){
+     *             @odata.type: String (Required)
+     *             name: String (Required)
+     *         }
+     *     ]
+     *     normalizers (Optional): [
+     *          (Optional){
+     *             @odata.type: String (Required)
+     *             name: String (Required)
+     *         }
+     *     ]
+     *     encryptionKey (Optional): {
+     *         keyVaultKeyName: String (Required)
+     *         keyVaultKeyVersion: String (Optional)
+     *         keyVaultUri: String (Required)
+     *         accessCredentials (Optional): {
+     *             applicationId: String (Required)
+     *             applicationSecret: String (Optional)
+     *         }
+     *         identity (Optional): {
+     *             @odata.type: String (Required)
+     *         }
+     *     }
+     *     similarity (Optional): {
+     *         @odata.type: String (Required)
+     *     }
+     *     semantic (Optional): {
+     *         defaultConfiguration: String (Optional)
+     *         configurations (Optional): [
+     *              (Optional){
+     *                 name: String (Required)
+     *                 prioritizedFields (Required): {
+     *                     titleField (Optional): {
+     *                         fieldName: String (Required)
+     *                     }
+     *                     prioritizedContentFields (Optional): [
+     *                         (recursive schema, see above)
+     *                     ]
+     *                     prioritizedKeywordsFields (Optional): [
+     *                         (recursive schema, see above)
+     *                     ]
+     *                 }
+     *                 flightingOptIn: Boolean (Optional)
+     *             }
+     *         ]
+     *     }
+     *     vectorSearch (Optional): {
+     *         profiles (Optional): [
+     *              (Optional){
+     *                 name: String (Required)
+     *                 algorithm: String (Required)
+     *                 vectorizer: String (Optional)
+     *                 compression: String (Optional)
+     *             }
+     *         ]
+     *         algorithms (Optional): [
+     *              (Optional){
+     *                 kind: String(hnsw/exhaustiveKnn) (Required)
+     *                 name: String (Required)
+     *             }
+     *         ]
+     *         vectorizers (Optional): [
+     *              (Optional){
+     *                 kind: String(azureOpenAI/customWebApi/aiServicesVision/aml) (Required)
+     *                 name: String (Required)
+     *             }
+     *         ]
+     *         compressions (Optional): [
+     *              (Optional){
+     *                 kind: String(scalarQuantization/binaryQuantization) (Required)
+     *                 name: String (Required)
+     *                 rerankWithOriginalVectors: Boolean (Optional)
+     *                 defaultOversampling: Double (Optional)
+     *                 rescoringOptions (Optional): {
+     *                     enableRescoring: Boolean (Optional)
+     *                     defaultOversampling: Double (Optional)
+     *                     rescoreStorageMethod: String(preserveOriginals/discardOriginals) (Optional)
+     *                 }
+     *                 truncationDimension: Integer (Optional)
+     *             }
+     *         ]
+     *     }
+     *     @odata.etag: String (Optional)
+     * }
+     * }
+     * 
+ * + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     name: String (Required)
+     *     fields (Required): [
+     *          (Required){
+     *             name: String (Required)
+     *             type: String(Edm.String/Edm.Int32/Edm.Int64/Edm.Double/Edm.Boolean/Edm.DateTimeOffset/Edm.GeographyPoint/Edm.ComplexType/Edm.Single/Edm.Half/Edm.Int16/Edm.SByte/Edm.Byte) (Required)
+     *             key: Boolean (Optional)
+     *             retrievable: Boolean (Optional)
+     *             stored: Boolean (Optional)
+     *             searchable: Boolean (Optional)
+     *             filterable: Boolean (Optional)
+     *             sortable: Boolean (Optional)
+     *             facetable: Boolean (Optional)
+     *             analyzer: String(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) (Optional)
+     *             searchAnalyzer: String(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) (Optional)
+     *             indexAnalyzer: String(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) (Optional)
+     *             normalizer: String(asciifolding/elision/lowercase/standard/uppercase) (Optional)
+     *             dimensions: Integer (Optional)
+     *             vectorSearchProfile: String (Optional)
+     *             vectorEncoding: String(packedBit) (Optional)
+     *             synonymMaps (Optional): [
+     *                 String (Optional)
+     *             ]
+     *             fields (Optional): [
+     *                 (recursive schema, see above)
+     *             ]
+     *         }
+     *     ]
+     *     scoringProfiles (Optional): [
+     *          (Optional){
+     *             name: String (Required)
+     *             text (Optional): {
+     *                 weights (Required): {
+     *                     String: double (Required)
+     *                 }
+     *             }
+     *             functions (Optional): [
+     *                  (Optional){
+     *                     type: String (Required)
+     *                     fieldName: String (Required)
+     *                     boost: double (Required)
+     *                     interpolation: String(linear/constant/quadratic/logarithmic) (Optional)
+     *                 }
+     *             ]
+     *             functionAggregation: String(sum/average/minimum/maximum/firstMatching) (Optional)
+     *         }
+     *     ]
+     *     defaultScoringProfile: String (Optional)
+     *     corsOptions (Optional): {
+     *         allowedOrigins (Required): [
+     *             String (Required)
+     *         ]
+     *         maxAgeInSeconds: Long (Optional)
+     *     }
+     *     suggesters (Optional): [
+     *          (Optional){
+     *             name: String (Required)
+     *             searchMode: String (Required)
+     *             sourceFields (Required): [
+     *                 String (Required)
+     *             ]
+     *         }
+     *     ]
+     *     analyzers (Optional): [
+     *          (Optional){
+     *             @odata.type: String (Required)
+     *             name: String (Required)
+     *         }
+     *     ]
+     *     tokenizers (Optional): [
+     *          (Optional){
+     *             @odata.type: String (Required)
+     *             name: String (Required)
+     *         }
+     *     ]
+     *     tokenFilters (Optional): [
+     *          (Optional){
+     *             @odata.type: String (Required)
+     *             name: String (Required)
+     *         }
+     *     ]
+     *     charFilters (Optional): [
+     *          (Optional){
+     *             @odata.type: String (Required)
+     *             name: String (Required)
+     *         }
+     *     ]
+     *     normalizers (Optional): [
+     *          (Optional){
+     *             @odata.type: String (Required)
+     *             name: String (Required)
+     *         }
+     *     ]
+     *     encryptionKey (Optional): {
+     *         keyVaultKeyName: String (Required)
+     *         keyVaultKeyVersion: String (Optional)
+     *         keyVaultUri: String (Required)
+     *         accessCredentials (Optional): {
+     *             applicationId: String (Required)
+     *             applicationSecret: String (Optional)
+     *         }
+     *         identity (Optional): {
+     *             @odata.type: String (Required)
+     *         }
+     *     }
+     *     similarity (Optional): {
+     *         @odata.type: String (Required)
+     *     }
+     *     semantic (Optional): {
+     *         defaultConfiguration: String (Optional)
+     *         configurations (Optional): [
+     *              (Optional){
+     *                 name: String (Required)
+     *                 prioritizedFields (Required): {
+     *                     titleField (Optional): {
+     *                         fieldName: String (Required)
+     *                     }
+     *                     prioritizedContentFields (Optional): [
+     *                         (recursive schema, see above)
+     *                     ]
+     *                     prioritizedKeywordsFields (Optional): [
+     *                         (recursive schema, see above)
+     *                     ]
+     *                 }
+     *                 flightingOptIn: Boolean (Optional)
+     *             }
+     *         ]
+     *     }
+     *     vectorSearch (Optional): {
+     *         profiles (Optional): [
+     *              (Optional){
+     *                 name: String (Required)
+     *                 algorithm: String (Required)
+     *                 vectorizer: String (Optional)
+     *                 compression: String (Optional)
+     *             }
+     *         ]
+     *         algorithms (Optional): [
+     *              (Optional){
+     *                 kind: String(hnsw/exhaustiveKnn) (Required)
+     *                 name: String (Required)
+     *             }
+     *         ]
+     *         vectorizers (Optional): [
+     *              (Optional){
+     *                 kind: String(azureOpenAI/customWebApi/aiServicesVision/aml) (Required)
+     *                 name: String (Required)
+     *             }
+     *         ]
+     *         compressions (Optional): [
+     *              (Optional){
+     *                 kind: String(scalarQuantization/binaryQuantization) (Required)
+     *                 name: String (Required)
+     *                 rerankWithOriginalVectors: Boolean (Optional)
+     *                 defaultOversampling: Double (Optional)
+     *                 rescoringOptions (Optional): {
+     *                     enableRescoring: Boolean (Optional)
+     *                     defaultOversampling: Double (Optional)
+     *                     rescoreStorageMethod: String(preserveOriginals/discardOriginals) (Optional)
+     *                 }
+     *                 truncationDimension: Integer (Optional)
+     *             }
+     *         ]
+     *     }
+     *     @odata.etag: String (Optional)
+     * }
+     * }
+     * 
+ * + * @param indexName The name of the index. + * @param index The definition of the index to create or update. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return represents a search index definition, which describes the fields and search + * behavior of an index along with {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono> createOrUpdateWithResponseAsync(String indexName, BinaryData index, + RequestOptions requestOptions) { + final String prefer = "return=representation"; + final String contentType = "application/json"; + final String accept = "application/json"; + return FluxUtil.withContext( + context -> service.createOrUpdate(this.client.getEndpoint(), this.client.getServiceVersion().getVersion(), + prefer, indexName, contentType, accept, index, requestOptions, context)); + } + + /** + * Creates a new search index or updates an index if it already exists. + *

Query Parameters

+ * + * + * + * + *
Query Parameters
NameTypeRequiredDescription
allowIndexDowntimeBooleanNoAllows 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.
+ * You can add these to a request with {@link RequestOptions#addQueryParam} + *

Header Parameters

+ * + * + * + * + * + *
Header Parameters
NameTypeRequiredDescription
If-MatchStringNoDefines the If-Match condition. The operation will be + * performed only if the ETag on the server matches this value.
If-None-MatchStringNoDefines the If-None-Match condition. The operation will + * be performed only if the ETag on the server does not match this value.
+ * You can add these to a request with {@link RequestOptions#addHeader} + *

Request Body Schema

+ * + *
+     * {@code
+     * {
+     *     name: String (Required)
+     *     fields (Required): [
+     *          (Required){
+     *             name: String (Required)
+     *             type: String(Edm.String/Edm.Int32/Edm.Int64/Edm.Double/Edm.Boolean/Edm.DateTimeOffset/Edm.GeographyPoint/Edm.ComplexType/Edm.Single/Edm.Half/Edm.Int16/Edm.SByte/Edm.Byte) (Required)
+     *             key: Boolean (Optional)
+     *             retrievable: Boolean (Optional)
+     *             stored: Boolean (Optional)
+     *             searchable: Boolean (Optional)
+     *             filterable: Boolean (Optional)
+     *             sortable: Boolean (Optional)
+     *             facetable: Boolean (Optional)
+     *             analyzer: String(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) (Optional)
+     *             searchAnalyzer: String(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) (Optional)
+     *             indexAnalyzer: String(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) (Optional)
+     *             normalizer: String(asciifolding/elision/lowercase/standard/uppercase) (Optional)
+     *             dimensions: Integer (Optional)
+     *             vectorSearchProfile: String (Optional)
+     *             vectorEncoding: String(packedBit) (Optional)
+     *             synonymMaps (Optional): [
+     *                 String (Optional)
+     *             ]
+     *             fields (Optional): [
+     *                 (recursive schema, see above)
+     *             ]
+     *         }
+     *     ]
+     *     scoringProfiles (Optional): [
+     *          (Optional){
+     *             name: String (Required)
+     *             text (Optional): {
+     *                 weights (Required): {
+     *                     String: double (Required)
+     *                 }
+     *             }
+     *             functions (Optional): [
+     *                  (Optional){
+     *                     type: String (Required)
+     *                     fieldName: String (Required)
+     *                     boost: double (Required)
+     *                     interpolation: String(linear/constant/quadratic/logarithmic) (Optional)
+     *                 }
+     *             ]
+     *             functionAggregation: String(sum/average/minimum/maximum/firstMatching) (Optional)
+     *         }
+     *     ]
+     *     defaultScoringProfile: String (Optional)
+     *     corsOptions (Optional): {
+     *         allowedOrigins (Required): [
+     *             String (Required)
+     *         ]
+     *         maxAgeInSeconds: Long (Optional)
+     *     }
+     *     suggesters (Optional): [
+     *          (Optional){
+     *             name: String (Required)
+     *             searchMode: String (Required)
+     *             sourceFields (Required): [
+     *                 String (Required)
+     *             ]
+     *         }
+     *     ]
+     *     analyzers (Optional): [
+     *          (Optional){
+     *             @odata.type: String (Required)
+     *             name: String (Required)
+     *         }
+     *     ]
+     *     tokenizers (Optional): [
+     *          (Optional){
+     *             @odata.type: String (Required)
+     *             name: String (Required)
+     *         }
+     *     ]
+     *     tokenFilters (Optional): [
+     *          (Optional){
+     *             @odata.type: String (Required)
+     *             name: String (Required)
+     *         }
+     *     ]
+     *     charFilters (Optional): [
+     *          (Optional){
+     *             @odata.type: String (Required)
+     *             name: String (Required)
+     *         }
+     *     ]
+     *     normalizers (Optional): [
+     *          (Optional){
+     *             @odata.type: String (Required)
+     *             name: String (Required)
+     *         }
+     *     ]
+     *     encryptionKey (Optional): {
+     *         keyVaultKeyName: String (Required)
+     *         keyVaultKeyVersion: String (Optional)
+     *         keyVaultUri: String (Required)
+     *         accessCredentials (Optional): {
+     *             applicationId: String (Required)
+     *             applicationSecret: String (Optional)
+     *         }
+     *         identity (Optional): {
+     *             @odata.type: String (Required)
+     *         }
+     *     }
+     *     similarity (Optional): {
+     *         @odata.type: String (Required)
+     *     }
+     *     semantic (Optional): {
+     *         defaultConfiguration: String (Optional)
+     *         configurations (Optional): [
+     *              (Optional){
+     *                 name: String (Required)
+     *                 prioritizedFields (Required): {
+     *                     titleField (Optional): {
+     *                         fieldName: String (Required)
+     *                     }
+     *                     prioritizedContentFields (Optional): [
+     *                         (recursive schema, see above)
+     *                     ]
+     *                     prioritizedKeywordsFields (Optional): [
+     *                         (recursive schema, see above)
+     *                     ]
+     *                 }
+     *                 flightingOptIn: Boolean (Optional)
+     *             }
+     *         ]
+     *     }
+     *     vectorSearch (Optional): {
+     *         profiles (Optional): [
+     *              (Optional){
+     *                 name: String (Required)
+     *                 algorithm: String (Required)
+     *                 vectorizer: String (Optional)
+     *                 compression: String (Optional)
+     *             }
+     *         ]
+     *         algorithms (Optional): [
+     *              (Optional){
+     *                 kind: String(hnsw/exhaustiveKnn) (Required)
+     *                 name: String (Required)
+     *             }
+     *         ]
+     *         vectorizers (Optional): [
+     *              (Optional){
+     *                 kind: String(azureOpenAI/customWebApi/aiServicesVision/aml) (Required)
+     *                 name: String (Required)
+     *             }
+     *         ]
+     *         compressions (Optional): [
+     *              (Optional){
+     *                 kind: String(scalarQuantization/binaryQuantization) (Required)
+     *                 name: String (Required)
+     *                 rerankWithOriginalVectors: Boolean (Optional)
+     *                 defaultOversampling: Double (Optional)
+     *                 rescoringOptions (Optional): {
+     *                     enableRescoring: Boolean (Optional)
+     *                     defaultOversampling: Double (Optional)
+     *                     rescoreStorageMethod: String(preserveOriginals/discardOriginals) (Optional)
+     *                 }
+     *                 truncationDimension: Integer (Optional)
+     *             }
+     *         ]
+     *     }
+     *     @odata.etag: String (Optional)
+     * }
+     * }
+     * 
+ * + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     name: String (Required)
+     *     fields (Required): [
+     *          (Required){
+     *             name: String (Required)
+     *             type: String(Edm.String/Edm.Int32/Edm.Int64/Edm.Double/Edm.Boolean/Edm.DateTimeOffset/Edm.GeographyPoint/Edm.ComplexType/Edm.Single/Edm.Half/Edm.Int16/Edm.SByte/Edm.Byte) (Required)
+     *             key: Boolean (Optional)
+     *             retrievable: Boolean (Optional)
+     *             stored: Boolean (Optional)
+     *             searchable: Boolean (Optional)
+     *             filterable: Boolean (Optional)
+     *             sortable: Boolean (Optional)
+     *             facetable: Boolean (Optional)
+     *             analyzer: String(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) (Optional)
+     *             searchAnalyzer: String(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) (Optional)
+     *             indexAnalyzer: String(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) (Optional)
+     *             normalizer: String(asciifolding/elision/lowercase/standard/uppercase) (Optional)
+     *             dimensions: Integer (Optional)
+     *             vectorSearchProfile: String (Optional)
+     *             vectorEncoding: String(packedBit) (Optional)
+     *             synonymMaps (Optional): [
+     *                 String (Optional)
+     *             ]
+     *             fields (Optional): [
+     *                 (recursive schema, see above)
+     *             ]
+     *         }
+     *     ]
+     *     scoringProfiles (Optional): [
+     *          (Optional){
+     *             name: String (Required)
+     *             text (Optional): {
+     *                 weights (Required): {
+     *                     String: double (Required)
+     *                 }
+     *             }
+     *             functions (Optional): [
+     *                  (Optional){
+     *                     type: String (Required)
+     *                     fieldName: String (Required)
+     *                     boost: double (Required)
+     *                     interpolation: String(linear/constant/quadratic/logarithmic) (Optional)
+     *                 }
+     *             ]
+     *             functionAggregation: String(sum/average/minimum/maximum/firstMatching) (Optional)
+     *         }
+     *     ]
+     *     defaultScoringProfile: String (Optional)
+     *     corsOptions (Optional): {
+     *         allowedOrigins (Required): [
+     *             String (Required)
+     *         ]
+     *         maxAgeInSeconds: Long (Optional)
+     *     }
+     *     suggesters (Optional): [
+     *          (Optional){
+     *             name: String (Required)
+     *             searchMode: String (Required)
+     *             sourceFields (Required): [
+     *                 String (Required)
+     *             ]
+     *         }
+     *     ]
+     *     analyzers (Optional): [
+     *          (Optional){
+     *             @odata.type: String (Required)
+     *             name: String (Required)
+     *         }
+     *     ]
+     *     tokenizers (Optional): [
+     *          (Optional){
+     *             @odata.type: String (Required)
+     *             name: String (Required)
+     *         }
+     *     ]
+     *     tokenFilters (Optional): [
+     *          (Optional){
+     *             @odata.type: String (Required)
+     *             name: String (Required)
+     *         }
+     *     ]
+     *     charFilters (Optional): [
+     *          (Optional){
+     *             @odata.type: String (Required)
+     *             name: String (Required)
+     *         }
+     *     ]
+     *     normalizers (Optional): [
+     *          (Optional){
+     *             @odata.type: String (Required)
+     *             name: String (Required)
+     *         }
+     *     ]
+     *     encryptionKey (Optional): {
+     *         keyVaultKeyName: String (Required)
+     *         keyVaultKeyVersion: String (Optional)
+     *         keyVaultUri: String (Required)
+     *         accessCredentials (Optional): {
+     *             applicationId: String (Required)
+     *             applicationSecret: String (Optional)
+     *         }
+     *         identity (Optional): {
+     *             @odata.type: String (Required)
+     *         }
+     *     }
+     *     similarity (Optional): {
+     *         @odata.type: String (Required)
+     *     }
+     *     semantic (Optional): {
+     *         defaultConfiguration: String (Optional)
+     *         configurations (Optional): [
+     *              (Optional){
+     *                 name: String (Required)
+     *                 prioritizedFields (Required): {
+     *                     titleField (Optional): {
+     *                         fieldName: String (Required)
+     *                     }
+     *                     prioritizedContentFields (Optional): [
+     *                         (recursive schema, see above)
+     *                     ]
+     *                     prioritizedKeywordsFields (Optional): [
+     *                         (recursive schema, see above)
+     *                     ]
+     *                 }
+     *                 flightingOptIn: Boolean (Optional)
+     *             }
+     *         ]
+     *     }
+     *     vectorSearch (Optional): {
+     *         profiles (Optional): [
+     *              (Optional){
+     *                 name: String (Required)
+     *                 algorithm: String (Required)
+     *                 vectorizer: String (Optional)
+     *                 compression: String (Optional)
+     *             }
+     *         ]
+     *         algorithms (Optional): [
+     *              (Optional){
+     *                 kind: String(hnsw/exhaustiveKnn) (Required)
+     *                 name: String (Required)
+     *             }
+     *         ]
+     *         vectorizers (Optional): [
+     *              (Optional){
+     *                 kind: String(azureOpenAI/customWebApi/aiServicesVision/aml) (Required)
+     *                 name: String (Required)
+     *             }
+     *         ]
+     *         compressions (Optional): [
+     *              (Optional){
+     *                 kind: String(scalarQuantization/binaryQuantization) (Required)
+     *                 name: String (Required)
+     *                 rerankWithOriginalVectors: Boolean (Optional)
+     *                 defaultOversampling: Double (Optional)
+     *                 rescoringOptions (Optional): {
+     *                     enableRescoring: Boolean (Optional)
+     *                     defaultOversampling: Double (Optional)
+     *                     rescoreStorageMethod: String(preserveOriginals/discardOriginals) (Optional)
+     *                 }
+     *                 truncationDimension: Integer (Optional)
+     *             }
+     *         ]
+     *     }
+     *     @odata.etag: String (Optional)
+     * }
+     * }
+     * 
+ * + * @param indexName The name of the index. + * @param index The definition of the index to create or update. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return represents a search index definition, which describes the fields and search + * behavior of an index along with {@link Response}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Response createOrUpdateWithResponse(String indexName, BinaryData index, + RequestOptions requestOptions) { + final String prefer = "return=representation"; + final String contentType = "application/json"; + final String accept = "application/json"; + return service.createOrUpdateSync(this.client.getEndpoint(), this.client.getServiceVersion().getVersion(), + prefer, indexName, contentType, accept, index, requestOptions, Context.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. + *

Header Parameters

+ * + * + * + * + * + *
Header Parameters
NameTypeRequiredDescription
If-MatchStringNoDefines the If-Match condition. The operation will be + * performed only if the ETag on the server matches this value.
If-None-MatchStringNoDefines the If-None-Match condition. The operation will + * be performed only if the ETag on the server does not match this value.
+ * You can add these to a request with {@link RequestOptions#addHeader} + * + * @param indexName The name of the index. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return the {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono> deleteWithResponseAsync(String indexName, RequestOptions requestOptions) { + final String accept = "application/json"; + return FluxUtil.withContext(context -> service.delete(this.client.getEndpoint(), + this.client.getServiceVersion().getVersion(), indexName, accept, requestOptions, context)); + } + + /** + * 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. + *

Header Parameters

+ * + * + * + * + * + *
Header Parameters
NameTypeRequiredDescription
If-MatchStringNoDefines the If-Match condition. The operation will be + * performed only if the ETag on the server matches this value.
If-None-MatchStringNoDefines the If-None-Match condition. The operation will + * be performed only if the ETag on the server does not match this value.
+ * You can add these to a request with {@link RequestOptions#addHeader} + * + * @param indexName The name of the index. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return the {@link Response}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Response deleteWithResponse(String indexName, RequestOptions requestOptions) { + final String accept = "application/json"; + return service.deleteSync(this.client.getEndpoint(), this.client.getServiceVersion().getVersion(), indexName, + accept, requestOptions, Context.NONE); + } + + /** + * Retrieves an index definition. + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     name: String (Required)
+     *     fields (Required): [
+     *          (Required){
+     *             name: String (Required)
+     *             type: String(Edm.String/Edm.Int32/Edm.Int64/Edm.Double/Edm.Boolean/Edm.DateTimeOffset/Edm.GeographyPoint/Edm.ComplexType/Edm.Single/Edm.Half/Edm.Int16/Edm.SByte/Edm.Byte) (Required)
+     *             key: Boolean (Optional)
+     *             retrievable: Boolean (Optional)
+     *             stored: Boolean (Optional)
+     *             searchable: Boolean (Optional)
+     *             filterable: Boolean (Optional)
+     *             sortable: Boolean (Optional)
+     *             facetable: Boolean (Optional)
+     *             analyzer: String(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) (Optional)
+     *             searchAnalyzer: String(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) (Optional)
+     *             indexAnalyzer: String(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) (Optional)
+     *             normalizer: String(asciifolding/elision/lowercase/standard/uppercase) (Optional)
+     *             dimensions: Integer (Optional)
+     *             vectorSearchProfile: String (Optional)
+     *             vectorEncoding: String(packedBit) (Optional)
+     *             synonymMaps (Optional): [
+     *                 String (Optional)
+     *             ]
+     *             fields (Optional): [
+     *                 (recursive schema, see above)
+     *             ]
+     *         }
+     *     ]
+     *     scoringProfiles (Optional): [
+     *          (Optional){
+     *             name: String (Required)
+     *             text (Optional): {
+     *                 weights (Required): {
+     *                     String: double (Required)
+     *                 }
+     *             }
+     *             functions (Optional): [
+     *                  (Optional){
+     *                     type: String (Required)
+     *                     fieldName: String (Required)
+     *                     boost: double (Required)
+     *                     interpolation: String(linear/constant/quadratic/logarithmic) (Optional)
+     *                 }
+     *             ]
+     *             functionAggregation: String(sum/average/minimum/maximum/firstMatching) (Optional)
+     *         }
+     *     ]
+     *     defaultScoringProfile: String (Optional)
+     *     corsOptions (Optional): {
+     *         allowedOrigins (Required): [
+     *             String (Required)
+     *         ]
+     *         maxAgeInSeconds: Long (Optional)
+     *     }
+     *     suggesters (Optional): [
+     *          (Optional){
+     *             name: String (Required)
+     *             searchMode: String (Required)
+     *             sourceFields (Required): [
+     *                 String (Required)
+     *             ]
+     *         }
+     *     ]
+     *     analyzers (Optional): [
+     *          (Optional){
+     *             @odata.type: String (Required)
+     *             name: String (Required)
+     *         }
+     *     ]
+     *     tokenizers (Optional): [
+     *          (Optional){
+     *             @odata.type: String (Required)
+     *             name: String (Required)
+     *         }
+     *     ]
+     *     tokenFilters (Optional): [
+     *          (Optional){
+     *             @odata.type: String (Required)
+     *             name: String (Required)
+     *         }
+     *     ]
+     *     charFilters (Optional): [
+     *          (Optional){
+     *             @odata.type: String (Required)
+     *             name: String (Required)
+     *         }
+     *     ]
+     *     normalizers (Optional): [
+     *          (Optional){
+     *             @odata.type: String (Required)
+     *             name: String (Required)
+     *         }
+     *     ]
+     *     encryptionKey (Optional): {
+     *         keyVaultKeyName: String (Required)
+     *         keyVaultKeyVersion: String (Optional)
+     *         keyVaultUri: String (Required)
+     *         accessCredentials (Optional): {
+     *             applicationId: String (Required)
+     *             applicationSecret: String (Optional)
+     *         }
+     *         identity (Optional): {
+     *             @odata.type: String (Required)
+     *         }
+     *     }
+     *     similarity (Optional): {
+     *         @odata.type: String (Required)
+     *     }
+     *     semantic (Optional): {
+     *         defaultConfiguration: String (Optional)
+     *         configurations (Optional): [
+     *              (Optional){
+     *                 name: String (Required)
+     *                 prioritizedFields (Required): {
+     *                     titleField (Optional): {
+     *                         fieldName: String (Required)
+     *                     }
+     *                     prioritizedContentFields (Optional): [
+     *                         (recursive schema, see above)
+     *                     ]
+     *                     prioritizedKeywordsFields (Optional): [
+     *                         (recursive schema, see above)
+     *                     ]
+     *                 }
+     *                 flightingOptIn: Boolean (Optional)
+     *             }
+     *         ]
+     *     }
+     *     vectorSearch (Optional): {
+     *         profiles (Optional): [
+     *              (Optional){
+     *                 name: String (Required)
+     *                 algorithm: String (Required)
+     *                 vectorizer: String (Optional)
+     *                 compression: String (Optional)
+     *             }
+     *         ]
+     *         algorithms (Optional): [
+     *              (Optional){
+     *                 kind: String(hnsw/exhaustiveKnn) (Required)
+     *                 name: String (Required)
+     *             }
+     *         ]
+     *         vectorizers (Optional): [
+     *              (Optional){
+     *                 kind: String(azureOpenAI/customWebApi/aiServicesVision/aml) (Required)
+     *                 name: String (Required)
+     *             }
+     *         ]
+     *         compressions (Optional): [
+     *              (Optional){
+     *                 kind: String(scalarQuantization/binaryQuantization) (Required)
+     *                 name: String (Required)
+     *                 rerankWithOriginalVectors: Boolean (Optional)
+     *                 defaultOversampling: Double (Optional)
+     *                 rescoringOptions (Optional): {
+     *                     enableRescoring: Boolean (Optional)
+     *                     defaultOversampling: Double (Optional)
+     *                     rescoreStorageMethod: String(preserveOriginals/discardOriginals) (Optional)
+     *                 }
+     *                 truncationDimension: Integer (Optional)
+     *             }
+     *         ]
+     *     }
+     *     @odata.etag: String (Optional)
+     * }
+     * }
+     * 
+ * + * @param indexName The name of the index. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return represents a search index definition, which describes the fields and search + * behavior of an index along with {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono> getWithResponseAsync(String indexName, RequestOptions requestOptions) { + final String accept = "application/json"; + return FluxUtil.withContext(context -> service.get(this.client.getEndpoint(), + this.client.getServiceVersion().getVersion(), indexName, accept, requestOptions, context)); + } + + /** + * Retrieves an index definition. + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     name: String (Required)
+     *     fields (Required): [
+     *          (Required){
+     *             name: String (Required)
+     *             type: String(Edm.String/Edm.Int32/Edm.Int64/Edm.Double/Edm.Boolean/Edm.DateTimeOffset/Edm.GeographyPoint/Edm.ComplexType/Edm.Single/Edm.Half/Edm.Int16/Edm.SByte/Edm.Byte) (Required)
+     *             key: Boolean (Optional)
+     *             retrievable: Boolean (Optional)
+     *             stored: Boolean (Optional)
+     *             searchable: Boolean (Optional)
+     *             filterable: Boolean (Optional)
+     *             sortable: Boolean (Optional)
+     *             facetable: Boolean (Optional)
+     *             analyzer: String(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) (Optional)
+     *             searchAnalyzer: String(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) (Optional)
+     *             indexAnalyzer: String(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) (Optional)
+     *             normalizer: String(asciifolding/elision/lowercase/standard/uppercase) (Optional)
+     *             dimensions: Integer (Optional)
+     *             vectorSearchProfile: String (Optional)
+     *             vectorEncoding: String(packedBit) (Optional)
+     *             synonymMaps (Optional): [
+     *                 String (Optional)
+     *             ]
+     *             fields (Optional): [
+     *                 (recursive schema, see above)
+     *             ]
+     *         }
+     *     ]
+     *     scoringProfiles (Optional): [
+     *          (Optional){
+     *             name: String (Required)
+     *             text (Optional): {
+     *                 weights (Required): {
+     *                     String: double (Required)
+     *                 }
+     *             }
+     *             functions (Optional): [
+     *                  (Optional){
+     *                     type: String (Required)
+     *                     fieldName: String (Required)
+     *                     boost: double (Required)
+     *                     interpolation: String(linear/constant/quadratic/logarithmic) (Optional)
+     *                 }
+     *             ]
+     *             functionAggregation: String(sum/average/minimum/maximum/firstMatching) (Optional)
+     *         }
+     *     ]
+     *     defaultScoringProfile: String (Optional)
+     *     corsOptions (Optional): {
+     *         allowedOrigins (Required): [
+     *             String (Required)
+     *         ]
+     *         maxAgeInSeconds: Long (Optional)
+     *     }
+     *     suggesters (Optional): [
+     *          (Optional){
+     *             name: String (Required)
+     *             searchMode: String (Required)
+     *             sourceFields (Required): [
+     *                 String (Required)
+     *             ]
+     *         }
+     *     ]
+     *     analyzers (Optional): [
+     *          (Optional){
+     *             @odata.type: String (Required)
+     *             name: String (Required)
+     *         }
+     *     ]
+     *     tokenizers (Optional): [
+     *          (Optional){
+     *             @odata.type: String (Required)
+     *             name: String (Required)
+     *         }
+     *     ]
+     *     tokenFilters (Optional): [
+     *          (Optional){
+     *             @odata.type: String (Required)
+     *             name: String (Required)
+     *         }
+     *     ]
+     *     charFilters (Optional): [
+     *          (Optional){
+     *             @odata.type: String (Required)
+     *             name: String (Required)
+     *         }
+     *     ]
+     *     normalizers (Optional): [
+     *          (Optional){
+     *             @odata.type: String (Required)
+     *             name: String (Required)
+     *         }
+     *     ]
+     *     encryptionKey (Optional): {
+     *         keyVaultKeyName: String (Required)
+     *         keyVaultKeyVersion: String (Optional)
+     *         keyVaultUri: String (Required)
+     *         accessCredentials (Optional): {
+     *             applicationId: String (Required)
+     *             applicationSecret: String (Optional)
+     *         }
+     *         identity (Optional): {
+     *             @odata.type: String (Required)
+     *         }
+     *     }
+     *     similarity (Optional): {
+     *         @odata.type: String (Required)
+     *     }
+     *     semantic (Optional): {
+     *         defaultConfiguration: String (Optional)
+     *         configurations (Optional): [
+     *              (Optional){
+     *                 name: String (Required)
+     *                 prioritizedFields (Required): {
+     *                     titleField (Optional): {
+     *                         fieldName: String (Required)
+     *                     }
+     *                     prioritizedContentFields (Optional): [
+     *                         (recursive schema, see above)
+     *                     ]
+     *                     prioritizedKeywordsFields (Optional): [
+     *                         (recursive schema, see above)
+     *                     ]
+     *                 }
+     *                 flightingOptIn: Boolean (Optional)
+     *             }
+     *         ]
+     *     }
+     *     vectorSearch (Optional): {
+     *         profiles (Optional): [
+     *              (Optional){
+     *                 name: String (Required)
+     *                 algorithm: String (Required)
+     *                 vectorizer: String (Optional)
+     *                 compression: String (Optional)
+     *             }
+     *         ]
+     *         algorithms (Optional): [
+     *              (Optional){
+     *                 kind: String(hnsw/exhaustiveKnn) (Required)
+     *                 name: String (Required)
+     *             }
+     *         ]
+     *         vectorizers (Optional): [
+     *              (Optional){
+     *                 kind: String(azureOpenAI/customWebApi/aiServicesVision/aml) (Required)
+     *                 name: String (Required)
+     *             }
+     *         ]
+     *         compressions (Optional): [
+     *              (Optional){
+     *                 kind: String(scalarQuantization/binaryQuantization) (Required)
+     *                 name: String (Required)
+     *                 rerankWithOriginalVectors: Boolean (Optional)
+     *                 defaultOversampling: Double (Optional)
+     *                 rescoringOptions (Optional): {
+     *                     enableRescoring: Boolean (Optional)
+     *                     defaultOversampling: Double (Optional)
+     *                     rescoreStorageMethod: String(preserveOriginals/discardOriginals) (Optional)
+     *                 }
+     *                 truncationDimension: Integer (Optional)
+     *             }
+     *         ]
+     *     }
+     *     @odata.etag: String (Optional)
+     * }
+     * }
+     * 
+ * + * @param indexName The name of the index. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return represents a search index definition, which describes the fields and search + * behavior of an index along with {@link Response}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Response getWithResponse(String indexName, RequestOptions requestOptions) { + final String accept = "application/json"; + return service.getSync(this.client.getEndpoint(), this.client.getServiceVersion().getVersion(), indexName, + accept, requestOptions, Context.NONE); + } + + /** + * Returns statistics for the given index, including a document count and storage + * usage. + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     documentCount: long (Required)
+     *     storageSize: long (Required)
+     *     vectorIndexSize: long (Required)
+     * }
+     * }
+     * 
+ * + * @param indexName The name of the index. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return statistics for a given index along with {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono> getStatisticsWithResponseAsync(String indexName, RequestOptions requestOptions) { + final String accept = "application/json"; + return FluxUtil.withContext(context -> service.getStatistics(this.client.getEndpoint(), + this.client.getServiceVersion().getVersion(), indexName, accept, requestOptions, context)); + } + + /** + * Returns statistics for the given index, including a document count and storage + * usage. + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     documentCount: long (Required)
+     *     storageSize: long (Required)
+     *     vectorIndexSize: long (Required)
+     * }
+     * }
+     * 
+ * + * @param indexName The name of the index. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return statistics for a given index along with {@link Response}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Response getStatisticsWithResponse(String indexName, RequestOptions requestOptions) { + final String accept = "application/json"; + return service.getStatisticsSync(this.client.getEndpoint(), this.client.getServiceVersion().getVersion(), + indexName, accept, requestOptions, Context.NONE); + } + + /** + * Shows how an analyzer breaks text into tokens. + *

Request Body Schema

+ * + *
+     * {@code
+     * {
+     *     text: String (Required)
+     *     analyzer: String(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) (Optional)
+     *     tokenizer: String(classic/edgeNGram/keyword_v2/letter/lowercase/microsoft_language_tokenizer/microsoft_language_stemming_tokenizer/nGram/path_hierarchy_v2/pattern/standard_v2/uax_url_email/whitespace) (Optional)
+     *     normalizer: String(asciifolding/elision/lowercase/standard/uppercase) (Optional)
+     *     tokenFilters (Optional): [
+     *         String(arabic_normalization/apostrophe/asciifolding/cjk_bigram/cjk_width/classic/common_grams/edgeNGram_v2/elision/german_normalization/hindi_normalization/indic_normalization/keyword_repeat/kstem/length/limit/lowercase/nGram_v2/persian_normalization/phonetic/porter_stem/reverse/scandinavian_normalization/scandinavian_folding/shingle/snowball/sorani_normalization/stemmer/stopwords/trim/truncate/unique/uppercase/word_delimiter) (Optional)
+     *     ]
+     *     charFilters (Optional): [
+     *         String(html_strip) (Optional)
+     *     ]
+     * }
+     * }
+     * 
+ * + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     tokens (Required): [
+     *          (Required){
+     *             token: String (Required)
+     *             startOffset: int (Required)
+     *             endOffset: int (Required)
+     *             position: int (Required)
+     *         }
+     *     ]
+     * }
+     * }
+     * 
+ * + * @param indexName The name of the index. + * @param request The text and analyzer or analysis components to test. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return the result of testing an analyzer on text along with {@link Response} on successful completion of + * {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono> analyzeWithResponseAsync(String indexName, BinaryData request, + RequestOptions requestOptions) { + final String contentType = "application/json"; + final String accept = "application/json"; + return FluxUtil.withContext( + context -> service.analyze(this.client.getEndpoint(), this.client.getServiceVersion().getVersion(), + indexName, contentType, accept, request, requestOptions, context)); + } + + /** + * Shows how an analyzer breaks text into tokens. + *

Request Body Schema

+ * + *
+     * {@code
+     * {
+     *     text: String (Required)
+     *     analyzer: String(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) (Optional)
+     *     tokenizer: String(classic/edgeNGram/keyword_v2/letter/lowercase/microsoft_language_tokenizer/microsoft_language_stemming_tokenizer/nGram/path_hierarchy_v2/pattern/standard_v2/uax_url_email/whitespace) (Optional)
+     *     normalizer: String(asciifolding/elision/lowercase/standard/uppercase) (Optional)
+     *     tokenFilters (Optional): [
+     *         String(arabic_normalization/apostrophe/asciifolding/cjk_bigram/cjk_width/classic/common_grams/edgeNGram_v2/elision/german_normalization/hindi_normalization/indic_normalization/keyword_repeat/kstem/length/limit/lowercase/nGram_v2/persian_normalization/phonetic/porter_stem/reverse/scandinavian_normalization/scandinavian_folding/shingle/snowball/sorani_normalization/stemmer/stopwords/trim/truncate/unique/uppercase/word_delimiter) (Optional)
+     *     ]
+     *     charFilters (Optional): [
+     *         String(html_strip) (Optional)
+     *     ]
+     * }
+     * }
+     * 
+ * + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     tokens (Required): [
+     *          (Required){
+     *             token: String (Required)
+     *             startOffset: int (Required)
+     *             endOffset: int (Required)
+     *             position: int (Required)
+     *         }
+     *     ]
+     * }
+     * }
+     * 
+ * + * @param indexName The name of the index. + * @param request The text and analyzer or analysis components to test. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return the result of testing an analyzer on text along with {@link Response}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Response analyzeWithResponse(String indexName, BinaryData request, + RequestOptions requestOptions) { + final String contentType = "application/json"; + final String accept = "application/json"; + return service.analyzeSync(this.client.getEndpoint(), this.client.getServiceVersion().getVersion(), indexName, + contentType, accept, request, requestOptions, Context.NONE); + } + + private List getValues(BinaryData binaryData, String path) { + try { + Map obj = binaryData.toObject(Map.class); + List values = (List) obj.get(path); + return values.stream().map(BinaryData::fromObject).collect(Collectors.toList()); + } catch (RuntimeException e) { + return null; + } + } + + private String getNextLink(BinaryData binaryData, String path) { + try { + Map obj = binaryData.toObject(Map.class); + return (String) obj.get(path); + } catch (RuntimeException e) { + return null; + } + } +} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/implementation/SearchClientImpl.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/implementation/SearchClientImpl.java new file mode 100644 index 000000000000..fc48d125d362 --- /dev/null +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/implementation/SearchClientImpl.java @@ -0,0 +1,530 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.search.documents.implementation; + +import com.azure.core.annotation.ExpectedResponses; +import com.azure.core.annotation.Get; +import com.azure.core.annotation.HeaderParam; +import com.azure.core.annotation.Host; +import com.azure.core.annotation.HostParam; +import com.azure.core.annotation.QueryParam; +import com.azure.core.annotation.ReturnType; +import com.azure.core.annotation.ServiceInterface; +import com.azure.core.annotation.ServiceMethod; +import com.azure.core.annotation.UnexpectedResponseExceptionType; +import com.azure.core.exception.ClientAuthenticationException; +import com.azure.core.exception.HttpResponseException; +import com.azure.core.exception.ResourceModifiedException; +import com.azure.core.exception.ResourceNotFoundException; +import com.azure.core.http.HttpPipeline; +import com.azure.core.http.HttpPipelineBuilder; +import com.azure.core.http.policy.RetryPolicy; +import com.azure.core.http.policy.UserAgentPolicy; +import com.azure.core.http.rest.PagedFlux; +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.http.rest.PagedResponse; +import com.azure.core.http.rest.PagedResponseBase; +import com.azure.core.http.rest.RequestOptions; +import com.azure.core.http.rest.Response; +import com.azure.core.http.rest.RestProxy; +import com.azure.core.util.BinaryData; +import com.azure.core.util.Context; +import com.azure.core.util.FluxUtil; +import com.azure.core.util.serializer.JacksonAdapter; +import com.azure.core.util.serializer.SerializerAdapter; +import com.azure.search.documents.SearchServiceVersion; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; +import reactor.core.publisher.Mono; + +/** + * Initializes a new instance of the SearchClient type. + */ +public final class SearchClientImpl { + /** + * The proxy service used to perform REST calls. + */ + private final SearchClientService service; + + /** + * Service host. + */ + private final String endpoint; + + /** + * Gets Service host. + * + * @return the endpoint value. + */ + public String getEndpoint() { + return this.endpoint; + } + + /** + * Service version. + */ + private final SearchServiceVersion serviceVersion; + + /** + * Gets Service version. + * + * @return the serviceVersion value. + */ + public SearchServiceVersion getServiceVersion() { + return this.serviceVersion; + } + + /** + * The HTTP pipeline to send requests through. + */ + private final HttpPipeline httpPipeline; + + /** + * Gets The HTTP pipeline to send requests through. + * + * @return the httpPipeline value. + */ + public HttpPipeline getHttpPipeline() { + return this.httpPipeline; + } + + /** + * The serializer to serialize an object into a string. + */ + private final SerializerAdapter serializerAdapter; + + /** + * Gets The serializer to serialize an object into a string. + * + * @return the serializerAdapter value. + */ + public SerializerAdapter getSerializerAdapter() { + return this.serializerAdapter; + } + + /** + * The DataSourcesImpl object to access its operations. + */ + private final DataSourcesImpl dataSources; + + /** + * Gets the DataSourcesImpl object to access its operations. + * + * @return the DataSourcesImpl object. + */ + public DataSourcesImpl getDataSources() { + return this.dataSources; + } + + /** + * The IndexersImpl object to access its operations. + */ + private final IndexersImpl indexers; + + /** + * Gets the IndexersImpl object to access its operations. + * + * @return the IndexersImpl object. + */ + public IndexersImpl getIndexers() { + return this.indexers; + } + + /** + * The SkillsetsImpl object to access its operations. + */ + private final SkillsetsImpl skillsets; + + /** + * Gets the SkillsetsImpl object to access its operations. + * + * @return the SkillsetsImpl object. + */ + public SkillsetsImpl getSkillsets() { + return this.skillsets; + } + + /** + * The SynonymMapsImpl object to access its operations. + */ + private final SynonymMapsImpl synonymMaps; + + /** + * Gets the SynonymMapsImpl object to access its operations. + * + * @return the SynonymMapsImpl object. + */ + public SynonymMapsImpl getSynonymMaps() { + return this.synonymMaps; + } + + /** + * The IndexesImpl object to access its operations. + */ + private final IndexesImpl indexes; + + /** + * Gets the IndexesImpl object to access its operations. + * + * @return the IndexesImpl object. + */ + public IndexesImpl getIndexes() { + return this.indexes; + } + + /** + * The AliasesImpl object to access its operations. + */ + private final AliasesImpl aliases; + + /** + * Gets the AliasesImpl object to access its operations. + * + * @return the AliasesImpl object. + */ + public AliasesImpl getAliases() { + return this.aliases; + } + + /** + * The DocumentsImpl object to access its operations. + */ + private final DocumentsImpl documents; + + /** + * Gets the DocumentsImpl object to access its operations. + * + * @return the DocumentsImpl object. + */ + public DocumentsImpl getDocuments() { + return this.documents; + } + + /** + * Initializes an instance of SearchClient client. + * + * @param endpoint Service host. + * @param serviceVersion Service version. + */ + public SearchClientImpl(String endpoint, SearchServiceVersion serviceVersion) { + this(new HttpPipelineBuilder().policies(new UserAgentPolicy(), new RetryPolicy()).build(), + JacksonAdapter.createDefaultSerializerAdapter(), endpoint, serviceVersion); + } + + /** + * Initializes an instance of SearchClient client. + * + * @param httpPipeline The HTTP pipeline to send requests through. + * @param endpoint Service host. + * @param serviceVersion Service version. + */ + public SearchClientImpl(HttpPipeline httpPipeline, String endpoint, SearchServiceVersion serviceVersion) { + this(httpPipeline, JacksonAdapter.createDefaultSerializerAdapter(), endpoint, serviceVersion); + } + + /** + * Initializes an instance of SearchClient client. + * + * @param httpPipeline The HTTP pipeline to send requests through. + * @param serializerAdapter The serializer to serialize an object into a string. + * @param endpoint Service host. + * @param serviceVersion Service version. + */ + public SearchClientImpl(HttpPipeline httpPipeline, SerializerAdapter serializerAdapter, String endpoint, + SearchServiceVersion serviceVersion) { + this.httpPipeline = httpPipeline; + this.serializerAdapter = serializerAdapter; + this.endpoint = endpoint; + this.serviceVersion = serviceVersion; + this.dataSources = new DataSourcesImpl(this); + this.indexers = new IndexersImpl(this); + this.skillsets = new SkillsetsImpl(this); + this.synonymMaps = new SynonymMapsImpl(this); + this.indexes = new IndexesImpl(this); + this.aliases = new AliasesImpl(this); + this.documents = new DocumentsImpl(this); + this.service = RestProxy.create(SearchClientService.class, this.httpPipeline, this.getSerializerAdapter()); + } + + /** + * The interface defining all the services for SearchClient to be used by the proxy service to perform REST calls. + */ + @Host("{endpoint}") + @ServiceInterface(name = "SearchClient") + public interface SearchClientService { + @Get("/servicestats") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Mono> getServiceStatistics(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, + RequestOptions requestOptions, Context context); + + @Get("/servicestats") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Response getServiceStatisticsSync(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, + RequestOptions requestOptions, Context context); + + @Get("/indexstats") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Mono> getIndexStatsSummary(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, + RequestOptions requestOptions, Context context); + + @Get("/indexstats") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Response getIndexStatsSummarySync(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, + RequestOptions requestOptions, Context context); + } + + /** + * Gets service level statistics for a search service. + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     counters (Required): {
+     *         aliasesCount (Required): {
+     *             usage: long (Required)
+     *             quota: Long (Optional)
+     *         }
+     *         documentCount (Required): (recursive schema, see documentCount above)
+     *         indexesCount (Required): (recursive schema, see indexesCount above)
+     *         indexersCount (Required): (recursive schema, see indexersCount above)
+     *         dataSourcesCount (Required): (recursive schema, see dataSourcesCount above)
+     *         storageSize (Required): (recursive schema, see storageSize above)
+     *         synonymMaps (Required): (recursive schema, see synonymMaps above)
+     *         skillsetCount (Required): (recursive schema, see skillsetCount above)
+     *         vectorIndexSize (Required): (recursive schema, see vectorIndexSize above)
+     *     }
+     *     limits (Required): {
+     *         maxFieldsPerIndex: Integer (Optional)
+     *         maxFieldNestingDepthPerIndex: Integer (Optional)
+     *         maxComplexCollectionFieldsPerIndex: Integer (Optional)
+     *         maxComplexObjectsInCollectionsPerDocument: Integer (Optional)
+     *         maxStoragePerIndex: Long (Optional)
+     *     }
+     * }
+     * }
+     * 
+ * + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return service level statistics for a search service along with {@link Response} on successful completion of + * {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono> getServiceStatisticsWithResponseAsync(RequestOptions requestOptions) { + final String accept = "application/json"; + return FluxUtil.withContext(context -> service.getServiceStatistics(this.getEndpoint(), + this.getServiceVersion().getVersion(), accept, requestOptions, context)); + } + + /** + * Gets service level statistics for a search service. + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     counters (Required): {
+     *         aliasesCount (Required): {
+     *             usage: long (Required)
+     *             quota: Long (Optional)
+     *         }
+     *         documentCount (Required): (recursive schema, see documentCount above)
+     *         indexesCount (Required): (recursive schema, see indexesCount above)
+     *         indexersCount (Required): (recursive schema, see indexersCount above)
+     *         dataSourcesCount (Required): (recursive schema, see dataSourcesCount above)
+     *         storageSize (Required): (recursive schema, see storageSize above)
+     *         synonymMaps (Required): (recursive schema, see synonymMaps above)
+     *         skillsetCount (Required): (recursive schema, see skillsetCount above)
+     *         vectorIndexSize (Required): (recursive schema, see vectorIndexSize above)
+     *     }
+     *     limits (Required): {
+     *         maxFieldsPerIndex: Integer (Optional)
+     *         maxFieldNestingDepthPerIndex: Integer (Optional)
+     *         maxComplexCollectionFieldsPerIndex: Integer (Optional)
+     *         maxComplexObjectsInCollectionsPerDocument: Integer (Optional)
+     *         maxStoragePerIndex: Long (Optional)
+     *     }
+     * }
+     * }
+     * 
+ * + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return service level statistics for a search service along with {@link Response}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Response getServiceStatisticsWithResponse(RequestOptions requestOptions) { + final String accept = "application/json"; + return service.getServiceStatisticsSync(this.getEndpoint(), this.getServiceVersion().getVersion(), accept, + requestOptions, Context.NONE); + } + + /** + * Retrieves a summary of statistics for all indexes in the search service. + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     name: String (Required)
+     *     documentCount: long (Required)
+     *     storageSize: long (Required)
+     *     vectorIndexSize: Long (Optional)
+     * }
+     * }
+     * 
+ * + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return response from a request to retrieve stats summary of all indexes along with {@link PagedResponse} on + * successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> getIndexStatsSummarySinglePageAsync(RequestOptions requestOptions) { + final String accept = "application/json"; + return FluxUtil + .withContext(context -> service.getIndexStatsSummary(this.getEndpoint(), + this.getServiceVersion().getVersion(), accept, requestOptions, context)) + .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), + getValues(res.getValue(), "value"), null, null)); + } + + /** + * Retrieves a summary of statistics for all indexes in the search service. + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     name: String (Required)
+     *     documentCount: long (Required)
+     *     storageSize: long (Required)
+     *     vectorIndexSize: Long (Optional)
+     * }
+     * }
+     * 
+ * + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return response from a request to retrieve stats summary of all indexes as paginated response with + * {@link PagedFlux}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + public PagedFlux getIndexStatsSummaryAsync(RequestOptions requestOptions) { + return new PagedFlux<>(() -> getIndexStatsSummarySinglePageAsync(requestOptions)); + } + + /** + * Retrieves a summary of statistics for all indexes in the search service. + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     name: String (Required)
+     *     documentCount: long (Required)
+     *     storageSize: long (Required)
+     *     vectorIndexSize: Long (Optional)
+     * }
+     * }
+     * 
+ * + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return response from a request to retrieve stats summary of all indexes along with {@link PagedResponse}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private PagedResponse getIndexStatsSummarySinglePage(RequestOptions requestOptions) { + final String accept = "application/json"; + Response res = service.getIndexStatsSummarySync(this.getEndpoint(), + this.getServiceVersion().getVersion(), accept, requestOptions, Context.NONE); + return new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), + getValues(res.getValue(), "value"), null, null); + } + + /** + * Retrieves a summary of statistics for all indexes in the search service. + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     name: String (Required)
+     *     documentCount: long (Required)
+     *     storageSize: long (Required)
+     *     vectorIndexSize: Long (Optional)
+     * }
+     * }
+     * 
+ * + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return response from a request to retrieve stats summary of all indexes as paginated response with + * {@link PagedIterable}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + public PagedIterable getIndexStatsSummary(RequestOptions requestOptions) { + return new PagedIterable<>(() -> getIndexStatsSummarySinglePage(requestOptions)); + } + + private List getValues(BinaryData binaryData, String path) { + try { + Map obj = binaryData.toObject(Map.class); + List values = (List) obj.get(path); + return values.stream().map(BinaryData::fromObject).collect(Collectors.toList()); + } catch (RuntimeException e) { + return null; + } + } + + private String getNextLink(BinaryData binaryData, String path) { + try { + Map obj = binaryData.toObject(Map.class); + return (String) obj.get(path); + } catch (RuntimeException e) { + return null; + } + } +} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/implementation/SearchIndexClientImpl.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/implementation/SearchIndexClientImpl.java deleted file mode 100644 index 7b9f74684079..000000000000 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/implementation/SearchIndexClientImpl.java +++ /dev/null @@ -1,146 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -package com.azure.search.documents.implementation; - -import com.azure.core.http.HttpPipeline; -import com.azure.core.http.HttpPipelineBuilder; -import com.azure.core.http.policy.RetryPolicy; -import com.azure.core.http.policy.UserAgentPolicy; -import com.azure.core.util.serializer.JacksonAdapter; -import com.azure.core.util.serializer.SerializerAdapter; - -/** - * Initializes a new instance of the SearchIndexClient type. - */ -public final class SearchIndexClientImpl { - /** - * The endpoint URL of the search service. - */ - private final String endpoint; - - /** - * Gets The endpoint URL of the search service. - * - * @return the endpoint value. - */ - public String getEndpoint() { - return this.endpoint; - } - - /** - * The name of the index. - */ - private final String indexName; - - /** - * Gets The name of the index. - * - * @return the indexName value. - */ - public String getIndexName() { - return this.indexName; - } - - /** - * Api Version. - */ - private final String apiVersion; - - /** - * Gets Api Version. - * - * @return the apiVersion value. - */ - public String getApiVersion() { - return this.apiVersion; - } - - /** - * The HTTP pipeline to send requests through. - */ - private final HttpPipeline httpPipeline; - - /** - * Gets The HTTP pipeline to send requests through. - * - * @return the httpPipeline value. - */ - public HttpPipeline getHttpPipeline() { - return this.httpPipeline; - } - - /** - * The serializer to serialize an object into a string. - */ - private final SerializerAdapter serializerAdapter; - - /** - * Gets The serializer to serialize an object into a string. - * - * @return the serializerAdapter value. - */ - public SerializerAdapter getSerializerAdapter() { - return this.serializerAdapter; - } - - /** - * The DocumentsImpl object to access its operations. - */ - private final DocumentsImpl documents; - - /** - * Gets the DocumentsImpl object to access its operations. - * - * @return the DocumentsImpl object. - */ - public DocumentsImpl getDocuments() { - return this.documents; - } - - /** - * Initializes an instance of SearchIndexClient client. - * - * @param endpoint The endpoint URL of the search service. - * @param indexName The name of the index. - * @param apiVersion Api Version. - */ - public SearchIndexClientImpl(String endpoint, String indexName, String apiVersion) { - this(new HttpPipelineBuilder().policies(new UserAgentPolicy(), new RetryPolicy()).build(), - JacksonAdapter.createDefaultSerializerAdapter(), endpoint, indexName, apiVersion); - } - - /** - * Initializes an instance of SearchIndexClient client. - * - * @param httpPipeline The HTTP pipeline to send requests through. - * @param endpoint The endpoint URL of the search service. - * @param indexName The name of the index. - * @param apiVersion Api Version. - */ - public SearchIndexClientImpl(HttpPipeline httpPipeline, String endpoint, String indexName, String apiVersion) { - this(httpPipeline, JacksonAdapter.createDefaultSerializerAdapter(), endpoint, indexName, apiVersion); - } - - /** - * Initializes an instance of SearchIndexClient client. - * - * @param httpPipeline The HTTP pipeline to send requests through. - * @param serializerAdapter The serializer to serialize an object into a string. - * @param endpoint The endpoint URL of the search service. - * @param indexName The name of the index. - * @param apiVersion Api Version. - */ - public SearchIndexClientImpl(HttpPipeline httpPipeline, SerializerAdapter serializerAdapter, String endpoint, - String indexName, String apiVersion) { - this.httpPipeline = httpPipeline; - this.serializerAdapter = serializerAdapter; - this.endpoint = endpoint; - this.indexName = indexName; - this.apiVersion = apiVersion; - this.documents = new DocumentsImpl(this); - } -} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/implementation/SkillsetsImpl.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/implementation/SkillsetsImpl.java new file mode 100644 index 000000000000..49ead2031337 --- /dev/null +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/implementation/SkillsetsImpl.java @@ -0,0 +1,1977 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.search.documents.implementation; + +import com.azure.core.annotation.BodyParam; +import com.azure.core.annotation.Delete; +import com.azure.core.annotation.ExpectedResponses; +import com.azure.core.annotation.Get; +import com.azure.core.annotation.HeaderParam; +import com.azure.core.annotation.Host; +import com.azure.core.annotation.HostParam; +import com.azure.core.annotation.PathParam; +import com.azure.core.annotation.Post; +import com.azure.core.annotation.Put; +import com.azure.core.annotation.QueryParam; +import com.azure.core.annotation.ReturnType; +import com.azure.core.annotation.ServiceInterface; +import com.azure.core.annotation.ServiceMethod; +import com.azure.core.annotation.UnexpectedResponseExceptionType; +import com.azure.core.exception.ClientAuthenticationException; +import com.azure.core.exception.HttpResponseException; +import com.azure.core.exception.ResourceModifiedException; +import com.azure.core.exception.ResourceNotFoundException; +import com.azure.core.http.rest.RequestOptions; +import com.azure.core.http.rest.Response; +import com.azure.core.http.rest.RestProxy; +import com.azure.core.util.BinaryData; +import com.azure.core.util.Context; +import com.azure.core.util.FluxUtil; +import com.azure.search.documents.SearchServiceVersion; +import reactor.core.publisher.Mono; + +/** + * An instance of this class provides access to all the operations defined in Skillsets. + */ +public final class SkillsetsImpl { + /** + * The proxy service used to perform REST calls. + */ + private final SkillsetsService service; + + /** + * The service client containing this operation class. + */ + private final SearchClientImpl client; + + /** + * Initializes an instance of SkillsetsImpl. + * + * @param client the instance of the service client containing this operation class. + */ + SkillsetsImpl(SearchClientImpl client) { + this.service + = RestProxy.create(SkillsetsService.class, client.getHttpPipeline(), client.getSerializerAdapter()); + this.client = client; + } + + /** + * Gets Service version. + * + * @return the serviceVersion value. + */ + public SearchServiceVersion getServiceVersion() { + return client.getServiceVersion(); + } + + /** + * The interface defining all the services for SearchClientSkillsets to be used by the proxy service to perform REST + * calls. + */ + @Host("{endpoint}") + @ServiceInterface(name = "SearchClientSkillset") + public interface SkillsetsService { + @Put("/skillsets('{skillsetName}')") + @ExpectedResponses({ 200, 201 }) + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Mono> createOrUpdate(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @HeaderParam("Prefer") String prefer, + @PathParam("skillsetName") String skillsetName, @HeaderParam("Content-Type") String contentType, + @HeaderParam("Accept") String accept, @BodyParam("application/json") BinaryData skillset, + RequestOptions requestOptions, Context context); + + @Put("/skillsets('{skillsetName}')") + @ExpectedResponses({ 200, 201 }) + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Response createOrUpdateSync(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @HeaderParam("Prefer") String prefer, + @PathParam("skillsetName") String skillsetName, @HeaderParam("Content-Type") String contentType, + @HeaderParam("Accept") String accept, @BodyParam("application/json") BinaryData skillset, + RequestOptions requestOptions, Context context); + + @Delete("/skillsets('{skillsetName}')") + @ExpectedResponses({ 204, 404 }) + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Mono> delete(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @PathParam("skillsetName") String skillsetName, + @HeaderParam("Accept") String accept, RequestOptions requestOptions, Context context); + + @Delete("/skillsets('{skillsetName}')") + @ExpectedResponses({ 204, 404 }) + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Response deleteSync(@HostParam("endpoint") String endpoint, @QueryParam("api-version") String apiVersion, + @PathParam("skillsetName") String skillsetName, @HeaderParam("Accept") String accept, + RequestOptions requestOptions, Context context); + + @Get("/skillsets('{skillsetName}')") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Mono> get(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @PathParam("skillsetName") String skillsetName, + @HeaderParam("Accept") String accept, RequestOptions requestOptions, Context context); + + @Get("/skillsets('{skillsetName}')") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Response getSync(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @PathParam("skillsetName") String skillsetName, + @HeaderParam("Accept") String accept, RequestOptions requestOptions, Context context); + + @Get("/skillsets") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Mono> list(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, + RequestOptions requestOptions, Context context); + + @Get("/skillsets") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Response listSync(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, + RequestOptions requestOptions, Context context); + + @Post("/skillsets") + @ExpectedResponses({ 201 }) + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Mono> create(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @HeaderParam("Content-Type") String contentType, + @HeaderParam("Accept") String accept, @BodyParam("application/json") BinaryData skillset, + RequestOptions requestOptions, Context context); + + @Post("/skillsets") + @ExpectedResponses({ 201 }) + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Response createSync(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @HeaderParam("Content-Type") String contentType, + @HeaderParam("Accept") String accept, @BodyParam("application/json") BinaryData skillset, + RequestOptions requestOptions, Context context); + + @Post("/skillsets('{skillsetName}')/search.resetskills") + @ExpectedResponses({ 204 }) + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Mono> resetSkills(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @PathParam("skillsetName") String skillsetName, + @HeaderParam("Content-Type") String contentType, @HeaderParam("Accept") String accept, + @BodyParam("application/json") BinaryData skillNames, RequestOptions requestOptions, Context context); + + @Post("/skillsets('{skillsetName}')/search.resetskills") + @ExpectedResponses({ 204 }) + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Response resetSkillsSync(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @PathParam("skillsetName") String skillsetName, + @HeaderParam("Content-Type") String contentType, @HeaderParam("Accept") String accept, + @BodyParam("application/json") BinaryData skillNames, RequestOptions requestOptions, Context context); + } + + /** + * Creates a new skillset in a search service or updates the skillset if it + * already exists. + *

Query Parameters

+ * + * + * + * + * + *
Query Parameters
NameTypeRequiredDescription
ignoreResetRequirementsBooleanNoIgnores cache reset requirements.
disableCacheReprocessingChangeDetectionBooleanNoDisables cache reprocessing + * change detection.
+ * You can add these to a request with {@link RequestOptions#addQueryParam} + *

Header Parameters

+ * + * + * + * + * + *
Header Parameters
NameTypeRequiredDescription
If-MatchStringNoDefines the If-Match condition. The operation will be + * performed only if the ETag on the server matches this value.
If-None-MatchStringNoDefines the If-None-Match condition. The operation will + * be performed only if the ETag on the server does not match this value.
+ * You can add these to a request with {@link RequestOptions#addHeader} + *

Request Body Schema

+ * + *
+     * {@code
+     * {
+     *     name: String (Required)
+     *     description: String (Optional)
+     *     skills (Required): [
+     *          (Required){
+     *             @odata.type: String (Required)
+     *             name: String (Optional)
+     *             description: String (Optional)
+     *             context: String (Optional)
+     *             inputs (Required): [
+     *                  (Required){
+     *                     name: String (Required)
+     *                     source: String (Optional)
+     *                     sourceContext: String (Optional)
+     *                     inputs (Optional): [
+     *                         (recursive schema, see above)
+     *                     ]
+     *                 }
+     *             ]
+     *             outputs (Required): [
+     *                  (Required){
+     *                     name: String (Required)
+     *                     targetName: String (Optional)
+     *                 }
+     *             ]
+     *         }
+     *     ]
+     *     cognitiveServices (Optional): {
+     *         @odata.type: String (Required)
+     *         description: String (Optional)
+     *     }
+     *     knowledgeStore (Optional): {
+     *         storageConnectionString: String (Required)
+     *         projections (Required): [
+     *              (Required){
+     *                 tables (Optional): [
+     *                      (Optional){
+     *                         referenceKeyName: String (Optional)
+     *                         generatedKeyName: String (Optional)
+     *                         source: String (Optional)
+     *                         sourceContext: String (Optional)
+     *                         inputs (Optional): [
+     *                             (recursive schema, see above)
+     *                         ]
+     *                         tableName: String (Required)
+     *                     }
+     *                 ]
+     *                 objects (Optional): [
+     *                      (Optional){
+     *                         referenceKeyName: String (Optional)
+     *                         generatedKeyName: String (Optional)
+     *                         source: String (Optional)
+     *                         sourceContext: String (Optional)
+     *                         inputs (Optional): [
+     *                             (recursive schema, see above)
+     *                         ]
+     *                         storageContainer: String (Required)
+     *                     }
+     *                 ]
+     *                 files (Optional): [
+     *                      (Optional){
+     *                         referenceKeyName: String (Optional)
+     *                         generatedKeyName: String (Optional)
+     *                         source: String (Optional)
+     *                         sourceContext: String (Optional)
+     *                         inputs (Optional): [
+     *                             (recursive schema, see above)
+     *                         ]
+     *                         storageContainer: String (Required)
+     *                     }
+     *                 ]
+     *             }
+     *         ]
+     *         identity (Optional): {
+     *             @odata.type: String (Required)
+     *         }
+     *         parameters (Optional): {
+     *             synthesizeGeneratedKeyName: Boolean (Optional)
+     *              (Optional): {
+     *                 String: BinaryData (Required)
+     *             }
+     *         }
+     *     }
+     *     indexProjections (Optional): {
+     *         selectors (Required): [
+     *              (Required){
+     *                 targetIndexName: String (Required)
+     *                 parentKeyFieldName: String (Required)
+     *                 sourceContext: String (Required)
+     *                 mappings (Required): [
+     *                     (recursive schema, see above)
+     *                 ]
+     *             }
+     *         ]
+     *         parameters (Optional): {
+     *             projectionMode: String(skipIndexingParentDocuments/includeIndexingParentDocuments) (Optional)
+     *              (Optional): {
+     *                 String: BinaryData (Required)
+     *             }
+     *         }
+     *     }
+     *     @odata.etag: String (Optional)
+     *     encryptionKey (Optional): {
+     *         keyVaultKeyName: String (Required)
+     *         keyVaultKeyVersion: String (Optional)
+     *         keyVaultUri: String (Required)
+     *         accessCredentials (Optional): {
+     *             applicationId: String (Required)
+     *             applicationSecret: String (Optional)
+     *         }
+     *         identity (Optional): (recursive schema, see identity above)
+     *     }
+     * }
+     * }
+     * 
+ * + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     name: String (Required)
+     *     description: String (Optional)
+     *     skills (Required): [
+     *          (Required){
+     *             @odata.type: String (Required)
+     *             name: String (Optional)
+     *             description: String (Optional)
+     *             context: String (Optional)
+     *             inputs (Required): [
+     *                  (Required){
+     *                     name: String (Required)
+     *                     source: String (Optional)
+     *                     sourceContext: String (Optional)
+     *                     inputs (Optional): [
+     *                         (recursive schema, see above)
+     *                     ]
+     *                 }
+     *             ]
+     *             outputs (Required): [
+     *                  (Required){
+     *                     name: String (Required)
+     *                     targetName: String (Optional)
+     *                 }
+     *             ]
+     *         }
+     *     ]
+     *     cognitiveServices (Optional): {
+     *         @odata.type: String (Required)
+     *         description: String (Optional)
+     *     }
+     *     knowledgeStore (Optional): {
+     *         storageConnectionString: String (Required)
+     *         projections (Required): [
+     *              (Required){
+     *                 tables (Optional): [
+     *                      (Optional){
+     *                         referenceKeyName: String (Optional)
+     *                         generatedKeyName: String (Optional)
+     *                         source: String (Optional)
+     *                         sourceContext: String (Optional)
+     *                         inputs (Optional): [
+     *                             (recursive schema, see above)
+     *                         ]
+     *                         tableName: String (Required)
+     *                     }
+     *                 ]
+     *                 objects (Optional): [
+     *                      (Optional){
+     *                         referenceKeyName: String (Optional)
+     *                         generatedKeyName: String (Optional)
+     *                         source: String (Optional)
+     *                         sourceContext: String (Optional)
+     *                         inputs (Optional): [
+     *                             (recursive schema, see above)
+     *                         ]
+     *                         storageContainer: String (Required)
+     *                     }
+     *                 ]
+     *                 files (Optional): [
+     *                      (Optional){
+     *                         referenceKeyName: String (Optional)
+     *                         generatedKeyName: String (Optional)
+     *                         source: String (Optional)
+     *                         sourceContext: String (Optional)
+     *                         inputs (Optional): [
+     *                             (recursive schema, see above)
+     *                         ]
+     *                         storageContainer: String (Required)
+     *                     }
+     *                 ]
+     *             }
+     *         ]
+     *         identity (Optional): {
+     *             @odata.type: String (Required)
+     *         }
+     *         parameters (Optional): {
+     *             synthesizeGeneratedKeyName: Boolean (Optional)
+     *              (Optional): {
+     *                 String: BinaryData (Required)
+     *             }
+     *         }
+     *     }
+     *     indexProjections (Optional): {
+     *         selectors (Required): [
+     *              (Required){
+     *                 targetIndexName: String (Required)
+     *                 parentKeyFieldName: String (Required)
+     *                 sourceContext: String (Required)
+     *                 mappings (Required): [
+     *                     (recursive schema, see above)
+     *                 ]
+     *             }
+     *         ]
+     *         parameters (Optional): {
+     *             projectionMode: String(skipIndexingParentDocuments/includeIndexingParentDocuments) (Optional)
+     *              (Optional): {
+     *                 String: BinaryData (Required)
+     *             }
+     *         }
+     *     }
+     *     @odata.etag: String (Optional)
+     *     encryptionKey (Optional): {
+     *         keyVaultKeyName: String (Required)
+     *         keyVaultKeyVersion: String (Optional)
+     *         keyVaultUri: String (Required)
+     *         accessCredentials (Optional): {
+     *             applicationId: String (Required)
+     *             applicationSecret: String (Optional)
+     *         }
+     *         identity (Optional): (recursive schema, see identity above)
+     *     }
+     * }
+     * }
+     * 
+ * + * @param skillsetName The name of the skillset. + * @param skillset The skillset containing one or more skills to create or update in a search + * service. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return a list of skills along with {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono> createOrUpdateWithResponseAsync(String skillsetName, BinaryData skillset, + RequestOptions requestOptions) { + final String prefer = "return=representation"; + final String contentType = "application/json"; + final String accept = "application/json"; + return FluxUtil.withContext( + context -> service.createOrUpdate(this.client.getEndpoint(), this.client.getServiceVersion().getVersion(), + prefer, skillsetName, contentType, accept, skillset, requestOptions, context)); + } + + /** + * Creates a new skillset in a search service or updates the skillset if it + * already exists. + *

Query Parameters

+ * + * + * + * + * + *
Query Parameters
NameTypeRequiredDescription
ignoreResetRequirementsBooleanNoIgnores cache reset requirements.
disableCacheReprocessingChangeDetectionBooleanNoDisables cache reprocessing + * change detection.
+ * You can add these to a request with {@link RequestOptions#addQueryParam} + *

Header Parameters

+ * + * + * + * + * + *
Header Parameters
NameTypeRequiredDescription
If-MatchStringNoDefines the If-Match condition. The operation will be + * performed only if the ETag on the server matches this value.
If-None-MatchStringNoDefines the If-None-Match condition. The operation will + * be performed only if the ETag on the server does not match this value.
+ * You can add these to a request with {@link RequestOptions#addHeader} + *

Request Body Schema

+ * + *
+     * {@code
+     * {
+     *     name: String (Required)
+     *     description: String (Optional)
+     *     skills (Required): [
+     *          (Required){
+     *             @odata.type: String (Required)
+     *             name: String (Optional)
+     *             description: String (Optional)
+     *             context: String (Optional)
+     *             inputs (Required): [
+     *                  (Required){
+     *                     name: String (Required)
+     *                     source: String (Optional)
+     *                     sourceContext: String (Optional)
+     *                     inputs (Optional): [
+     *                         (recursive schema, see above)
+     *                     ]
+     *                 }
+     *             ]
+     *             outputs (Required): [
+     *                  (Required){
+     *                     name: String (Required)
+     *                     targetName: String (Optional)
+     *                 }
+     *             ]
+     *         }
+     *     ]
+     *     cognitiveServices (Optional): {
+     *         @odata.type: String (Required)
+     *         description: String (Optional)
+     *     }
+     *     knowledgeStore (Optional): {
+     *         storageConnectionString: String (Required)
+     *         projections (Required): [
+     *              (Required){
+     *                 tables (Optional): [
+     *                      (Optional){
+     *                         referenceKeyName: String (Optional)
+     *                         generatedKeyName: String (Optional)
+     *                         source: String (Optional)
+     *                         sourceContext: String (Optional)
+     *                         inputs (Optional): [
+     *                             (recursive schema, see above)
+     *                         ]
+     *                         tableName: String (Required)
+     *                     }
+     *                 ]
+     *                 objects (Optional): [
+     *                      (Optional){
+     *                         referenceKeyName: String (Optional)
+     *                         generatedKeyName: String (Optional)
+     *                         source: String (Optional)
+     *                         sourceContext: String (Optional)
+     *                         inputs (Optional): [
+     *                             (recursive schema, see above)
+     *                         ]
+     *                         storageContainer: String (Required)
+     *                     }
+     *                 ]
+     *                 files (Optional): [
+     *                      (Optional){
+     *                         referenceKeyName: String (Optional)
+     *                         generatedKeyName: String (Optional)
+     *                         source: String (Optional)
+     *                         sourceContext: String (Optional)
+     *                         inputs (Optional): [
+     *                             (recursive schema, see above)
+     *                         ]
+     *                         storageContainer: String (Required)
+     *                     }
+     *                 ]
+     *             }
+     *         ]
+     *         identity (Optional): {
+     *             @odata.type: String (Required)
+     *         }
+     *         parameters (Optional): {
+     *             synthesizeGeneratedKeyName: Boolean (Optional)
+     *              (Optional): {
+     *                 String: BinaryData (Required)
+     *             }
+     *         }
+     *     }
+     *     indexProjections (Optional): {
+     *         selectors (Required): [
+     *              (Required){
+     *                 targetIndexName: String (Required)
+     *                 parentKeyFieldName: String (Required)
+     *                 sourceContext: String (Required)
+     *                 mappings (Required): [
+     *                     (recursive schema, see above)
+     *                 ]
+     *             }
+     *         ]
+     *         parameters (Optional): {
+     *             projectionMode: String(skipIndexingParentDocuments/includeIndexingParentDocuments) (Optional)
+     *              (Optional): {
+     *                 String: BinaryData (Required)
+     *             }
+     *         }
+     *     }
+     *     @odata.etag: String (Optional)
+     *     encryptionKey (Optional): {
+     *         keyVaultKeyName: String (Required)
+     *         keyVaultKeyVersion: String (Optional)
+     *         keyVaultUri: String (Required)
+     *         accessCredentials (Optional): {
+     *             applicationId: String (Required)
+     *             applicationSecret: String (Optional)
+     *         }
+     *         identity (Optional): (recursive schema, see identity above)
+     *     }
+     * }
+     * }
+     * 
+ * + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     name: String (Required)
+     *     description: String (Optional)
+     *     skills (Required): [
+     *          (Required){
+     *             @odata.type: String (Required)
+     *             name: String (Optional)
+     *             description: String (Optional)
+     *             context: String (Optional)
+     *             inputs (Required): [
+     *                  (Required){
+     *                     name: String (Required)
+     *                     source: String (Optional)
+     *                     sourceContext: String (Optional)
+     *                     inputs (Optional): [
+     *                         (recursive schema, see above)
+     *                     ]
+     *                 }
+     *             ]
+     *             outputs (Required): [
+     *                  (Required){
+     *                     name: String (Required)
+     *                     targetName: String (Optional)
+     *                 }
+     *             ]
+     *         }
+     *     ]
+     *     cognitiveServices (Optional): {
+     *         @odata.type: String (Required)
+     *         description: String (Optional)
+     *     }
+     *     knowledgeStore (Optional): {
+     *         storageConnectionString: String (Required)
+     *         projections (Required): [
+     *              (Required){
+     *                 tables (Optional): [
+     *                      (Optional){
+     *                         referenceKeyName: String (Optional)
+     *                         generatedKeyName: String (Optional)
+     *                         source: String (Optional)
+     *                         sourceContext: String (Optional)
+     *                         inputs (Optional): [
+     *                             (recursive schema, see above)
+     *                         ]
+     *                         tableName: String (Required)
+     *                     }
+     *                 ]
+     *                 objects (Optional): [
+     *                      (Optional){
+     *                         referenceKeyName: String (Optional)
+     *                         generatedKeyName: String (Optional)
+     *                         source: String (Optional)
+     *                         sourceContext: String (Optional)
+     *                         inputs (Optional): [
+     *                             (recursive schema, see above)
+     *                         ]
+     *                         storageContainer: String (Required)
+     *                     }
+     *                 ]
+     *                 files (Optional): [
+     *                      (Optional){
+     *                         referenceKeyName: String (Optional)
+     *                         generatedKeyName: String (Optional)
+     *                         source: String (Optional)
+     *                         sourceContext: String (Optional)
+     *                         inputs (Optional): [
+     *                             (recursive schema, see above)
+     *                         ]
+     *                         storageContainer: String (Required)
+     *                     }
+     *                 ]
+     *             }
+     *         ]
+     *         identity (Optional): {
+     *             @odata.type: String (Required)
+     *         }
+     *         parameters (Optional): {
+     *             synthesizeGeneratedKeyName: Boolean (Optional)
+     *              (Optional): {
+     *                 String: BinaryData (Required)
+     *             }
+     *         }
+     *     }
+     *     indexProjections (Optional): {
+     *         selectors (Required): [
+     *              (Required){
+     *                 targetIndexName: String (Required)
+     *                 parentKeyFieldName: String (Required)
+     *                 sourceContext: String (Required)
+     *                 mappings (Required): [
+     *                     (recursive schema, see above)
+     *                 ]
+     *             }
+     *         ]
+     *         parameters (Optional): {
+     *             projectionMode: String(skipIndexingParentDocuments/includeIndexingParentDocuments) (Optional)
+     *              (Optional): {
+     *                 String: BinaryData (Required)
+     *             }
+     *         }
+     *     }
+     *     @odata.etag: String (Optional)
+     *     encryptionKey (Optional): {
+     *         keyVaultKeyName: String (Required)
+     *         keyVaultKeyVersion: String (Optional)
+     *         keyVaultUri: String (Required)
+     *         accessCredentials (Optional): {
+     *             applicationId: String (Required)
+     *             applicationSecret: String (Optional)
+     *         }
+     *         identity (Optional): (recursive schema, see identity above)
+     *     }
+     * }
+     * }
+     * 
+ * + * @param skillsetName The name of the skillset. + * @param skillset The skillset containing one or more skills to create or update in a search + * service. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return a list of skills along with {@link Response}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Response createOrUpdateWithResponse(String skillsetName, BinaryData skillset, + RequestOptions requestOptions) { + final String prefer = "return=representation"; + final String contentType = "application/json"; + final String accept = "application/json"; + return service.createOrUpdateSync(this.client.getEndpoint(), this.client.getServiceVersion().getVersion(), + prefer, skillsetName, contentType, accept, skillset, requestOptions, Context.NONE); + } + + /** + * Deletes a skillset in a search service. + *

Header Parameters

+ * + * + * + * + * + *
Header Parameters
NameTypeRequiredDescription
If-MatchStringNoDefines the If-Match condition. The operation will be + * performed only if the ETag on the server matches this value.
If-None-MatchStringNoDefines the If-None-Match condition. The operation will + * be performed only if the ETag on the server does not match this value.
+ * You can add these to a request with {@link RequestOptions#addHeader} + * + * @param skillsetName The name of the skillset. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return the {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono> deleteWithResponseAsync(String skillsetName, RequestOptions requestOptions) { + final String accept = "application/json"; + return FluxUtil.withContext(context -> service.delete(this.client.getEndpoint(), + this.client.getServiceVersion().getVersion(), skillsetName, accept, requestOptions, context)); + } + + /** + * Deletes a skillset in a search service. + *

Header Parameters

+ * + * + * + * + * + *
Header Parameters
NameTypeRequiredDescription
If-MatchStringNoDefines the If-Match condition. The operation will be + * performed only if the ETag on the server matches this value.
If-None-MatchStringNoDefines the If-None-Match condition. The operation will + * be performed only if the ETag on the server does not match this value.
+ * You can add these to a request with {@link RequestOptions#addHeader} + * + * @param skillsetName The name of the skillset. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return the {@link Response}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Response deleteWithResponse(String skillsetName, RequestOptions requestOptions) { + final String accept = "application/json"; + return service.deleteSync(this.client.getEndpoint(), this.client.getServiceVersion().getVersion(), skillsetName, + accept, requestOptions, Context.NONE); + } + + /** + * Retrieves a skillset in a search service. + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     name: String (Required)
+     *     description: String (Optional)
+     *     skills (Required): [
+     *          (Required){
+     *             @odata.type: String (Required)
+     *             name: String (Optional)
+     *             description: String (Optional)
+     *             context: String (Optional)
+     *             inputs (Required): [
+     *                  (Required){
+     *                     name: String (Required)
+     *                     source: String (Optional)
+     *                     sourceContext: String (Optional)
+     *                     inputs (Optional): [
+     *                         (recursive schema, see above)
+     *                     ]
+     *                 }
+     *             ]
+     *             outputs (Required): [
+     *                  (Required){
+     *                     name: String (Required)
+     *                     targetName: String (Optional)
+     *                 }
+     *             ]
+     *         }
+     *     ]
+     *     cognitiveServices (Optional): {
+     *         @odata.type: String (Required)
+     *         description: String (Optional)
+     *     }
+     *     knowledgeStore (Optional): {
+     *         storageConnectionString: String (Required)
+     *         projections (Required): [
+     *              (Required){
+     *                 tables (Optional): [
+     *                      (Optional){
+     *                         referenceKeyName: String (Optional)
+     *                         generatedKeyName: String (Optional)
+     *                         source: String (Optional)
+     *                         sourceContext: String (Optional)
+     *                         inputs (Optional): [
+     *                             (recursive schema, see above)
+     *                         ]
+     *                         tableName: String (Required)
+     *                     }
+     *                 ]
+     *                 objects (Optional): [
+     *                      (Optional){
+     *                         referenceKeyName: String (Optional)
+     *                         generatedKeyName: String (Optional)
+     *                         source: String (Optional)
+     *                         sourceContext: String (Optional)
+     *                         inputs (Optional): [
+     *                             (recursive schema, see above)
+     *                         ]
+     *                         storageContainer: String (Required)
+     *                     }
+     *                 ]
+     *                 files (Optional): [
+     *                      (Optional){
+     *                         referenceKeyName: String (Optional)
+     *                         generatedKeyName: String (Optional)
+     *                         source: String (Optional)
+     *                         sourceContext: String (Optional)
+     *                         inputs (Optional): [
+     *                             (recursive schema, see above)
+     *                         ]
+     *                         storageContainer: String (Required)
+     *                     }
+     *                 ]
+     *             }
+     *         ]
+     *         identity (Optional): {
+     *             @odata.type: String (Required)
+     *         }
+     *         parameters (Optional): {
+     *             synthesizeGeneratedKeyName: Boolean (Optional)
+     *              (Optional): {
+     *                 String: BinaryData (Required)
+     *             }
+     *         }
+     *     }
+     *     indexProjections (Optional): {
+     *         selectors (Required): [
+     *              (Required){
+     *                 targetIndexName: String (Required)
+     *                 parentKeyFieldName: String (Required)
+     *                 sourceContext: String (Required)
+     *                 mappings (Required): [
+     *                     (recursive schema, see above)
+     *                 ]
+     *             }
+     *         ]
+     *         parameters (Optional): {
+     *             projectionMode: String(skipIndexingParentDocuments/includeIndexingParentDocuments) (Optional)
+     *              (Optional): {
+     *                 String: BinaryData (Required)
+     *             }
+     *         }
+     *     }
+     *     @odata.etag: String (Optional)
+     *     encryptionKey (Optional): {
+     *         keyVaultKeyName: String (Required)
+     *         keyVaultKeyVersion: String (Optional)
+     *         keyVaultUri: String (Required)
+     *         accessCredentials (Optional): {
+     *             applicationId: String (Required)
+     *             applicationSecret: String (Optional)
+     *         }
+     *         identity (Optional): (recursive schema, see identity above)
+     *     }
+     * }
+     * }
+     * 
+ * + * @param skillsetName The name of the skillset. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return a list of skills along with {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono> getWithResponseAsync(String skillsetName, RequestOptions requestOptions) { + final String accept = "application/json"; + return FluxUtil.withContext(context -> service.get(this.client.getEndpoint(), + this.client.getServiceVersion().getVersion(), skillsetName, accept, requestOptions, context)); + } + + /** + * Retrieves a skillset in a search service. + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     name: String (Required)
+     *     description: String (Optional)
+     *     skills (Required): [
+     *          (Required){
+     *             @odata.type: String (Required)
+     *             name: String (Optional)
+     *             description: String (Optional)
+     *             context: String (Optional)
+     *             inputs (Required): [
+     *                  (Required){
+     *                     name: String (Required)
+     *                     source: String (Optional)
+     *                     sourceContext: String (Optional)
+     *                     inputs (Optional): [
+     *                         (recursive schema, see above)
+     *                     ]
+     *                 }
+     *             ]
+     *             outputs (Required): [
+     *                  (Required){
+     *                     name: String (Required)
+     *                     targetName: String (Optional)
+     *                 }
+     *             ]
+     *         }
+     *     ]
+     *     cognitiveServices (Optional): {
+     *         @odata.type: String (Required)
+     *         description: String (Optional)
+     *     }
+     *     knowledgeStore (Optional): {
+     *         storageConnectionString: String (Required)
+     *         projections (Required): [
+     *              (Required){
+     *                 tables (Optional): [
+     *                      (Optional){
+     *                         referenceKeyName: String (Optional)
+     *                         generatedKeyName: String (Optional)
+     *                         source: String (Optional)
+     *                         sourceContext: String (Optional)
+     *                         inputs (Optional): [
+     *                             (recursive schema, see above)
+     *                         ]
+     *                         tableName: String (Required)
+     *                     }
+     *                 ]
+     *                 objects (Optional): [
+     *                      (Optional){
+     *                         referenceKeyName: String (Optional)
+     *                         generatedKeyName: String (Optional)
+     *                         source: String (Optional)
+     *                         sourceContext: String (Optional)
+     *                         inputs (Optional): [
+     *                             (recursive schema, see above)
+     *                         ]
+     *                         storageContainer: String (Required)
+     *                     }
+     *                 ]
+     *                 files (Optional): [
+     *                      (Optional){
+     *                         referenceKeyName: String (Optional)
+     *                         generatedKeyName: String (Optional)
+     *                         source: String (Optional)
+     *                         sourceContext: String (Optional)
+     *                         inputs (Optional): [
+     *                             (recursive schema, see above)
+     *                         ]
+     *                         storageContainer: String (Required)
+     *                     }
+     *                 ]
+     *             }
+     *         ]
+     *         identity (Optional): {
+     *             @odata.type: String (Required)
+     *         }
+     *         parameters (Optional): {
+     *             synthesizeGeneratedKeyName: Boolean (Optional)
+     *              (Optional): {
+     *                 String: BinaryData (Required)
+     *             }
+     *         }
+     *     }
+     *     indexProjections (Optional): {
+     *         selectors (Required): [
+     *              (Required){
+     *                 targetIndexName: String (Required)
+     *                 parentKeyFieldName: String (Required)
+     *                 sourceContext: String (Required)
+     *                 mappings (Required): [
+     *                     (recursive schema, see above)
+     *                 ]
+     *             }
+     *         ]
+     *         parameters (Optional): {
+     *             projectionMode: String(skipIndexingParentDocuments/includeIndexingParentDocuments) (Optional)
+     *              (Optional): {
+     *                 String: BinaryData (Required)
+     *             }
+     *         }
+     *     }
+     *     @odata.etag: String (Optional)
+     *     encryptionKey (Optional): {
+     *         keyVaultKeyName: String (Required)
+     *         keyVaultKeyVersion: String (Optional)
+     *         keyVaultUri: String (Required)
+     *         accessCredentials (Optional): {
+     *             applicationId: String (Required)
+     *             applicationSecret: String (Optional)
+     *         }
+     *         identity (Optional): (recursive schema, see identity above)
+     *     }
+     * }
+     * }
+     * 
+ * + * @param skillsetName The name of the skillset. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return a list of skills along with {@link Response}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Response getWithResponse(String skillsetName, RequestOptions requestOptions) { + final String accept = "application/json"; + return service.getSync(this.client.getEndpoint(), this.client.getServiceVersion().getVersion(), skillsetName, + accept, requestOptions, Context.NONE); + } + + /** + * List all skillsets in a search service. + *

Query Parameters

+ * + * + * + * + *
Query Parameters
NameTypeRequiredDescription
$selectStringNoSelects 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.
+ * You can add these to a request with {@link RequestOptions#addQueryParam} + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     value (Required): [
+     *          (Required){
+     *             name: String (Required)
+     *             description: String (Optional)
+     *             skills (Required): [
+     *                  (Required){
+     *                     @odata.type: String (Required)
+     *                     name: String (Optional)
+     *                     description: String (Optional)
+     *                     context: String (Optional)
+     *                     inputs (Required): [
+     *                          (Required){
+     *                             name: String (Required)
+     *                             source: String (Optional)
+     *                             sourceContext: String (Optional)
+     *                             inputs (Optional): [
+     *                                 (recursive schema, see above)
+     *                             ]
+     *                         }
+     *                     ]
+     *                     outputs (Required): [
+     *                          (Required){
+     *                             name: String (Required)
+     *                             targetName: String (Optional)
+     *                         }
+     *                     ]
+     *                 }
+     *             ]
+     *             cognitiveServices (Optional): {
+     *                 @odata.type: String (Required)
+     *                 description: String (Optional)
+     *             }
+     *             knowledgeStore (Optional): {
+     *                 storageConnectionString: String (Required)
+     *                 projections (Required): [
+     *                      (Required){
+     *                         tables (Optional): [
+     *                              (Optional){
+     *                                 referenceKeyName: String (Optional)
+     *                                 generatedKeyName: String (Optional)
+     *                                 source: String (Optional)
+     *                                 sourceContext: String (Optional)
+     *                                 inputs (Optional): [
+     *                                     (recursive schema, see above)
+     *                                 ]
+     *                                 tableName: String (Required)
+     *                             }
+     *                         ]
+     *                         objects (Optional): [
+     *                              (Optional){
+     *                                 referenceKeyName: String (Optional)
+     *                                 generatedKeyName: String (Optional)
+     *                                 source: String (Optional)
+     *                                 sourceContext: String (Optional)
+     *                                 inputs (Optional): [
+     *                                     (recursive schema, see above)
+     *                                 ]
+     *                                 storageContainer: String (Required)
+     *                             }
+     *                         ]
+     *                         files (Optional): [
+     *                              (Optional){
+     *                                 referenceKeyName: String (Optional)
+     *                                 generatedKeyName: String (Optional)
+     *                                 source: String (Optional)
+     *                                 sourceContext: String (Optional)
+     *                                 inputs (Optional): [
+     *                                     (recursive schema, see above)
+     *                                 ]
+     *                                 storageContainer: String (Required)
+     *                             }
+     *                         ]
+     *                     }
+     *                 ]
+     *                 identity (Optional): {
+     *                     @odata.type: String (Required)
+     *                 }
+     *                 parameters (Optional): {
+     *                     synthesizeGeneratedKeyName: Boolean (Optional)
+     *                      (Optional): {
+     *                         String: BinaryData (Required)
+     *                     }
+     *                 }
+     *             }
+     *             indexProjections (Optional): {
+     *                 selectors (Required): [
+     *                      (Required){
+     *                         targetIndexName: String (Required)
+     *                         parentKeyFieldName: String (Required)
+     *                         sourceContext: String (Required)
+     *                         mappings (Required): [
+     *                             (recursive schema, see above)
+     *                         ]
+     *                     }
+     *                 ]
+     *                 parameters (Optional): {
+     *                     projectionMode: String(skipIndexingParentDocuments/includeIndexingParentDocuments) (Optional)
+     *                      (Optional): {
+     *                         String: BinaryData (Required)
+     *                     }
+     *                 }
+     *             }
+     *             @odata.etag: String (Optional)
+     *             encryptionKey (Optional): {
+     *                 keyVaultKeyName: String (Required)
+     *                 keyVaultKeyVersion: String (Optional)
+     *                 keyVaultUri: String (Required)
+     *                 accessCredentials (Optional): {
+     *                     applicationId: String (Required)
+     *                     applicationSecret: String (Optional)
+     *                 }
+     *                 identity (Optional): (recursive schema, see identity above)
+     *             }
+     *         }
+     *     ]
+     * }
+     * }
+     * 
+ * + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return response from a list skillset request along with {@link Response} on successful completion of + * {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono> listWithResponseAsync(RequestOptions requestOptions) { + final String accept = "application/json"; + return FluxUtil.withContext(context -> service.list(this.client.getEndpoint(), + this.client.getServiceVersion().getVersion(), accept, requestOptions, context)); + } + + /** + * List all skillsets in a search service. + *

Query Parameters

+ * + * + * + * + *
Query Parameters
NameTypeRequiredDescription
$selectStringNoSelects 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.
+ * You can add these to a request with {@link RequestOptions#addQueryParam} + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     value (Required): [
+     *          (Required){
+     *             name: String (Required)
+     *             description: String (Optional)
+     *             skills (Required): [
+     *                  (Required){
+     *                     @odata.type: String (Required)
+     *                     name: String (Optional)
+     *                     description: String (Optional)
+     *                     context: String (Optional)
+     *                     inputs (Required): [
+     *                          (Required){
+     *                             name: String (Required)
+     *                             source: String (Optional)
+     *                             sourceContext: String (Optional)
+     *                             inputs (Optional): [
+     *                                 (recursive schema, see above)
+     *                             ]
+     *                         }
+     *                     ]
+     *                     outputs (Required): [
+     *                          (Required){
+     *                             name: String (Required)
+     *                             targetName: String (Optional)
+     *                         }
+     *                     ]
+     *                 }
+     *             ]
+     *             cognitiveServices (Optional): {
+     *                 @odata.type: String (Required)
+     *                 description: String (Optional)
+     *             }
+     *             knowledgeStore (Optional): {
+     *                 storageConnectionString: String (Required)
+     *                 projections (Required): [
+     *                      (Required){
+     *                         tables (Optional): [
+     *                              (Optional){
+     *                                 referenceKeyName: String (Optional)
+     *                                 generatedKeyName: String (Optional)
+     *                                 source: String (Optional)
+     *                                 sourceContext: String (Optional)
+     *                                 inputs (Optional): [
+     *                                     (recursive schema, see above)
+     *                                 ]
+     *                                 tableName: String (Required)
+     *                             }
+     *                         ]
+     *                         objects (Optional): [
+     *                              (Optional){
+     *                                 referenceKeyName: String (Optional)
+     *                                 generatedKeyName: String (Optional)
+     *                                 source: String (Optional)
+     *                                 sourceContext: String (Optional)
+     *                                 inputs (Optional): [
+     *                                     (recursive schema, see above)
+     *                                 ]
+     *                                 storageContainer: String (Required)
+     *                             }
+     *                         ]
+     *                         files (Optional): [
+     *                              (Optional){
+     *                                 referenceKeyName: String (Optional)
+     *                                 generatedKeyName: String (Optional)
+     *                                 source: String (Optional)
+     *                                 sourceContext: String (Optional)
+     *                                 inputs (Optional): [
+     *                                     (recursive schema, see above)
+     *                                 ]
+     *                                 storageContainer: String (Required)
+     *                             }
+     *                         ]
+     *                     }
+     *                 ]
+     *                 identity (Optional): {
+     *                     @odata.type: String (Required)
+     *                 }
+     *                 parameters (Optional): {
+     *                     synthesizeGeneratedKeyName: Boolean (Optional)
+     *                      (Optional): {
+     *                         String: BinaryData (Required)
+     *                     }
+     *                 }
+     *             }
+     *             indexProjections (Optional): {
+     *                 selectors (Required): [
+     *                      (Required){
+     *                         targetIndexName: String (Required)
+     *                         parentKeyFieldName: String (Required)
+     *                         sourceContext: String (Required)
+     *                         mappings (Required): [
+     *                             (recursive schema, see above)
+     *                         ]
+     *                     }
+     *                 ]
+     *                 parameters (Optional): {
+     *                     projectionMode: String(skipIndexingParentDocuments/includeIndexingParentDocuments) (Optional)
+     *                      (Optional): {
+     *                         String: BinaryData (Required)
+     *                     }
+     *                 }
+     *             }
+     *             @odata.etag: String (Optional)
+     *             encryptionKey (Optional): {
+     *                 keyVaultKeyName: String (Required)
+     *                 keyVaultKeyVersion: String (Optional)
+     *                 keyVaultUri: String (Required)
+     *                 accessCredentials (Optional): {
+     *                     applicationId: String (Required)
+     *                     applicationSecret: String (Optional)
+     *                 }
+     *                 identity (Optional): (recursive schema, see identity above)
+     *             }
+     *         }
+     *     ]
+     * }
+     * }
+     * 
+ * + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return response from a list skillset request along with {@link Response}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Response listWithResponse(RequestOptions requestOptions) { + final String accept = "application/json"; + return service.listSync(this.client.getEndpoint(), this.client.getServiceVersion().getVersion(), accept, + requestOptions, Context.NONE); + } + + /** + * Creates a new skillset in a search service. + *

Request Body Schema

+ * + *
+     * {@code
+     * {
+     *     name: String (Required)
+     *     description: String (Optional)
+     *     skills (Required): [
+     *          (Required){
+     *             @odata.type: String (Required)
+     *             name: String (Optional)
+     *             description: String (Optional)
+     *             context: String (Optional)
+     *             inputs (Required): [
+     *                  (Required){
+     *                     name: String (Required)
+     *                     source: String (Optional)
+     *                     sourceContext: String (Optional)
+     *                     inputs (Optional): [
+     *                         (recursive schema, see above)
+     *                     ]
+     *                 }
+     *             ]
+     *             outputs (Required): [
+     *                  (Required){
+     *                     name: String (Required)
+     *                     targetName: String (Optional)
+     *                 }
+     *             ]
+     *         }
+     *     ]
+     *     cognitiveServices (Optional): {
+     *         @odata.type: String (Required)
+     *         description: String (Optional)
+     *     }
+     *     knowledgeStore (Optional): {
+     *         storageConnectionString: String (Required)
+     *         projections (Required): [
+     *              (Required){
+     *                 tables (Optional): [
+     *                      (Optional){
+     *                         referenceKeyName: String (Optional)
+     *                         generatedKeyName: String (Optional)
+     *                         source: String (Optional)
+     *                         sourceContext: String (Optional)
+     *                         inputs (Optional): [
+     *                             (recursive schema, see above)
+     *                         ]
+     *                         tableName: String (Required)
+     *                     }
+     *                 ]
+     *                 objects (Optional): [
+     *                      (Optional){
+     *                         referenceKeyName: String (Optional)
+     *                         generatedKeyName: String (Optional)
+     *                         source: String (Optional)
+     *                         sourceContext: String (Optional)
+     *                         inputs (Optional): [
+     *                             (recursive schema, see above)
+     *                         ]
+     *                         storageContainer: String (Required)
+     *                     }
+     *                 ]
+     *                 files (Optional): [
+     *                      (Optional){
+     *                         referenceKeyName: String (Optional)
+     *                         generatedKeyName: String (Optional)
+     *                         source: String (Optional)
+     *                         sourceContext: String (Optional)
+     *                         inputs (Optional): [
+     *                             (recursive schema, see above)
+     *                         ]
+     *                         storageContainer: String (Required)
+     *                     }
+     *                 ]
+     *             }
+     *         ]
+     *         identity (Optional): {
+     *             @odata.type: String (Required)
+     *         }
+     *         parameters (Optional): {
+     *             synthesizeGeneratedKeyName: Boolean (Optional)
+     *              (Optional): {
+     *                 String: BinaryData (Required)
+     *             }
+     *         }
+     *     }
+     *     indexProjections (Optional): {
+     *         selectors (Required): [
+     *              (Required){
+     *                 targetIndexName: String (Required)
+     *                 parentKeyFieldName: String (Required)
+     *                 sourceContext: String (Required)
+     *                 mappings (Required): [
+     *                     (recursive schema, see above)
+     *                 ]
+     *             }
+     *         ]
+     *         parameters (Optional): {
+     *             projectionMode: String(skipIndexingParentDocuments/includeIndexingParentDocuments) (Optional)
+     *              (Optional): {
+     *                 String: BinaryData (Required)
+     *             }
+     *         }
+     *     }
+     *     @odata.etag: String (Optional)
+     *     encryptionKey (Optional): {
+     *         keyVaultKeyName: String (Required)
+     *         keyVaultKeyVersion: String (Optional)
+     *         keyVaultUri: String (Required)
+     *         accessCredentials (Optional): {
+     *             applicationId: String (Required)
+     *             applicationSecret: String (Optional)
+     *         }
+     *         identity (Optional): (recursive schema, see identity above)
+     *     }
+     * }
+     * }
+     * 
+ * + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     name: String (Required)
+     *     description: String (Optional)
+     *     skills (Required): [
+     *          (Required){
+     *             @odata.type: String (Required)
+     *             name: String (Optional)
+     *             description: String (Optional)
+     *             context: String (Optional)
+     *             inputs (Required): [
+     *                  (Required){
+     *                     name: String (Required)
+     *                     source: String (Optional)
+     *                     sourceContext: String (Optional)
+     *                     inputs (Optional): [
+     *                         (recursive schema, see above)
+     *                     ]
+     *                 }
+     *             ]
+     *             outputs (Required): [
+     *                  (Required){
+     *                     name: String (Required)
+     *                     targetName: String (Optional)
+     *                 }
+     *             ]
+     *         }
+     *     ]
+     *     cognitiveServices (Optional): {
+     *         @odata.type: String (Required)
+     *         description: String (Optional)
+     *     }
+     *     knowledgeStore (Optional): {
+     *         storageConnectionString: String (Required)
+     *         projections (Required): [
+     *              (Required){
+     *                 tables (Optional): [
+     *                      (Optional){
+     *                         referenceKeyName: String (Optional)
+     *                         generatedKeyName: String (Optional)
+     *                         source: String (Optional)
+     *                         sourceContext: String (Optional)
+     *                         inputs (Optional): [
+     *                             (recursive schema, see above)
+     *                         ]
+     *                         tableName: String (Required)
+     *                     }
+     *                 ]
+     *                 objects (Optional): [
+     *                      (Optional){
+     *                         referenceKeyName: String (Optional)
+     *                         generatedKeyName: String (Optional)
+     *                         source: String (Optional)
+     *                         sourceContext: String (Optional)
+     *                         inputs (Optional): [
+     *                             (recursive schema, see above)
+     *                         ]
+     *                         storageContainer: String (Required)
+     *                     }
+     *                 ]
+     *                 files (Optional): [
+     *                      (Optional){
+     *                         referenceKeyName: String (Optional)
+     *                         generatedKeyName: String (Optional)
+     *                         source: String (Optional)
+     *                         sourceContext: String (Optional)
+     *                         inputs (Optional): [
+     *                             (recursive schema, see above)
+     *                         ]
+     *                         storageContainer: String (Required)
+     *                     }
+     *                 ]
+     *             }
+     *         ]
+     *         identity (Optional): {
+     *             @odata.type: String (Required)
+     *         }
+     *         parameters (Optional): {
+     *             synthesizeGeneratedKeyName: Boolean (Optional)
+     *              (Optional): {
+     *                 String: BinaryData (Required)
+     *             }
+     *         }
+     *     }
+     *     indexProjections (Optional): {
+     *         selectors (Required): [
+     *              (Required){
+     *                 targetIndexName: String (Required)
+     *                 parentKeyFieldName: String (Required)
+     *                 sourceContext: String (Required)
+     *                 mappings (Required): [
+     *                     (recursive schema, see above)
+     *                 ]
+     *             }
+     *         ]
+     *         parameters (Optional): {
+     *             projectionMode: String(skipIndexingParentDocuments/includeIndexingParentDocuments) (Optional)
+     *              (Optional): {
+     *                 String: BinaryData (Required)
+     *             }
+     *         }
+     *     }
+     *     @odata.etag: String (Optional)
+     *     encryptionKey (Optional): {
+     *         keyVaultKeyName: String (Required)
+     *         keyVaultKeyVersion: String (Optional)
+     *         keyVaultUri: String (Required)
+     *         accessCredentials (Optional): {
+     *             applicationId: String (Required)
+     *             applicationSecret: String (Optional)
+     *         }
+     *         identity (Optional): (recursive schema, see identity above)
+     *     }
+     * }
+     * }
+     * 
+ * + * @param skillset The skillset containing one or more skills to create in a search service. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return a list of skills along with {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono> createWithResponseAsync(BinaryData skillset, RequestOptions requestOptions) { + final String contentType = "application/json"; + final String accept = "application/json"; + return FluxUtil.withContext(context -> service.create(this.client.getEndpoint(), + this.client.getServiceVersion().getVersion(), contentType, accept, skillset, requestOptions, context)); + } + + /** + * Creates a new skillset in a search service. + *

Request Body Schema

+ * + *
+     * {@code
+     * {
+     *     name: String (Required)
+     *     description: String (Optional)
+     *     skills (Required): [
+     *          (Required){
+     *             @odata.type: String (Required)
+     *             name: String (Optional)
+     *             description: String (Optional)
+     *             context: String (Optional)
+     *             inputs (Required): [
+     *                  (Required){
+     *                     name: String (Required)
+     *                     source: String (Optional)
+     *                     sourceContext: String (Optional)
+     *                     inputs (Optional): [
+     *                         (recursive schema, see above)
+     *                     ]
+     *                 }
+     *             ]
+     *             outputs (Required): [
+     *                  (Required){
+     *                     name: String (Required)
+     *                     targetName: String (Optional)
+     *                 }
+     *             ]
+     *         }
+     *     ]
+     *     cognitiveServices (Optional): {
+     *         @odata.type: String (Required)
+     *         description: String (Optional)
+     *     }
+     *     knowledgeStore (Optional): {
+     *         storageConnectionString: String (Required)
+     *         projections (Required): [
+     *              (Required){
+     *                 tables (Optional): [
+     *                      (Optional){
+     *                         referenceKeyName: String (Optional)
+     *                         generatedKeyName: String (Optional)
+     *                         source: String (Optional)
+     *                         sourceContext: String (Optional)
+     *                         inputs (Optional): [
+     *                             (recursive schema, see above)
+     *                         ]
+     *                         tableName: String (Required)
+     *                     }
+     *                 ]
+     *                 objects (Optional): [
+     *                      (Optional){
+     *                         referenceKeyName: String (Optional)
+     *                         generatedKeyName: String (Optional)
+     *                         source: String (Optional)
+     *                         sourceContext: String (Optional)
+     *                         inputs (Optional): [
+     *                             (recursive schema, see above)
+     *                         ]
+     *                         storageContainer: String (Required)
+     *                     }
+     *                 ]
+     *                 files (Optional): [
+     *                      (Optional){
+     *                         referenceKeyName: String (Optional)
+     *                         generatedKeyName: String (Optional)
+     *                         source: String (Optional)
+     *                         sourceContext: String (Optional)
+     *                         inputs (Optional): [
+     *                             (recursive schema, see above)
+     *                         ]
+     *                         storageContainer: String (Required)
+     *                     }
+     *                 ]
+     *             }
+     *         ]
+     *         identity (Optional): {
+     *             @odata.type: String (Required)
+     *         }
+     *         parameters (Optional): {
+     *             synthesizeGeneratedKeyName: Boolean (Optional)
+     *              (Optional): {
+     *                 String: BinaryData (Required)
+     *             }
+     *         }
+     *     }
+     *     indexProjections (Optional): {
+     *         selectors (Required): [
+     *              (Required){
+     *                 targetIndexName: String (Required)
+     *                 parentKeyFieldName: String (Required)
+     *                 sourceContext: String (Required)
+     *                 mappings (Required): [
+     *                     (recursive schema, see above)
+     *                 ]
+     *             }
+     *         ]
+     *         parameters (Optional): {
+     *             projectionMode: String(skipIndexingParentDocuments/includeIndexingParentDocuments) (Optional)
+     *              (Optional): {
+     *                 String: BinaryData (Required)
+     *             }
+     *         }
+     *     }
+     *     @odata.etag: String (Optional)
+     *     encryptionKey (Optional): {
+     *         keyVaultKeyName: String (Required)
+     *         keyVaultKeyVersion: String (Optional)
+     *         keyVaultUri: String (Required)
+     *         accessCredentials (Optional): {
+     *             applicationId: String (Required)
+     *             applicationSecret: String (Optional)
+     *         }
+     *         identity (Optional): (recursive schema, see identity above)
+     *     }
+     * }
+     * }
+     * 
+ * + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     name: String (Required)
+     *     description: String (Optional)
+     *     skills (Required): [
+     *          (Required){
+     *             @odata.type: String (Required)
+     *             name: String (Optional)
+     *             description: String (Optional)
+     *             context: String (Optional)
+     *             inputs (Required): [
+     *                  (Required){
+     *                     name: String (Required)
+     *                     source: String (Optional)
+     *                     sourceContext: String (Optional)
+     *                     inputs (Optional): [
+     *                         (recursive schema, see above)
+     *                     ]
+     *                 }
+     *             ]
+     *             outputs (Required): [
+     *                  (Required){
+     *                     name: String (Required)
+     *                     targetName: String (Optional)
+     *                 }
+     *             ]
+     *         }
+     *     ]
+     *     cognitiveServices (Optional): {
+     *         @odata.type: String (Required)
+     *         description: String (Optional)
+     *     }
+     *     knowledgeStore (Optional): {
+     *         storageConnectionString: String (Required)
+     *         projections (Required): [
+     *              (Required){
+     *                 tables (Optional): [
+     *                      (Optional){
+     *                         referenceKeyName: String (Optional)
+     *                         generatedKeyName: String (Optional)
+     *                         source: String (Optional)
+     *                         sourceContext: String (Optional)
+     *                         inputs (Optional): [
+     *                             (recursive schema, see above)
+     *                         ]
+     *                         tableName: String (Required)
+     *                     }
+     *                 ]
+     *                 objects (Optional): [
+     *                      (Optional){
+     *                         referenceKeyName: String (Optional)
+     *                         generatedKeyName: String (Optional)
+     *                         source: String (Optional)
+     *                         sourceContext: String (Optional)
+     *                         inputs (Optional): [
+     *                             (recursive schema, see above)
+     *                         ]
+     *                         storageContainer: String (Required)
+     *                     }
+     *                 ]
+     *                 files (Optional): [
+     *                      (Optional){
+     *                         referenceKeyName: String (Optional)
+     *                         generatedKeyName: String (Optional)
+     *                         source: String (Optional)
+     *                         sourceContext: String (Optional)
+     *                         inputs (Optional): [
+     *                             (recursive schema, see above)
+     *                         ]
+     *                         storageContainer: String (Required)
+     *                     }
+     *                 ]
+     *             }
+     *         ]
+     *         identity (Optional): {
+     *             @odata.type: String (Required)
+     *         }
+     *         parameters (Optional): {
+     *             synthesizeGeneratedKeyName: Boolean (Optional)
+     *              (Optional): {
+     *                 String: BinaryData (Required)
+     *             }
+     *         }
+     *     }
+     *     indexProjections (Optional): {
+     *         selectors (Required): [
+     *              (Required){
+     *                 targetIndexName: String (Required)
+     *                 parentKeyFieldName: String (Required)
+     *                 sourceContext: String (Required)
+     *                 mappings (Required): [
+     *                     (recursive schema, see above)
+     *                 ]
+     *             }
+     *         ]
+     *         parameters (Optional): {
+     *             projectionMode: String(skipIndexingParentDocuments/includeIndexingParentDocuments) (Optional)
+     *              (Optional): {
+     *                 String: BinaryData (Required)
+     *             }
+     *         }
+     *     }
+     *     @odata.etag: String (Optional)
+     *     encryptionKey (Optional): {
+     *         keyVaultKeyName: String (Required)
+     *         keyVaultKeyVersion: String (Optional)
+     *         keyVaultUri: String (Required)
+     *         accessCredentials (Optional): {
+     *             applicationId: String (Required)
+     *             applicationSecret: String (Optional)
+     *         }
+     *         identity (Optional): (recursive schema, see identity above)
+     *     }
+     * }
+     * }
+     * 
+ * + * @param skillset The skillset containing one or more skills to create in a search service. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return a list of skills along with {@link Response}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Response createWithResponse(BinaryData skillset, RequestOptions requestOptions) { + final String contentType = "application/json"; + final String accept = "application/json"; + return service.createSync(this.client.getEndpoint(), this.client.getServiceVersion().getVersion(), contentType, + accept, skillset, requestOptions, Context.NONE); + } + + /** + * Reset an existing skillset in a search service. + *

Request Body Schema

+ * + *
+     * {@code
+     * {
+     *     skillNames (Optional): [
+     *         String (Optional)
+     *     ]
+     * }
+     * }
+     * 
+ * + * @param skillsetName The name of the skillset. + * @param skillNames The names of the skills to reset. If not specified, all skills in the skillset + * will be reset. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return the {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono> resetSkillsWithResponseAsync(String skillsetName, BinaryData skillNames, + RequestOptions requestOptions) { + final String contentType = "application/json"; + final String accept = "application/json"; + return FluxUtil.withContext( + context -> service.resetSkills(this.client.getEndpoint(), this.client.getServiceVersion().getVersion(), + skillsetName, contentType, accept, skillNames, requestOptions, context)); + } + + /** + * Reset an existing skillset in a search service. + *

Request Body Schema

+ * + *
+     * {@code
+     * {
+     *     skillNames (Optional): [
+     *         String (Optional)
+     *     ]
+     * }
+     * }
+     * 
+ * + * @param skillsetName The name of the skillset. + * @param skillNames The names of the skills to reset. If not specified, all skills in the skillset + * will be reset. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return the {@link Response}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Response resetSkillsWithResponse(String skillsetName, BinaryData skillNames, + RequestOptions requestOptions) { + final String contentType = "application/json"; + final String accept = "application/json"; + return service.resetSkillsSync(this.client.getEndpoint(), this.client.getServiceVersion().getVersion(), + skillsetName, contentType, accept, skillNames, requestOptions, Context.NONE); + } +} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/implementation/SynonymMapsImpl.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/implementation/SynonymMapsImpl.java new file mode 100644 index 000000000000..582a2d2efaf1 --- /dev/null +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/implementation/SynonymMapsImpl.java @@ -0,0 +1,726 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.search.documents.implementation; + +import com.azure.core.annotation.BodyParam; +import com.azure.core.annotation.Delete; +import com.azure.core.annotation.ExpectedResponses; +import com.azure.core.annotation.Get; +import com.azure.core.annotation.HeaderParam; +import com.azure.core.annotation.Host; +import com.azure.core.annotation.HostParam; +import com.azure.core.annotation.PathParam; +import com.azure.core.annotation.Post; +import com.azure.core.annotation.Put; +import com.azure.core.annotation.QueryParam; +import com.azure.core.annotation.ReturnType; +import com.azure.core.annotation.ServiceInterface; +import com.azure.core.annotation.ServiceMethod; +import com.azure.core.annotation.UnexpectedResponseExceptionType; +import com.azure.core.exception.ClientAuthenticationException; +import com.azure.core.exception.HttpResponseException; +import com.azure.core.exception.ResourceModifiedException; +import com.azure.core.exception.ResourceNotFoundException; +import com.azure.core.http.rest.RequestOptions; +import com.azure.core.http.rest.Response; +import com.azure.core.http.rest.RestProxy; +import com.azure.core.util.BinaryData; +import com.azure.core.util.Context; +import com.azure.core.util.FluxUtil; +import com.azure.search.documents.SearchServiceVersion; +import reactor.core.publisher.Mono; + +/** + * An instance of this class provides access to all the operations defined in SynonymMaps. + */ +public final class SynonymMapsImpl { + /** + * The proxy service used to perform REST calls. + */ + private final SynonymMapsService service; + + /** + * The service client containing this operation class. + */ + private final SearchClientImpl client; + + /** + * Initializes an instance of SynonymMapsImpl. + * + * @param client the instance of the service client containing this operation class. + */ + SynonymMapsImpl(SearchClientImpl client) { + this.service + = RestProxy.create(SynonymMapsService.class, client.getHttpPipeline(), client.getSerializerAdapter()); + this.client = client; + } + + /** + * Gets Service version. + * + * @return the serviceVersion value. + */ + public SearchServiceVersion getServiceVersion() { + return client.getServiceVersion(); + } + + /** + * The interface defining all the services for SearchClientSynonymMaps to be used by the proxy service to perform + * REST calls. + */ + @Host("{endpoint}") + @ServiceInterface(name = "SearchClientSynonymM") + public interface SynonymMapsService { + @Put("/synonymmaps('{synonymMapName}')") + @ExpectedResponses({ 200, 201 }) + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Mono> createOrUpdate(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @HeaderParam("Prefer") String prefer, + @PathParam("synonymMapName") String synonymMapName, @HeaderParam("Content-Type") String contentType, + @HeaderParam("Accept") String accept, @BodyParam("application/json") BinaryData synonymMap, + RequestOptions requestOptions, Context context); + + @Put("/synonymmaps('{synonymMapName}')") + @ExpectedResponses({ 200, 201 }) + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Response createOrUpdateSync(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @HeaderParam("Prefer") String prefer, + @PathParam("synonymMapName") String synonymMapName, @HeaderParam("Content-Type") String contentType, + @HeaderParam("Accept") String accept, @BodyParam("application/json") BinaryData synonymMap, + RequestOptions requestOptions, Context context); + + @Delete("/synonymmaps('{synonymMapName}')") + @ExpectedResponses({ 204, 404 }) + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Mono> delete(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @PathParam("synonymMapName") String synonymMapName, + @HeaderParam("Accept") String accept, RequestOptions requestOptions, Context context); + + @Delete("/synonymmaps('{synonymMapName}')") + @ExpectedResponses({ 204, 404 }) + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Response deleteSync(@HostParam("endpoint") String endpoint, @QueryParam("api-version") String apiVersion, + @PathParam("synonymMapName") String synonymMapName, @HeaderParam("Accept") String accept, + RequestOptions requestOptions, Context context); + + @Get("/synonymmaps('{synonymMapName}')") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Mono> get(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @PathParam("synonymMapName") String synonymMapName, + @HeaderParam("Accept") String accept, RequestOptions requestOptions, Context context); + + @Get("/synonymmaps('{synonymMapName}')") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Response getSync(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @PathParam("synonymMapName") String synonymMapName, + @HeaderParam("Accept") String accept, RequestOptions requestOptions, Context context); + + @Get("/synonymmaps") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Mono> list(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, + RequestOptions requestOptions, Context context); + + @Get("/synonymmaps") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Response listSync(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, + RequestOptions requestOptions, Context context); + + @Post("/synonymmaps") + @ExpectedResponses({ 201 }) + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Mono> create(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @HeaderParam("Content-Type") String contentType, + @HeaderParam("Accept") String accept, @BodyParam("application/json") BinaryData synonymMap, + RequestOptions requestOptions, Context context); + + @Post("/synonymmaps") + @ExpectedResponses({ 201 }) + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Response createSync(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @HeaderParam("Content-Type") String contentType, + @HeaderParam("Accept") String accept, @BodyParam("application/json") BinaryData synonymMap, + RequestOptions requestOptions, Context context); + } + + /** + * Creates a new synonym map or updates a synonym map if it already exists. + *

Header Parameters

+ * + * + * + * + * + *
Header Parameters
NameTypeRequiredDescription
If-MatchStringNoDefines the If-Match condition. The operation will be + * performed only if the ETag on the server matches this value.
If-None-MatchStringNoDefines the If-None-Match condition. The operation will + * be performed only if the ETag on the server does not match this value.
+ * You can add these to a request with {@link RequestOptions#addHeader} + *

Request Body Schema

+ * + *
+     * {@code
+     * {
+     *     name: String (Required)
+     *     format: String (Required)
+     *     synonyms: String (Required)
+     *     encryptionKey (Optional): {
+     *         keyVaultKeyName: String (Required)
+     *         keyVaultKeyVersion: String (Optional)
+     *         keyVaultUri: String (Required)
+     *         accessCredentials (Optional): {
+     *             applicationId: String (Required)
+     *             applicationSecret: String (Optional)
+     *         }
+     *         identity (Optional): {
+     *             @odata.type: String (Required)
+     *         }
+     *     }
+     *     @odata.etag: String (Optional)
+     * }
+     * }
+     * 
+ * + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     name: String (Required)
+     *     format: String (Required)
+     *     synonyms: String (Required)
+     *     encryptionKey (Optional): {
+     *         keyVaultKeyName: String (Required)
+     *         keyVaultKeyVersion: String (Optional)
+     *         keyVaultUri: String (Required)
+     *         accessCredentials (Optional): {
+     *             applicationId: String (Required)
+     *             applicationSecret: String (Optional)
+     *         }
+     *         identity (Optional): {
+     *             @odata.type: String (Required)
+     *         }
+     *     }
+     *     @odata.etag: String (Optional)
+     * }
+     * }
+     * 
+ * + * @param synonymMapName The name of the synonym map. + * @param synonymMap The definition of the synonym map to create or update. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return represents a synonym map definition along with {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono> createOrUpdateWithResponseAsync(String synonymMapName, BinaryData synonymMap, + RequestOptions requestOptions) { + final String prefer = "return=representation"; + final String contentType = "application/json"; + final String accept = "application/json"; + return FluxUtil.withContext( + context -> service.createOrUpdate(this.client.getEndpoint(), this.client.getServiceVersion().getVersion(), + prefer, synonymMapName, contentType, accept, synonymMap, requestOptions, context)); + } + + /** + * Creates a new synonym map or updates a synonym map if it already exists. + *

Header Parameters

+ * + * + * + * + * + *
Header Parameters
NameTypeRequiredDescription
If-MatchStringNoDefines the If-Match condition. The operation will be + * performed only if the ETag on the server matches this value.
If-None-MatchStringNoDefines the If-None-Match condition. The operation will + * be performed only if the ETag on the server does not match this value.
+ * You can add these to a request with {@link RequestOptions#addHeader} + *

Request Body Schema

+ * + *
+     * {@code
+     * {
+     *     name: String (Required)
+     *     format: String (Required)
+     *     synonyms: String (Required)
+     *     encryptionKey (Optional): {
+     *         keyVaultKeyName: String (Required)
+     *         keyVaultKeyVersion: String (Optional)
+     *         keyVaultUri: String (Required)
+     *         accessCredentials (Optional): {
+     *             applicationId: String (Required)
+     *             applicationSecret: String (Optional)
+     *         }
+     *         identity (Optional): {
+     *             @odata.type: String (Required)
+     *         }
+     *     }
+     *     @odata.etag: String (Optional)
+     * }
+     * }
+     * 
+ * + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     name: String (Required)
+     *     format: String (Required)
+     *     synonyms: String (Required)
+     *     encryptionKey (Optional): {
+     *         keyVaultKeyName: String (Required)
+     *         keyVaultKeyVersion: String (Optional)
+     *         keyVaultUri: String (Required)
+     *         accessCredentials (Optional): {
+     *             applicationId: String (Required)
+     *             applicationSecret: String (Optional)
+     *         }
+     *         identity (Optional): {
+     *             @odata.type: String (Required)
+     *         }
+     *     }
+     *     @odata.etag: String (Optional)
+     * }
+     * }
+     * 
+ * + * @param synonymMapName The name of the synonym map. + * @param synonymMap The definition of the synonym map to create or update. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return represents a synonym map definition along with {@link Response}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Response createOrUpdateWithResponse(String synonymMapName, BinaryData synonymMap, + RequestOptions requestOptions) { + final String prefer = "return=representation"; + final String contentType = "application/json"; + final String accept = "application/json"; + return service.createOrUpdateSync(this.client.getEndpoint(), this.client.getServiceVersion().getVersion(), + prefer, synonymMapName, contentType, accept, synonymMap, requestOptions, Context.NONE); + } + + /** + * Deletes a synonym map. + *

Header Parameters

+ * + * + * + * + * + *
Header Parameters
NameTypeRequiredDescription
If-MatchStringNoDefines the If-Match condition. The operation will be + * performed only if the ETag on the server matches this value.
If-None-MatchStringNoDefines the If-None-Match condition. The operation will + * be performed only if the ETag on the server does not match this value.
+ * You can add these to a request with {@link RequestOptions#addHeader} + * + * @param synonymMapName The name of the synonym map. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return the {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono> deleteWithResponseAsync(String synonymMapName, RequestOptions requestOptions) { + final String accept = "application/json"; + return FluxUtil.withContext(context -> service.delete(this.client.getEndpoint(), + this.client.getServiceVersion().getVersion(), synonymMapName, accept, requestOptions, context)); + } + + /** + * Deletes a synonym map. + *

Header Parameters

+ * + * + * + * + * + *
Header Parameters
NameTypeRequiredDescription
If-MatchStringNoDefines the If-Match condition. The operation will be + * performed only if the ETag on the server matches this value.
If-None-MatchStringNoDefines the If-None-Match condition. The operation will + * be performed only if the ETag on the server does not match this value.
+ * You can add these to a request with {@link RequestOptions#addHeader} + * + * @param synonymMapName The name of the synonym map. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return the {@link Response}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Response deleteWithResponse(String synonymMapName, RequestOptions requestOptions) { + final String accept = "application/json"; + return service.deleteSync(this.client.getEndpoint(), this.client.getServiceVersion().getVersion(), + synonymMapName, accept, requestOptions, Context.NONE); + } + + /** + * Retrieves a synonym map definition. + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     name: String (Required)
+     *     format: String (Required)
+     *     synonyms: String (Required)
+     *     encryptionKey (Optional): {
+     *         keyVaultKeyName: String (Required)
+     *         keyVaultKeyVersion: String (Optional)
+     *         keyVaultUri: String (Required)
+     *         accessCredentials (Optional): {
+     *             applicationId: String (Required)
+     *             applicationSecret: String (Optional)
+     *         }
+     *         identity (Optional): {
+     *             @odata.type: String (Required)
+     *         }
+     *     }
+     *     @odata.etag: String (Optional)
+     * }
+     * }
+     * 
+ * + * @param synonymMapName The name of the synonym map. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return represents a synonym map definition along with {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono> getWithResponseAsync(String synonymMapName, RequestOptions requestOptions) { + final String accept = "application/json"; + return FluxUtil.withContext(context -> service.get(this.client.getEndpoint(), + this.client.getServiceVersion().getVersion(), synonymMapName, accept, requestOptions, context)); + } + + /** + * Retrieves a synonym map definition. + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     name: String (Required)
+     *     format: String (Required)
+     *     synonyms: String (Required)
+     *     encryptionKey (Optional): {
+     *         keyVaultKeyName: String (Required)
+     *         keyVaultKeyVersion: String (Optional)
+     *         keyVaultUri: String (Required)
+     *         accessCredentials (Optional): {
+     *             applicationId: String (Required)
+     *             applicationSecret: String (Optional)
+     *         }
+     *         identity (Optional): {
+     *             @odata.type: String (Required)
+     *         }
+     *     }
+     *     @odata.etag: String (Optional)
+     * }
+     * }
+     * 
+ * + * @param synonymMapName The name of the synonym map. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return represents a synonym map definition along with {@link Response}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Response getWithResponse(String synonymMapName, RequestOptions requestOptions) { + final String accept = "application/json"; + return service.getSync(this.client.getEndpoint(), this.client.getServiceVersion().getVersion(), synonymMapName, + accept, requestOptions, Context.NONE); + } + + /** + * Lists all synonym maps available for a search service. + *

Query Parameters

+ * + * + * + * + *
Query Parameters
NameTypeRequiredDescription
$selectStringNoSelects 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.
+ * You can add these to a request with {@link RequestOptions#addQueryParam} + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     value (Required): [
+     *          (Required){
+     *             name: String (Required)
+     *             format: String (Required)
+     *             synonyms: String (Required)
+     *             encryptionKey (Optional): {
+     *                 keyVaultKeyName: String (Required)
+     *                 keyVaultKeyVersion: String (Optional)
+     *                 keyVaultUri: String (Required)
+     *                 accessCredentials (Optional): {
+     *                     applicationId: String (Required)
+     *                     applicationSecret: String (Optional)
+     *                 }
+     *                 identity (Optional): {
+     *                     @odata.type: String (Required)
+     *                 }
+     *             }
+     *             @odata.etag: String (Optional)
+     *         }
+     *     ]
+     * }
+     * }
+     * 
+ * + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return response from a List SynonymMaps request along with {@link Response} on successful completion of + * {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono> listWithResponseAsync(RequestOptions requestOptions) { + final String accept = "application/json"; + return FluxUtil.withContext(context -> service.list(this.client.getEndpoint(), + this.client.getServiceVersion().getVersion(), accept, requestOptions, context)); + } + + /** + * Lists all synonym maps available for a search service. + *

Query Parameters

+ * + * + * + * + *
Query Parameters
NameTypeRequiredDescription
$selectStringNoSelects 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.
+ * You can add these to a request with {@link RequestOptions#addQueryParam} + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     value (Required): [
+     *          (Required){
+     *             name: String (Required)
+     *             format: String (Required)
+     *             synonyms: String (Required)
+     *             encryptionKey (Optional): {
+     *                 keyVaultKeyName: String (Required)
+     *                 keyVaultKeyVersion: String (Optional)
+     *                 keyVaultUri: String (Required)
+     *                 accessCredentials (Optional): {
+     *                     applicationId: String (Required)
+     *                     applicationSecret: String (Optional)
+     *                 }
+     *                 identity (Optional): {
+     *                     @odata.type: String (Required)
+     *                 }
+     *             }
+     *             @odata.etag: String (Optional)
+     *         }
+     *     ]
+     * }
+     * }
+     * 
+ * + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return response from a List SynonymMaps request along with {@link Response}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Response listWithResponse(RequestOptions requestOptions) { + final String accept = "application/json"; + return service.listSync(this.client.getEndpoint(), this.client.getServiceVersion().getVersion(), accept, + requestOptions, Context.NONE); + } + + /** + * Creates a new synonym map. + *

Request Body Schema

+ * + *
+     * {@code
+     * {
+     *     name: String (Required)
+     *     format: String (Required)
+     *     synonyms: String (Required)
+     *     encryptionKey (Optional): {
+     *         keyVaultKeyName: String (Required)
+     *         keyVaultKeyVersion: String (Optional)
+     *         keyVaultUri: String (Required)
+     *         accessCredentials (Optional): {
+     *             applicationId: String (Required)
+     *             applicationSecret: String (Optional)
+     *         }
+     *         identity (Optional): {
+     *             @odata.type: String (Required)
+     *         }
+     *     }
+     *     @odata.etag: String (Optional)
+     * }
+     * }
+     * 
+ * + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     name: String (Required)
+     *     format: String (Required)
+     *     synonyms: String (Required)
+     *     encryptionKey (Optional): {
+     *         keyVaultKeyName: String (Required)
+     *         keyVaultKeyVersion: String (Optional)
+     *         keyVaultUri: String (Required)
+     *         accessCredentials (Optional): {
+     *             applicationId: String (Required)
+     *             applicationSecret: String (Optional)
+     *         }
+     *         identity (Optional): {
+     *             @odata.type: String (Required)
+     *         }
+     *     }
+     *     @odata.etag: String (Optional)
+     * }
+     * }
+     * 
+ * + * @param synonymMap The definition of the synonym map to create. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return represents a synonym map definition along with {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono> createWithResponseAsync(BinaryData synonymMap, RequestOptions requestOptions) { + final String contentType = "application/json"; + final String accept = "application/json"; + return FluxUtil.withContext(context -> service.create(this.client.getEndpoint(), + this.client.getServiceVersion().getVersion(), contentType, accept, synonymMap, requestOptions, context)); + } + + /** + * Creates a new synonym map. + *

Request Body Schema

+ * + *
+     * {@code
+     * {
+     *     name: String (Required)
+     *     format: String (Required)
+     *     synonyms: String (Required)
+     *     encryptionKey (Optional): {
+     *         keyVaultKeyName: String (Required)
+     *         keyVaultKeyVersion: String (Optional)
+     *         keyVaultUri: String (Required)
+     *         accessCredentials (Optional): {
+     *             applicationId: String (Required)
+     *             applicationSecret: String (Optional)
+     *         }
+     *         identity (Optional): {
+     *             @odata.type: String (Required)
+     *         }
+     *     }
+     *     @odata.etag: String (Optional)
+     * }
+     * }
+     * 
+ * + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     name: String (Required)
+     *     format: String (Required)
+     *     synonyms: String (Required)
+     *     encryptionKey (Optional): {
+     *         keyVaultKeyName: String (Required)
+     *         keyVaultKeyVersion: String (Optional)
+     *         keyVaultUri: String (Required)
+     *         accessCredentials (Optional): {
+     *             applicationId: String (Required)
+     *             applicationSecret: String (Optional)
+     *         }
+     *         identity (Optional): {
+     *             @odata.type: String (Required)
+     *         }
+     *     }
+     *     @odata.etag: String (Optional)
+     * }
+     * }
+     * 
+ * + * @param synonymMap The definition of the synonym map to create. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return represents a synonym map definition along with {@link Response}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Response createWithResponse(BinaryData synonymMap, RequestOptions requestOptions) { + final String contentType = "application/json"; + final String accept = "application/json"; + return service.createSync(this.client.getEndpoint(), this.client.getServiceVersion().getVersion(), contentType, + accept, synonymMap, requestOptions, Context.NONE); + } +} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/implementation/batching/IndexBatchResponse.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/implementation/batching/IndexBatchResponse.java deleted file mode 100644 index cb4151f77bdf..000000000000 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/implementation/batching/IndexBatchResponse.java +++ /dev/null @@ -1,42 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.search.documents.implementation.batching; - -import com.azure.search.documents.models.IndexingResult; - -import java.util.List; - -/** - * Model class which keeps track of the service results, the offset from the initial request set if it was split, - * and whether the response is an error status. - */ -final class IndexBatchResponse { - private final int statusCode; - private final List results; - private final int count; - private final boolean isError; - - IndexBatchResponse(int statusCode, List results, int count, boolean isError) { - this.statusCode = statusCode; - this.results = results; - this.count = count; - this.isError = isError; - } - - public int getStatusCode() { - return statusCode; - } - - public List getResults() { - return results; - } - - public int getCount() { - return count; - } - - public boolean isError() { - return isError; - } -} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/implementation/batching/IndexingDocumentManager.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/implementation/batching/IndexingDocumentManager.java deleted file mode 100644 index 585bb2c9e2a5..000000000000 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/implementation/batching/IndexingDocumentManager.java +++ /dev/null @@ -1,187 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -package com.azure.search.documents.implementation.batching; - -import com.azure.search.documents.models.IndexAction; -import com.azure.search.documents.options.OnActionAddedOptions; -import reactor.util.function.Tuple2; -import reactor.util.function.Tuples; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.Deque; -import java.util.HashSet; -import java.util.Iterator; -import java.util.LinkedList; -import java.util.List; -import java.util.Set; -import java.util.concurrent.locks.ReentrantLock; -import java.util.function.Consumer; -import java.util.function.Function; - -/** - * This class is responsible for keeping track of the documents that are currently being indexed and the documents that - * are waiting to be indexed. - * - * @param The type of document that is being indexed. - */ -final class IndexingDocumentManager { - private final LinkedList> actions = new LinkedList<>(); - private final ReentrantLock lock = new ReentrantLock(); - - IndexingDocumentManager() { - } - - /* - * This queue keeps track of documents that are currently being sent to the service for indexing. This queue is - * resilient against cases where the request timeouts or is cancelled by an external operation, preventing the - * documents from being lost. - */ - private final Deque> inFlightActions = new LinkedList<>(); - - Collection> getActions() { - lock.lock(); - try { - List> actions = new ArrayList<>(inFlightActions.size() + this.actions.size()); - - for (TryTrackingIndexAction inFlightAction : inFlightActions) { - actions.add(inFlightAction.getAction()); - } - - for (TryTrackingIndexAction action : this.actions) { - actions.add(action.getAction()); - } - - return actions; - } finally { - lock.unlock(); - } - } - - /** - * Adds documents to the batch and checks if there is a batch available for processing. - *

- * Adding documents and checking for a batch is done at the same time as these generally happen together and reduces - * the number of times the lock needs to be acquired. - * - * @param actions The documents to be indexed. - * @param documentKeyRetriever The function to retrieve the key from the document. - * @param onActionAddedConsumer The consumer to be called when an action is added. - * @param batchSize The size required to create a batch - * @return A tuple of the number of actions in the batch and if a batch is available for processing. - */ - Tuple2 addAndCheckForBatch(Collection> actions, - Function documentKeyRetriever, Consumer> onActionAddedConsumer, - int batchSize) { - lock.lock(); - - try { - for (IndexAction action : actions) { - this.actions - .addLast(new TryTrackingIndexAction<>(action, documentKeyRetriever.apply(action.getDocument()))); - - if (onActionAddedConsumer != null) { - onActionAddedConsumer.accept(new OnActionAddedOptions<>(action)); - } - } - - int numberOfActions = this.actions.size(); - boolean hasBatch = numberOfActions + inFlightActions.size() >= batchSize; - - return Tuples.of(numberOfActions, hasBatch); - } finally { - lock.unlock(); - } - } - - /** - * Attempts to create a batch of documents to be sent to the service for indexing. - *

- * If a batch fails to be created null will be returned. A batch can fail to be created if there aren't enough - * documents to create a batch. - * - * @param batchSize The number of actions to include in the batch. - * @param ignoreBatchSize If true, the batch size won't be checked and the batch will be created with the number of - * actions available. - * @return A list of documents to be sent to the service for indexing. - */ - List> tryCreateBatch(int batchSize, boolean ignoreBatchSize) { - lock.lock(); - - try { - int actionSize = this.actions.size(); - int inFlightActionSize = this.inFlightActions.size(); - if (!ignoreBatchSize && actionSize + inFlightActionSize < batchSize) { - return null; - } - - int size = Math.min(batchSize, actionSize + inFlightActionSize); - final List> batchActions = new ArrayList<>(size); - - // Make the set size larger than the expected batch size to prevent a resizing scenario. Don't use a load - // factor of 1 as that would potentially cause collisions. - final Set keysInBatch = new HashSet<>(size * 2); - - // First attempt to fill the batch from documents that were lost in-flight. - int inFlightDocumentsAdded = fillFromQueue(batchActions, inFlightActions, size, keysInBatch); - - // If the batch is filled using documents lost in-flight add the remaining back to the beginning of the queue. - if (inFlightDocumentsAdded == size) { - TryTrackingIndexAction inflightAction; - while ((inflightAction = inFlightActions.pollLast()) != null) { - actions.push(inflightAction); - } - } else { - // Then attempt to fill the batch from documents in the actions queue. - fillFromQueue(batchActions, actions, size - inFlightDocumentsAdded, keysInBatch); - } - - return batchActions; - } finally { - lock.unlock(); - } - } - - private int fillFromQueue(List> batch, Collection> queue, - int requested, Set duplicateKeyTracker) { - int actionsAdded = 0; - - Iterator> iterator = queue.iterator(); - while (actionsAdded < requested && iterator.hasNext()) { - TryTrackingIndexAction potentialDocumentToAdd = iterator.next(); - - if (duplicateKeyTracker.contains(potentialDocumentToAdd.getKey())) { - continue; - } - - duplicateKeyTracker.add(potentialDocumentToAdd.getKey()); - batch.add(potentialDocumentToAdd); - iterator.remove(); - actionsAdded += 1; - } - - return actionsAdded; - } - - void reinsertCancelledActions(List> actionsInFlight) { - lock.lock(); - try { - inFlightActions.addAll(actionsInFlight); - } finally { - lock.unlock(); - } - } - - void reinsertFailedActions(List> actionsToRetry) { - lock.lock(); - - try { - // Push all actions that need to be retried back into the queue. - for (int i = actionsToRetry.size() - 1; i >= 0; i--) { - this.actions.push(actionsToRetry.get(i)); - } - } finally { - lock.unlock(); - } - } -} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/implementation/batching/SearchBatchingUtils.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/implementation/batching/SearchBatchingUtils.java deleted file mode 100644 index 0dee3d9bb90a..000000000000 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/implementation/batching/SearchBatchingUtils.java +++ /dev/null @@ -1,91 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.search.documents.implementation.batching; - -import java.time.Duration; -import java.util.concurrent.ThreadLocalRandom; - -/** - * Utility classes used by Cognitive Search batching publishers. - */ -public final class SearchBatchingUtils { - private static final double JITTER_FACTOR = 0.05; - - /** - * Log message stating that a batch was too large and is being retried as smaller batches. - */ - static final String BATCH_SIZE_SCALED_DOWN - = "Scaling down batch size due to 413 (Payload too large) response.{}Scaled down from {} to {}"; - - /** - * Determines if there is a batch available for processing based on the number of actions and the number of inflight - * actions. - * - * @param actionCount The number of actions in the batch. - * @param inflightActionCount The number of actions that are currently inflight. - * @param batchActionCount The maximum number of actions allowed in a batch. - * @return Whether there is a batch available for processing. - */ - static boolean batchAvailableForProcessing(int actionCount, int inflightActionCount, int batchActionCount) { - return (actionCount + inflightActionCount) >= batchActionCount; - } - - /** - * Determines if the batch action succeeded. - *

- * Only status codes 200 and 201 are considered successful. - * - * @param statusCode The status code of the batch action. - * @return Whether the batch action succeeded. - */ - static boolean isSuccess(int statusCode) { - return statusCode == 200 || statusCode == 201; - } - - /** - * Determines if the batch action is retryable. - *

- * Only status codes 409, 422, and 503 are considered retryable. - * - * @param statusCode The status code of the batch action. - * @return Whether the batch action is retryable. - */ - static boolean isRetryable(int statusCode) { - return statusCode == 409 || statusCode == 422 || statusCode == 503; - } - - /** - * Calculates the retry delay based on the backoff count, delay, and max delay. - * - * @param backoffCount The number of times the batch action has been retried. - * @param delayNanos The delay in nanoseconds. - * @param maxDelayNanos The maximum delay in nanoseconds. - * @return The retry delay. - */ - static Duration calculateRetryDelay(int backoffCount, long delayNanos, long maxDelayNanos) { - // Introduce a small amount of jitter to base delay - long delayWithJitterInNanos = ThreadLocalRandom.current() - .nextLong((long) (delayNanos * (1 - JITTER_FACTOR)), (long) (delayNanos * (1 + JITTER_FACTOR))); - - return Duration.ofNanos(Math.min((1L << backoffCount) * delayWithJitterInNanos, maxDelayNanos)); - } - - /** - * Creates a {@link RuntimeException} for a document that is too large to be indexed. - * - * @return A {@link RuntimeException} for a document that is too large to be indexed. - */ - static RuntimeException createDocumentTooLargeException() { - return new RuntimeException("Document is too large to be indexed and won't be tried again."); - } - - /** - * Creates a {@link RuntimeException} for a document that has reached the retry limit. - * - * @return A {@link RuntimeException} for a document that has reached the retry limit. - */ - static RuntimeException createDocumentHitRetryLimitException() { - return new RuntimeException("Document has reached retry limit and won't be tried again."); - } -} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/implementation/batching/SearchIndexingAsyncPublisher.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/implementation/batching/SearchIndexingAsyncPublisher.java deleted file mode 100644 index 772de7455f8d..000000000000 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/implementation/batching/SearchIndexingAsyncPublisher.java +++ /dev/null @@ -1,314 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.search.documents.implementation.batching; - -import com.azure.core.exception.HttpResponseException; -import com.azure.core.http.rest.Response; -import com.azure.core.util.Context; -import com.azure.core.util.CoreUtils; -import com.azure.core.util.logging.ClientLogger; -import com.azure.core.util.serializer.JsonSerializer; -import com.azure.search.documents.implementation.SearchIndexClientImpl; -import com.azure.search.documents.implementation.converters.IndexActionConverter; -import com.azure.search.documents.implementation.util.Utility; -import com.azure.search.documents.models.IndexAction; -import com.azure.search.documents.models.IndexBatchException; -import com.azure.search.documents.models.IndexDocumentsResult; -import com.azure.search.documents.models.IndexingResult; -import com.azure.search.documents.options.OnActionAddedOptions; -import com.azure.search.documents.options.OnActionErrorOptions; -import com.azure.search.documents.options.OnActionSentOptions; -import com.azure.search.documents.options.OnActionSucceededOptions; -import reactor.core.publisher.Flux; -import reactor.core.publisher.Mono; -import reactor.util.function.Tuple2; - -import java.net.HttpURLConnection; -import java.time.Duration; -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; -import java.util.Objects; -import java.util.concurrent.Semaphore; -import java.util.concurrent.atomic.AtomicInteger; -import java.util.function.Consumer; -import java.util.function.Function; -import java.util.stream.Collectors; - -import static com.azure.search.documents.implementation.batching.SearchBatchingUtils.BATCH_SIZE_SCALED_DOWN; -import static com.azure.search.documents.implementation.batching.SearchBatchingUtils.calculateRetryDelay; -import static com.azure.search.documents.implementation.batching.SearchBatchingUtils.createDocumentHitRetryLimitException; -import static com.azure.search.documents.implementation.batching.SearchBatchingUtils.createDocumentTooLargeException; -import static com.azure.search.documents.implementation.batching.SearchBatchingUtils.isRetryable; -import static com.azure.search.documents.implementation.batching.SearchBatchingUtils.isSuccess; - -/** - * Internal helper class that manages sending automatic document batches to Azure Search Documents. - * - * @param Type of the document in the batch. - */ -public final class SearchIndexingAsyncPublisher { - private static final ClientLogger LOGGER = new ClientLogger(SearchIndexingAsyncPublisher.class); - - private final SearchIndexClientImpl restClient; - private final JsonSerializer serializer; - - private final boolean autoFlush; - private int batchSize; - private final int maxRetries; - private final long throttlingDelayNanos; - private final long maxThrottlingDelayNanos; - - private final Consumer> onActionAdded; - private final Consumer> onActionSent; - private final Consumer> onActionSucceeded; - private final Consumer> onActionError; - - private final Function documentKeyRetriever; - private final Function scaleDownFunction = size -> size / 2; - private final IndexingDocumentManager documentManager; - - private final Semaphore processingSemaphore = new Semaphore(1, true); - - volatile AtomicInteger backoffCount = new AtomicInteger(); - volatile Duration currentRetryDelay = Duration.ZERO; - - public SearchIndexingAsyncPublisher(SearchIndexClientImpl restClient, JsonSerializer serializer, - Function documentKeyRetriever, boolean autoFlush, int initialBatchActionCount, - int maxRetriesPerAction, Duration throttlingDelay, Duration maxThrottlingDelay, - Consumer> onActionAdded, Consumer> onActionSucceeded, - Consumer> onActionError, Consumer> onActionSent) { - this.documentKeyRetriever - = Objects.requireNonNull(documentKeyRetriever, "'documentKeyRetriever' cannot be null"); - - this.restClient = restClient; - this.serializer = serializer; - this.documentManager = new IndexingDocumentManager<>(); - - this.autoFlush = autoFlush; - this.batchSize = initialBatchActionCount; - this.maxRetries = maxRetriesPerAction; - this.throttlingDelayNanos = throttlingDelay.toNanos(); - this.maxThrottlingDelayNanos = (maxThrottlingDelay.compareTo(throttlingDelay) < 0) - ? this.throttlingDelayNanos - : maxThrottlingDelay.toNanos(); - - this.onActionAdded = onActionAdded; - this.onActionSent = onActionSent; - this.onActionSucceeded = onActionSucceeded; - this.onActionError = onActionError; - } - - public Collection> getActions() { - return documentManager.getActions(); - } - - public int getBatchSize() { - return batchSize; - } - - public Duration getCurrentRetryDelay() { - return currentRetryDelay; - } - - public Mono addActions(Collection> actions, Context context, Runnable rescheduleFlush) { - Tuple2 batchSizeAndAvailable - = documentManager.addAndCheckForBatch(actions, documentKeyRetriever, onActionAdded, batchSize); - - LOGGER.verbose("Actions added, new pending queue size: {}.", batchSizeAndAvailable.getT1()); - - if (autoFlush && batchSizeAndAvailable.getT2()) { - rescheduleFlush.run(); - LOGGER.verbose("Adding documents triggered batch size limit, sending documents for indexing."); - return flush(false, false, context); - } - - return Mono.empty(); - } - - public Mono flush(boolean awaitLock, boolean isClose, Context context) { - if (awaitLock) { - try { - processingSemaphore.acquire(); - } catch (InterruptedException e) { - throw LOGGER.logExceptionAsError(new RuntimeException(e)); - } - - return Mono.using(() -> processingSemaphore, ignored -> flushLoop(isClose, context), Semaphore::release); - } else if (processingSemaphore.tryAcquire()) { - return Mono.using(() -> processingSemaphore, ignored -> flushLoop(isClose, context), Semaphore::release); - } else { - LOGGER.verbose("Batch already in-flight and not waiting for completion. Performing no-op."); - return Mono.empty(); - } - } - - private Mono flushLoop(boolean isClosed, Context context) { - return createAndProcessBatch(context, true) - .expand(ignored -> Flux.defer(() -> createAndProcessBatch(context, isClosed))) - .then(); - } - - private Mono createAndProcessBatch(Context context, boolean ignoreBatchSize) { - List> batchActions = documentManager.tryCreateBatch(batchSize, ignoreBatchSize); - - // If there are no documents to in the batch to index just return. - if (CoreUtils.isNullOrEmpty(batchActions)) { - return Mono.empty(); - } - - List convertedActions = batchActions.stream() - .map(action -> IndexActionConverter.map(action.getAction(), serializer)) - .collect(Collectors.toList()); - - return sendBatch(convertedActions, batchActions, context).map(response -> { - handleResponse(batchActions, response); - - return response; - }); - } - - /* - * This may result in more than one service call in the case where the index batch is too large and we attempt to - * split it. - */ - private Mono sendBatch( - List actions, - List> batchActions, Context context) { - LOGGER.verbose("Sending a batch of size {}.", batchActions.size()); - - if (onActionSent != null) { - batchActions.forEach(action -> onActionSent.accept(new OnActionSentOptions<>(action.getAction()))); - } - - Mono> batchCall - = Utility.indexDocumentsWithResponseAsync(restClient, actions, true, context, LOGGER); - - if (!currentRetryDelay.isZero() && !currentRetryDelay.isNegative()) { - batchCall = batchCall.delaySubscription(currentRetryDelay); - } - - return batchCall.map(response -> new IndexBatchResponse(response.getStatusCode(), - response.getValue().getResults(), actions.size(), false)).doOnCancel(() -> { - LOGGER.warning("Request was cancelled before response, adding all in-flight documents back to queue."); - documentManager.reinsertCancelledActions(batchActions); - }) - // Handles mixed success responses. - .onErrorResume(IndexBatchException.class, - exception -> Mono - .just(new IndexBatchResponse(207, exception.getIndexingResults(), actions.size(), true))) - .onErrorResume(HttpResponseException.class, exception -> { - /* - * If we received an error response where the payload was too large split it into two smaller payloads - * and attempt to index again. If the number of index actions was one raise the error as we cannot split - * that any further. - */ - int statusCode = exception.getResponse().getStatusCode(); - if (statusCode == HttpURLConnection.HTTP_ENTITY_TOO_LARGE) { - /* - * Pass both the sent batch size and the configured batch size. This covers that case where the - * sent batch size was smaller than the configured batch size and a 413 was trigger. - * - * For example, by default the configured batch size defaults to 512 but a batch of 200 may be sent - * and trigger 413, if we only halved 512 we'd send the same batch again and 413 a second time. - * Instead in this scenario we should halve 200 to 100. - */ - int previousBatchSize = Math.min(batchSize, actions.size()); - this.batchSize = Math.max(1, scaleDownFunction.apply(previousBatchSize)); - - LOGGER.verbose(BATCH_SIZE_SCALED_DOWN, System.lineSeparator(), previousBatchSize, batchSize); - - int actionCount = actions.size(); - if (actionCount == 1) { - return Mono.just(new IndexBatchResponse(statusCode, null, actionCount, true)); - } - - int splitOffset = Math.min(actions.size(), batchSize); - List> batchActionsToRemove - = batchActions.subList(splitOffset, batchActions.size()); - documentManager.reinsertFailedActions(batchActionsToRemove); - batchActionsToRemove.clear(); - - return sendBatch(actions.subList(0, splitOffset), batchActions, context); - } - - return Mono.just(new IndexBatchResponse(statusCode, null, actions.size(), true)); - }) - // General catch all to allow operation to continue. - .onErrorResume(Exception.class, - ignored -> Mono.just(new IndexBatchResponse(0, null, actions.size(), true))); - } - - private void handleResponse(List> actions, IndexBatchResponse batchResponse) { - /* - * Batch has been split until it had one document in it and it returned a 413 response. - */ - if (batchResponse.getStatusCode() == HttpURLConnection.HTTP_ENTITY_TOO_LARGE && batchResponse.getCount() == 1) { - IndexAction action = actions.get(0).getAction(); - if (onActionError != null) { - onActionError - .accept(new OnActionErrorOptions<>(action).setThrowable(createDocumentTooLargeException())); - } - return; - } - - List> actionsToRetry = new ArrayList<>(); - boolean has503 = batchResponse.getStatusCode() == HttpURLConnection.HTTP_UNAVAILABLE; - if (batchResponse.getResults() == null) { - /* - * Null results indicates that the entire request failed. Retry all documents. - */ - actionsToRetry.addAll(actions); - } else { - /* - * We got back a result set, correlate responses to their request document and add retryable actions back - * into the queue. - */ - for (IndexingResult result : batchResponse.getResults()) { - String key = result.getKey(); - TryTrackingIndexAction action - = actions.stream().filter(a -> key.equals(a.getKey())).findFirst().orElse(null); - - if (action == null) { - LOGGER.warning("Unable to correlate result key {} to initial document.", key); - continue; - } - - if (isSuccess(result.getStatusCode())) { - if (onActionSucceeded != null) { - onActionSucceeded.accept(new OnActionSucceededOptions<>(action.getAction())); - } - } else if (isRetryable(result.getStatusCode())) { - has503 |= result.getStatusCode() == HttpURLConnection.HTTP_UNAVAILABLE; - if (action.getTryCount() < maxRetries) { - action.incrementTryCount(); - actionsToRetry.add(action); - } else { - if (onActionError != null) { - onActionError.accept(new OnActionErrorOptions<>(action.getAction()) - .setThrowable(createDocumentHitRetryLimitException()) - .setIndexingResult(result)); - } - } - } else { - if (onActionError != null) { - onActionError.accept(new OnActionErrorOptions<>(action.getAction()).setIndexingResult(result)); - } - } - } - } - - if (has503) { - currentRetryDelay - = calculateRetryDelay(backoffCount.getAndIncrement(), throttlingDelayNanos, maxThrottlingDelayNanos); - } else { - backoffCount.set(0); - currentRetryDelay = Duration.ZERO; - } - - if (!CoreUtils.isNullOrEmpty(actionsToRetry)) { - documentManager.reinsertFailedActions(actionsToRetry); - } - } -} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/implementation/batching/SearchIndexingPublisher.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/implementation/batching/SearchIndexingPublisher.java deleted file mode 100644 index 55dab982b93a..000000000000 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/implementation/batching/SearchIndexingPublisher.java +++ /dev/null @@ -1,360 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.search.documents.implementation.batching; - -import com.azure.core.exception.HttpResponseException; -import com.azure.core.http.rest.Response; -import com.azure.core.util.Context; -import com.azure.core.util.CoreUtils; -import com.azure.core.util.SharedExecutorService; -import com.azure.core.util.logging.ClientLogger; -import com.azure.core.util.serializer.JsonSerializer; -import com.azure.search.documents.implementation.SearchIndexClientImpl; -import com.azure.search.documents.implementation.converters.IndexActionConverter; -import com.azure.search.documents.implementation.util.Utility; -import com.azure.search.documents.models.IndexAction; -import com.azure.search.documents.models.IndexBatchException; -import com.azure.search.documents.models.IndexDocumentsResult; -import com.azure.search.documents.models.IndexingResult; -import com.azure.search.documents.options.OnActionAddedOptions; -import com.azure.search.documents.options.OnActionErrorOptions; -import com.azure.search.documents.options.OnActionSentOptions; -import com.azure.search.documents.options.OnActionSucceededOptions; -import reactor.util.function.Tuple2; - -import java.net.HttpURLConnection; -import java.time.Duration; -import java.util.Collection; -import java.util.LinkedList; -import java.util.List; -import java.util.Objects; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.Future; -import java.util.concurrent.TimeoutException; -import java.util.concurrent.atomic.AtomicInteger; -import java.util.concurrent.atomic.AtomicReference; -import java.util.concurrent.locks.ReentrantLock; -import java.util.function.Consumer; -import java.util.function.Function; -import java.util.stream.Collectors; - -import static com.azure.search.documents.implementation.batching.SearchBatchingUtils.BATCH_SIZE_SCALED_DOWN; -import static com.azure.search.documents.implementation.batching.SearchBatchingUtils.calculateRetryDelay; -import static com.azure.search.documents.implementation.batching.SearchBatchingUtils.createDocumentHitRetryLimitException; -import static com.azure.search.documents.implementation.batching.SearchBatchingUtils.createDocumentTooLargeException; -import static com.azure.search.documents.implementation.batching.SearchBatchingUtils.isRetryable; -import static com.azure.search.documents.implementation.batching.SearchBatchingUtils.isSuccess; - -/** - * Internal helper class that manages sending automatic document batches to Azure Search Documents. - * - * @param The type of document in the batch. - */ -public final class SearchIndexingPublisher { - private static final ClientLogger LOGGER = new ClientLogger(SearchIndexingPublisher.class); - - private final SearchIndexClientImpl restClient; - private final JsonSerializer serializer; - - private final boolean autoFlush; - private int batchSize; - private final int maxRetries; - private final long throttlingDelayNanos; - private final long maxThrottlingDelayNanos; - - private final Consumer> onActionAdded; - private final Consumer> onActionSent; - private final Consumer> onActionSucceeded; - private final Consumer> onActionError; - - private final Function documentKeyRetriever; - private final Function scaleDownFunction = size -> size / 2; - private final IndexingDocumentManager documentManager; - - private final ReentrantLock lock = new ReentrantLock(true); - - volatile AtomicInteger backoffCount = new AtomicInteger(); - volatile Duration currentRetryDelay = Duration.ZERO; - - public SearchIndexingPublisher(SearchIndexClientImpl restClient, JsonSerializer serializer, - Function documentKeyRetriever, boolean autoFlush, int initialBatchActionCount, - int maxRetriesPerAction, Duration throttlingDelay, Duration maxThrottlingDelay, - Consumer> onActionAdded, Consumer> onActionSucceeded, - Consumer> onActionError, Consumer> onActionSent) { - this.documentKeyRetriever - = Objects.requireNonNull(documentKeyRetriever, "'documentKeyRetriever' cannot be null"); - - this.restClient = restClient; - this.serializer = serializer; - this.documentManager = new IndexingDocumentManager<>(); - - this.autoFlush = autoFlush; - this.batchSize = initialBatchActionCount; - this.maxRetries = maxRetriesPerAction; - this.throttlingDelayNanos = throttlingDelay.toNanos(); - this.maxThrottlingDelayNanos = (maxThrottlingDelay.compareTo(throttlingDelay) < 0) - ? this.throttlingDelayNanos - : maxThrottlingDelay.toNanos(); - - this.onActionAdded = onActionAdded; - this.onActionSent = onActionSent; - this.onActionSucceeded = onActionSucceeded; - this.onActionError = onActionError; - } - - public Collection> getActions() { - return documentManager.getActions(); - } - - public int getBatchSize() { - return batchSize; - } - - public Duration getCurrentRetryDelay() { - return currentRetryDelay; - } - - public void addActions(Collection> actions, Duration timeout, Context context, - Runnable rescheduleFlush) { - Tuple2 batchSizeAndAvailable - = documentManager.addAndCheckForBatch(actions, documentKeyRetriever, onActionAdded, batchSize); - - LOGGER.verbose("Actions added, new pending queue size: {}.", batchSizeAndAvailable.getT1()); - - if (autoFlush && batchSizeAndAvailable.getT2()) { - rescheduleFlush.run(); - LOGGER.verbose("Adding documents triggered batch size limit, sending documents for indexing."); - flush(false, false, timeout, context); - } - } - - public void flush(boolean awaitLock, boolean isClose, Duration timeout, Context context) { - if (awaitLock) { - lock.lock(); - - try { - flushLoop(isClose, timeout, context); - } finally { - lock.unlock(); - } - } else if (lock.tryLock()) { - try { - flushLoop(isClose, timeout, context); - } finally { - lock.unlock(); - } - } else { - LOGGER.verbose("Batch already in-flight and not waiting for completion. Performing no-op."); - } - } - - private void flushLoop(boolean isClosed, Duration timeout, Context context) { - if (timeout != null && !timeout.isNegative() && !timeout.isZero()) { - final AtomicReference>> batchActions = new AtomicReference<>(); - Future future - = SharedExecutorService.getInstance().submit(() -> flushLoopHelper(isClosed, context, batchActions)); - - try { - CoreUtils.getResultWithTimeout(future, timeout); - } catch (ExecutionException e) { - Throwable realCause = e.getCause(); - if (realCause instanceof Error) { - throw (Error) realCause; - } else if (realCause instanceof RuntimeException) { - throw LOGGER.logExceptionAsError((RuntimeException) realCause); - } else { - throw LOGGER.logExceptionAsError(new RuntimeException(realCause)); - } - } catch (InterruptedException e) { - throw LOGGER.logExceptionAsError(new RuntimeException(e)); - } catch (TimeoutException e) { - documentManager.reinsertCancelledActions(batchActions.get()); - - throw LOGGER.logExceptionAsError(new RuntimeException(e)); - } - } else { - flushLoopHelper(isClosed, context, null); - } - } - - private void flushLoopHelper(boolean isClosed, Context context, - AtomicReference>> batchActions) { - List> batch = documentManager.tryCreateBatch(batchSize, true); - if (batchActions != null) { - batchActions.set(batch); - } - - // Process the current batch. - IndexBatchResponse response = processBatch(batch, context); - - // Then while a batch has been processed and there are still documents to index, keep processing batches. - while (response != null && (batch = documentManager.tryCreateBatch(batchSize, isClosed)) != null) { - if (batchActions != null) { - batchActions.set(batch); - } - - response = processBatch(batch, context); - } - } - - private IndexBatchResponse processBatch(List> batchActions, Context context) { - // If there are no documents to in the batch to index just return. - if (CoreUtils.isNullOrEmpty(batchActions)) { - return null; - } - - List convertedActions = batchActions.stream() - .map(action -> IndexActionConverter.map(action.getAction(), serializer)) - .collect(Collectors.toList()); - - IndexBatchResponse response = sendBatch(convertedActions, batchActions, context); - handleResponse(batchActions, response); - - return response; - } - - /* - * This may result in more than one service call in the case where the index batch is too large and we attempt to - * split it. - */ - private IndexBatchResponse sendBatch(List actions, - List> batchActions, Context context) { - LOGGER.verbose("Sending a batch of size {}.", batchActions.size()); - - if (onActionSent != null) { - batchActions.forEach(action -> onActionSent.accept(new OnActionSentOptions<>(action.getAction()))); - } - - if (!currentRetryDelay.isZero() && !currentRetryDelay.isNegative()) { - sleep(currentRetryDelay.toMillis()); - } - - try { - Response batchCall - = Utility.indexDocumentsWithResponse(restClient, actions, true, context, LOGGER); - return new IndexBatchResponse(batchCall.getStatusCode(), batchCall.getValue().getResults(), actions.size(), - false); - } catch (IndexBatchException exception) { - return new IndexBatchResponse(207, exception.getIndexingResults(), actions.size(), true); - } catch (HttpResponseException exception) { - /* - * If we received an error response where the payload was too large split it into two smaller payloads - * and attempt to index again. If the number of index actions was one raise the error as we cannot split - * that any further. - */ - int statusCode = exception.getResponse().getStatusCode(); - if (statusCode == HttpURLConnection.HTTP_ENTITY_TOO_LARGE) { - /* - * Pass both the sent batch size and the configured batch size. This covers that case where the - * sent batch size was smaller than the configured batch size and a 413 was trigger. - * - * For example, by default the configured batch size defaults to 512 but a batch of 200 may be sent - * and trigger 413, if we only halved 512 we'd send the same batch again and 413 a second time. - * Instead in this scenario we should halve 200 to 100. - */ - int previousBatchSize = Math.min(batchSize, actions.size()); - this.batchSize = Math.max(1, scaleDownFunction.apply(previousBatchSize)); - - LOGGER.verbose(BATCH_SIZE_SCALED_DOWN, System.lineSeparator(), previousBatchSize, batchSize); - - int actionCount = actions.size(); - if (actionCount == 1) { - return new IndexBatchResponse(statusCode, null, actionCount, true); - } - - int splitOffset = Math.min(actions.size(), batchSize); - List> batchActionsToRemove - = batchActions.subList(splitOffset, batchActions.size()); - documentManager.reinsertFailedActions(batchActionsToRemove); - batchActionsToRemove.clear(); - - return sendBatch(actions.subList(0, splitOffset), batchActions, context); - } - - return new IndexBatchResponse(statusCode, null, actions.size(), true); - } catch (Exception e) { - // General catch all to allow operation to continue. - return new IndexBatchResponse(0, null, actions.size(), true); - } - } - - private void handleResponse(List> actions, IndexBatchResponse batchResponse) { - /* - * Batch has been split until it had one document in it and it returned a 413 response. - */ - if (batchResponse.getStatusCode() == HttpURLConnection.HTTP_ENTITY_TOO_LARGE && batchResponse.getCount() == 1) { - IndexAction action = actions.get(0).getAction(); - if (onActionError != null) { - onActionError - .accept(new OnActionErrorOptions<>(action).setThrowable(createDocumentTooLargeException())); - } - return; - } - - LinkedList> actionsToRetry = new LinkedList<>(); - boolean has503 = batchResponse.getStatusCode() == HttpURLConnection.HTTP_UNAVAILABLE; - if (batchResponse.getResults() == null) { - /* - * Null results indicates that the entire request failed. Retry all documents. - */ - actionsToRetry.addAll(actions); - } else { - /* - * We got back a result set, correlate responses to their request document and add retryable actions back - * into the queue. - */ - for (IndexingResult result : batchResponse.getResults()) { - String key = result.getKey(); - TryTrackingIndexAction action - = actions.stream().filter(a -> key.equals(a.getKey())).findFirst().orElse(null); - - if (action == null) { - LOGGER.warning("Unable to correlate result key {} to initial document.", key); - continue; - } - - if (isSuccess(result.getStatusCode())) { - if (onActionSucceeded != null) { - onActionSucceeded.accept(new OnActionSucceededOptions<>(action.getAction())); - } - } else if (isRetryable(result.getStatusCode())) { - has503 |= result.getStatusCode() == HttpURLConnection.HTTP_UNAVAILABLE; - if (action.getTryCount() < maxRetries) { - action.incrementTryCount(); - actionsToRetry.add(action); - } else { - if (onActionError != null) { - onActionError.accept(new OnActionErrorOptions<>(action.getAction()) - .setThrowable(createDocumentHitRetryLimitException()) - .setIndexingResult(result)); - } - } - } else { - if (onActionError != null) { - onActionError.accept(new OnActionErrorOptions<>(action.getAction()).setIndexingResult(result)); - } - } - } - } - - if (has503) { - currentRetryDelay - = calculateRetryDelay(backoffCount.getAndIncrement(), throttlingDelayNanos, maxThrottlingDelayNanos); - } else { - backoffCount.set(0); - currentRetryDelay = Duration.ZERO; - } - - if (!CoreUtils.isNullOrEmpty(actionsToRetry)) { - documentManager.reinsertFailedActions(actionsToRetry); - } - } - - private static void sleep(long millis) { - try { - Thread.sleep(millis); - } catch (InterruptedException ignored) { - } - } -} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/implementation/batching/TryTrackingIndexAction.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/implementation/batching/TryTrackingIndexAction.java deleted file mode 100644 index 376c5994ea51..000000000000 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/implementation/batching/TryTrackingIndexAction.java +++ /dev/null @@ -1,37 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.search.documents.implementation.batching; - -import com.azure.search.documents.models.IndexAction; - -/** - * Model class that tracks the number of times an IndexAction has tried to be indexed. - */ -final class TryTrackingIndexAction { - private final IndexAction action; - private final String key; - - private int tryCount = 0; - - TryTrackingIndexAction(IndexAction action, String key) { - this.action = action; - this.key = key; - } - - public IndexAction getAction() { - return action; - } - - public String getKey() { - return key; - } - - public int getTryCount() { - return tryCount; - } - - public void incrementTryCount() { - tryCount++; - } -} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/implementation/batching/package-info.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/implementation/batching/package-info.java deleted file mode 100644 index dfebc642f1c9..000000000000 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/implementation/batching/package-info.java +++ /dev/null @@ -1,7 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -/** - * Package containing implementation classes for batching. - */ -package com.azure.search.documents.implementation.batching; diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/implementation/converters/AnalyzeRequestConverter.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/implementation/converters/AnalyzeRequestConverter.java deleted file mode 100644 index 500feb8d77da..000000000000 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/implementation/converters/AnalyzeRequestConverter.java +++ /dev/null @@ -1,30 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.search.documents.implementation.converters; - -import com.azure.search.documents.indexes.models.AnalyzeTextOptions; - -/** - * A converter between {@link com.azure.search.documents.indexes.implementation.models.AnalyzeRequest} and - * {@link AnalyzeTextOptions}. - */ -public final class AnalyzeRequestConverter { - /** - * Maps from {@link AnalyzeTextOptions} to {@link com.azure.search.documents.indexes.implementation.models.AnalyzeRequest}. - */ - public static com.azure.search.documents.indexes.implementation.models.AnalyzeRequest map(AnalyzeTextOptions obj) { - if (obj == null) { - return null; - } - - return new com.azure.search.documents.indexes.implementation.models.AnalyzeRequest(obj.getText()) - .setAnalyzer(obj.getAnalyzerName()) - .setTokenizer(obj.getTokenizerName()) - .setCharFilters(obj.getCharFilters()) - .setTokenFilters(obj.getTokenFilters()); - } - - private AnalyzeRequestConverter() { - } -} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/implementation/converters/IndexActionConverter.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/implementation/converters/IndexActionConverter.java deleted file mode 100644 index 685d74584efd..000000000000 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/implementation/converters/IndexActionConverter.java +++ /dev/null @@ -1,72 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.search.documents.implementation.converters; - -import com.azure.core.util.serializer.ObjectSerializer; -import com.azure.json.JsonProviders; -import com.azure.json.JsonReader; -import com.azure.search.documents.models.IndexAction; - -import java.io.IOException; -import java.io.UncheckedIOException; -import java.util.Map; - -/** - * A converter between {@link com.azure.search.documents.implementation.models.IndexAction} and {@link IndexAction}. - */ -public final class IndexActionConverter { - /** - * Maps from {@link com.azure.search.documents.implementation.models.IndexAction} to {@link IndexAction}. - */ - public static IndexAction map(com.azure.search.documents.implementation.models.IndexAction obj) { - if (obj == null) { - return null; - } - - IndexAction indexAction = new IndexAction<>(); - indexAction.setActionType(obj.getActionType()); - - if (obj.getAdditionalProperties() != null) { - Map properties = obj.getAdditionalProperties(); - IndexActionHelper.setProperties(indexAction, properties); - } - - return indexAction; - } - - /** - * Maps from {@link IndexAction} to {@link com.azure.search.documents.implementation.models.IndexAction}. - */ - public static com.azure.search.documents.implementation.models.IndexAction map(IndexAction obj, - ObjectSerializer serializer) { - if (obj == null) { - return null; - } - com.azure.search.documents.implementation.models.IndexAction indexAction - = new com.azure.search.documents.implementation.models.IndexAction().setActionType(obj.getActionType()); - - // Attempt to get the document as the Map properties. - Object document = IndexActionHelper.getProperties(obj); - if (document == null) { - // If ths document wasn't a Map type, get the generic document type. - document = obj.getDocument(); - } - - // Convert the document to the JSON representation. - byte[] documentJson = serializer.serializeToBytes(document); - - if (documentJson != null) { - try (JsonReader reader = JsonProviders.createReader(documentJson)) { - indexAction.setAdditionalProperties(reader.readMap(JsonReader::readUntyped)); - } catch (IOException ex) { - throw new UncheckedIOException(ex); - } - } - - return indexAction; - } - - private IndexActionConverter() { - } -} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/implementation/converters/IndexActionHelper.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/implementation/converters/IndexActionHelper.java deleted file mode 100644 index 7d84f8e45606..000000000000 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/implementation/converters/IndexActionHelper.java +++ /dev/null @@ -1,44 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.search.documents.implementation.converters; - -import com.azure.search.documents.models.IndexAction; - -import java.util.Map; - -/** - * The helper class to set the non-public properties of an {@link IndexAction} instance. - */ -public final class IndexActionHelper { - private static IndexActionAccessor accessor; - - private IndexActionHelper() { - } - - /** - * Type defining the methods to set the non-public properties of an {@link IndexAction} instance. - */ - public interface IndexActionAccessor { - void setProperties(IndexAction indexAction, Map properties); - - Map getProperties(IndexAction indexAction); - } - - /** - * The method called from {@link IndexAction} to set it's accessor. - * - * @param indexActionAccessor The accessor. - */ - public static void setAccessor(final IndexActionAccessor indexActionAccessor) { - accessor = indexActionAccessor; - } - - static void setProperties(IndexAction indexAction, Map properties) { - accessor.setProperties(indexAction, properties); - } - - static Map getProperties(IndexAction indexAction) { - return accessor.getProperties(indexAction); - } -} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/implementation/converters/SearchResultConverter.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/implementation/converters/SearchResultConverter.java deleted file mode 100644 index f5d5cc5fda84..000000000000 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/implementation/converters/SearchResultConverter.java +++ /dev/null @@ -1,36 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.search.documents.implementation.converters; - -import com.azure.core.util.serializer.JsonSerializer; -import com.azure.core.util.serializer.ObjectSerializer; -import com.azure.search.documents.SearchDocument; -import com.azure.search.documents.models.SearchResult; - -/** - * A converter between {@link com.azure.search.documents.implementation.models.SearchResult} and {@link SearchResult}. - */ -public final class SearchResultConverter { - /** - * Maps from {@link com.azure.search.documents.implementation.models.SearchResult} to {@link SearchResult}. - */ - public static SearchResult map(com.azure.search.documents.implementation.models.SearchResult obj, - ObjectSerializer serializer) { - if (obj == null) { - return null; - } - - SearchResult searchResult = new SearchResult(obj.getScore()); - - SearchResultHelper.setHighlights(searchResult, obj.getHighlights()); - SearchResultHelper.setSemanticSearchResults(searchResult, obj.getRerankerScore(), obj.getCaptions()); - SearchResultHelper.setDocumentDebugInfo(searchResult, obj.getDocumentDebugInfo()); - SearchResultHelper.setAdditionalProperties(searchResult, new SearchDocument(obj.getAdditionalProperties())); - SearchResultHelper.setJsonSerializer(searchResult, (JsonSerializer) serializer); - return searchResult; - } - - private SearchResultConverter() { - } -} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/implementation/converters/SearchResultHelper.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/implementation/converters/SearchResultHelper.java deleted file mode 100644 index 8388a0d2376e..000000000000 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/implementation/converters/SearchResultHelper.java +++ /dev/null @@ -1,69 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.search.documents.implementation.converters; - -import com.azure.core.util.serializer.JsonSerializer; -import com.azure.search.documents.SearchDocument; -import com.azure.search.documents.models.DocumentDebugInfo; -import com.azure.search.documents.models.QueryCaptionResult; -import com.azure.search.documents.models.SearchResult; - -import java.util.List; -import java.util.Map; - -/** - * The helper class to set the non-public properties of an {@link SearchResult} instance. - */ -public final class SearchResultHelper { - private static SearchResultAccessor accessor; - - private SearchResultHelper() { - } - - /** - * Type defining the methods to set the non-public properties of an {@link SearchResult} instance. - */ - public interface SearchResultAccessor { - void setAdditionalProperties(SearchResult searchResult, SearchDocument additionalProperties); - - void setHighlights(SearchResult searchResult, Map> highlights); - - void setJsonSerializer(SearchResult searchResult, JsonSerializer jsonSerializer); - - void setSemanticSearchResults(SearchResult searchResult, Double rerankerScore, - List captions); - - void setDocumentDebugInfo(SearchResult searchResult, DocumentDebugInfo documentDebugInfo); - } - - /** - * The method called from {@link SearchResult} to set it's accessor. - * - * @param searchResultAccessor The accessor. - */ - public static void setAccessor(final SearchResultAccessor searchResultAccessor) { - accessor = searchResultAccessor; - } - - static void setAdditionalProperties(SearchResult searchResult, SearchDocument additionalProperties) { - accessor.setAdditionalProperties(searchResult, additionalProperties); - } - - static void setHighlights(SearchResult searchResult, Map> highlights) { - accessor.setHighlights(searchResult, highlights); - } - - static void setJsonSerializer(SearchResult searchResult, JsonSerializer jsonSerializer) { - accessor.setJsonSerializer(searchResult, jsonSerializer); - } - - static void setSemanticSearchResults(SearchResult searchResult, Double rerankerScore, - List captions) { - accessor.setSemanticSearchResults(searchResult, rerankerScore, captions); - } - - static void setDocumentDebugInfo(SearchResult searchResult, DocumentDebugInfo documentDebugInfo) { - accessor.setDocumentDebugInfo(searchResult, documentDebugInfo); - } -} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/implementation/converters/SuggestResultConverter.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/implementation/converters/SuggestResultConverter.java deleted file mode 100644 index d20f977cb249..000000000000 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/implementation/converters/SuggestResultConverter.java +++ /dev/null @@ -1,33 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.search.documents.implementation.converters; - -import com.azure.core.util.serializer.JsonSerializer; -import com.azure.search.documents.SearchDocument; -import com.azure.search.documents.models.SuggestResult; - -/** - * A converter between {@link com.azure.search.documents.implementation.models.SuggestResult} and {@link SuggestResult}. - */ -public final class SuggestResultConverter { - /** - * Maps from {@link com.azure.search.documents.implementation.models.SuggestResult} to {@link SuggestResult}. - */ - public static SuggestResult map(com.azure.search.documents.implementation.models.SuggestResult obj, - JsonSerializer jsonSerializer) { - if (obj == null) { - return null; - } - SuggestResult suggestResult = new SuggestResult(obj.getText()); - - SearchDocument additionalProperties = new SearchDocument(obj.getAdditionalProperties()); - SuggestResultHelper.setAdditionalProperties(suggestResult, additionalProperties); - SuggestResultHelper.setJsonSerializer(suggestResult, jsonSerializer); - - return suggestResult; - } - - private SuggestResultConverter() { - } -} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/implementation/converters/SuggestResultHelper.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/implementation/converters/SuggestResultHelper.java deleted file mode 100644 index 523be151707d..000000000000 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/implementation/converters/SuggestResultHelper.java +++ /dev/null @@ -1,44 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.search.documents.implementation.converters; - -import com.azure.core.util.serializer.JsonSerializer; -import com.azure.search.documents.SearchDocument; -import com.azure.search.documents.models.SuggestResult; - -/** - * The helper class to set the non-public properties of an {@link SuggestResult} instance. - */ -public final class SuggestResultHelper { - private static SuggestResultAccessor accessor; - - private SuggestResultHelper() { - } - - /** - * Type defining the methods to set the non-public properties of an {@link SuggestResult} instance. - */ - public interface SuggestResultAccessor { - void setAdditionalProperties(SuggestResult suggestResult, SearchDocument additionalProperties); - - void setJsonSerializer(SuggestResult suggestResult, JsonSerializer jsonSerializer); - } - - /** - * The method called from {@link SuggestResult} to set it's accessor. - * - * @param suggestResultAccessor The accessor. - */ - public static void setAccessor(final SuggestResultAccessor suggestResultAccessor) { - accessor = suggestResultAccessor; - } - - static void setAdditionalProperties(SuggestResult suggestResult, SearchDocument additionalProperties) { - accessor.setAdditionalProperties(suggestResult, additionalProperties); - } - - static void setJsonSerializer(SuggestResult suggestResult, JsonSerializer jsonSerializer) { - accessor.setJsonSerializer(suggestResult, jsonSerializer); - } -} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/implementation/converters/package-info.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/implementation/converters/package-info.java deleted file mode 100644 index a48ed1b16b2b..000000000000 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/implementation/converters/package-info.java +++ /dev/null @@ -1,7 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -/** - * Package containing utility classes that converts generated types to handwritten types. - */ -package com.azure.search.documents.implementation.converters; diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/implementation/models/ErrorAdditionalInfo.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/implementation/models/ErrorAdditionalInfo.java deleted file mode 100644 index 5ce7cecd4142..000000000000 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/implementation/models/ErrorAdditionalInfo.java +++ /dev/null @@ -1,91 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -package com.azure.search.documents.implementation.models; - -import com.azure.core.annotation.Immutable; -import com.azure.json.JsonReader; -import com.azure.json.JsonSerializable; -import com.azure.json.JsonToken; -import com.azure.json.JsonWriter; -import java.io.IOException; - -/** - * The resource management error additional info. - */ -@Immutable -public final class ErrorAdditionalInfo implements JsonSerializable { - /* - * The additional info type. - */ - private String type; - - /* - * The additional info. - */ - private Object info; - - /** - * Creates an instance of ErrorAdditionalInfo class. - */ - public ErrorAdditionalInfo() { - } - - /** - * Get the type property: The additional info type. - * - * @return the type value. - */ - public String getType() { - return this.type; - } - - /** - * Get the info property: The additional info. - * - * @return the info value. - */ - public Object getInfo() { - return this.info; - } - - /** - * {@inheritDoc} - */ - @Override - public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { - jsonWriter.writeStartObject(); - return jsonWriter.writeEndObject(); - } - - /** - * Reads an instance of ErrorAdditionalInfo from the JsonReader. - * - * @param jsonReader The JsonReader being read. - * @return An instance of ErrorAdditionalInfo if the JsonReader was pointing to an instance of it, or null if it was - * pointing to JSON null. - * @throws IOException If an error occurs while reading the ErrorAdditionalInfo. - */ - public static ErrorAdditionalInfo fromJson(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - ErrorAdditionalInfo deserializedErrorAdditionalInfo = new ErrorAdditionalInfo(); - while (reader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = reader.getFieldName(); - reader.nextToken(); - - if ("type".equals(fieldName)) { - deserializedErrorAdditionalInfo.type = reader.getString(); - } else if ("info".equals(fieldName)) { - deserializedErrorAdditionalInfo.info = reader.readUntyped(); - } else { - reader.skipChildren(); - } - } - - return deserializedErrorAdditionalInfo; - }); - } -} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/implementation/models/ErrorDetail.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/implementation/models/ErrorDetail.java deleted file mode 100644 index fdbf7d701f74..000000000000 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/implementation/models/ErrorDetail.java +++ /dev/null @@ -1,143 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -package com.azure.search.documents.implementation.models; - -import com.azure.core.annotation.Immutable; -import com.azure.json.JsonReader; -import com.azure.json.JsonSerializable; -import com.azure.json.JsonToken; -import com.azure.json.JsonWriter; -import java.io.IOException; -import java.util.List; - -/** - * The error detail. - */ -@Immutable -public final class ErrorDetail implements JsonSerializable { - /* - * The error code. - */ - private String code; - - /* - * The error message. - */ - private String message; - - /* - * The error target. - */ - private String target; - - /* - * The error details. - */ - private List details; - - /* - * The error additional info. - */ - private List additionalInfo; - - /** - * Creates an instance of ErrorDetail class. - */ - public ErrorDetail() { - } - - /** - * Get the code property: The error code. - * - * @return the code value. - */ - public String getCode() { - return this.code; - } - - /** - * Get the message property: The error message. - * - * @return the message value. - */ - public String getMessage() { - return this.message; - } - - /** - * Get the target property: The error target. - * - * @return the target value. - */ - public String getTarget() { - return this.target; - } - - /** - * Get the details property: The error details. - * - * @return the details value. - */ - public List getDetails() { - return this.details; - } - - /** - * Get the additionalInfo property: The error additional info. - * - * @return the additionalInfo value. - */ - public List getAdditionalInfo() { - return this.additionalInfo; - } - - /** - * {@inheritDoc} - */ - @Override - public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { - jsonWriter.writeStartObject(); - return jsonWriter.writeEndObject(); - } - - /** - * Reads an instance of ErrorDetail from the JsonReader. - * - * @param jsonReader The JsonReader being read. - * @return An instance of ErrorDetail if the JsonReader was pointing to an instance of it, or null if it was - * pointing to JSON null. - * @throws IOException If an error occurs while reading the ErrorDetail. - */ - public static ErrorDetail fromJson(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - ErrorDetail deserializedErrorDetail = new ErrorDetail(); - while (reader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = reader.getFieldName(); - reader.nextToken(); - - if ("code".equals(fieldName)) { - deserializedErrorDetail.code = reader.getString(); - } else if ("message".equals(fieldName)) { - deserializedErrorDetail.message = reader.getString(); - } else if ("target".equals(fieldName)) { - deserializedErrorDetail.target = reader.getString(); - } else if ("details".equals(fieldName)) { - List details = reader.readArray(reader1 -> ErrorDetail.fromJson(reader1)); - deserializedErrorDetail.details = details; - } else if ("additionalInfo".equals(fieldName)) { - List additionalInfo - = reader.readArray(reader1 -> ErrorAdditionalInfo.fromJson(reader1)); - deserializedErrorDetail.additionalInfo = additionalInfo; - } else { - reader.skipChildren(); - } - } - - return deserializedErrorDetail; - }); - } -} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/implementation/models/ErrorResponse.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/implementation/models/ErrorResponse.java deleted file mode 100644 index 6c4ae87ba463..000000000000 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/implementation/models/ErrorResponse.java +++ /dev/null @@ -1,90 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -package com.azure.search.documents.implementation.models; - -import com.azure.core.annotation.Fluent; -import com.azure.json.JsonReader; -import com.azure.json.JsonSerializable; -import com.azure.json.JsonToken; -import com.azure.json.JsonWriter; -import java.io.IOException; - -/** - * Error response - * - * Common error response for all Azure Resource Manager APIs to return error details for failed operations. (This also - * follows the OData error response format.). - */ -@Fluent -public final class ErrorResponse implements JsonSerializable { - /* - * The error object. - */ - private ErrorDetail error; - - /** - * Creates an instance of ErrorResponse class. - */ - public ErrorResponse() { - } - - /** - * Get the error property: The error object. - * - * @return the error value. - */ - public ErrorDetail getError() { - return this.error; - } - - /** - * Set the error property: The error object. - * - * @param error the error value to set. - * @return the ErrorResponse object itself. - */ - public ErrorResponse setError(ErrorDetail error) { - this.error = error; - return this; - } - - /** - * {@inheritDoc} - */ - @Override - public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { - jsonWriter.writeStartObject(); - jsonWriter.writeJsonField("error", this.error); - return jsonWriter.writeEndObject(); - } - - /** - * Reads an instance of ErrorResponse from the JsonReader. - * - * @param jsonReader The JsonReader being read. - * @return An instance of ErrorResponse if the JsonReader was pointing to an instance of it, or null if it was - * pointing to JSON null. - * @throws IOException If an error occurs while reading the ErrorResponse. - */ - public static ErrorResponse fromJson(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - ErrorResponse deserializedErrorResponse = new ErrorResponse(); - while (reader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = reader.getFieldName(); - reader.nextToken(); - - if ("error".equals(fieldName)) { - deserializedErrorResponse.error = ErrorDetail.fromJson(reader); - } else { - reader.skipChildren(); - } - } - - return deserializedErrorResponse; - }); - } -} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/implementation/models/ErrorResponseException.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/implementation/models/ErrorResponseException.java deleted file mode 100644 index 5dc911f2c3a8..000000000000 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/implementation/models/ErrorResponseException.java +++ /dev/null @@ -1,44 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -package com.azure.search.documents.implementation.models; - -import com.azure.core.exception.HttpResponseException; -import com.azure.core.http.HttpResponse; - -/** - * Exception thrown for an invalid response with ErrorResponse information. - */ -public final class ErrorResponseException extends HttpResponseException { - /** - * Initializes a new instance of the ErrorResponseException class. - * - * @param message the exception message or the response content if a message is not available. - * @param response the HTTP response. - */ - public ErrorResponseException(String message, HttpResponse response) { - super(message, response); - } - - /** - * Initializes a new instance of the ErrorResponseException class. - * - * @param message the exception message or the response content if a message is not available. - * @param response the HTTP response. - * @param value the deserialized response value. - */ - public ErrorResponseException(String message, HttpResponse response, ErrorResponse value) { - super(message, response, value); - } - - /** - * {@inheritDoc} - */ - @Override - public ErrorResponse getValue() { - return (ErrorResponse) super.getValue(); - } -} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/implementation/models/IndexAction.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/implementation/models/IndexAction.java deleted file mode 100644 index eb9e7bb46a24..000000000000 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/implementation/models/IndexAction.java +++ /dev/null @@ -1,149 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. -package com.azure.search.documents.implementation.models; - -import com.azure.core.annotation.Fluent; -import com.azure.json.JsonReader; -import com.azure.json.JsonSerializable; -import com.azure.json.JsonToken; -import com.azure.json.JsonWriter; -import com.azure.search.documents.models.IndexActionType; -import java.io.IOException; -import java.util.LinkedHashMap; -import java.util.Map; - -/** - * Represents an index action that operates on a document. - */ -@Fluent -public final class IndexAction implements JsonSerializable { - - /* - * The operation to perform on a document in an indexing batch. - */ - private IndexActionType actionType; - - /* - * Represents an index action that operates on a document. - */ - private Map additionalProperties; - - /** - * Creates an instance of IndexAction class. - */ - public IndexAction() { - } - - /** - * Get the actionType property: The operation to perform on a document in an indexing batch. - * - * @return the actionType value. - */ - public IndexActionType getActionType() { - return this.actionType; - } - - /** - * Set the actionType property: The operation to perform on a document in an indexing batch. - * - * @param actionType the actionType value to set. - * @return the IndexAction object itself. - */ - public IndexAction setActionType(IndexActionType actionType) { - this.actionType = actionType; - return this; - } - - /** - * Get the additionalProperties property: Represents an index action that operates on a document. - * - * @return the additionalProperties value. - */ - public Map getAdditionalProperties() { - return this.additionalProperties; - } - - /** - * Set the additionalProperties property: Represents an index action that operates on a document. - * - * @param additionalProperties the additionalProperties value to set. - * @return the IndexAction object itself. - */ - public IndexAction setAdditionalProperties(Map additionalProperties) { - this.additionalProperties = additionalProperties; - return this; - } - - /** - * {@inheritDoc} - */ - @Override - public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { - jsonWriter.writeStartObject(); - jsonWriter.writeStringField("@search.action", this.actionType == null ? null : this.actionType.toString()); - if (additionalProperties != null) { - for (Map.Entry additionalProperty : additionalProperties.entrySet()) { - jsonWriter.writeUntypedField(additionalProperty.getKey(), additionalProperty.getValue()); - } - } - return jsonWriter.writeEndObject(); - } - - /** - * Reads an instance of IndexAction from the JsonReader. - * - * @param jsonReader The JsonReader being read. - * @return An instance of IndexAction if the JsonReader was pointing to an instance of it, or null if it was - * pointing to JSON null. - * @throws IOException If an error occurs while reading the IndexAction. - */ - public static IndexAction fromJson(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - IndexAction deserializedIndexAction = new IndexAction(); - Map additionalProperties = null; - while (reader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = reader.getFieldName(); - reader.nextToken(); - if ("@search.action".equals(fieldName)) { - deserializedIndexAction.actionType = IndexActionType.fromString(reader.getString()); - } else { - if (additionalProperties == null) { - additionalProperties = new LinkedHashMap<>(); - } - additionalProperties.put(fieldName, reader.readUntyped()); - } - } - deserializedIndexAction.additionalProperties = additionalProperties; - return deserializedIndexAction; - }); - } - - private String rawDocument; - - /** - * /** - * Gets the raw JSON document. - * - * @return The raw JSON document. - * / - */ - public String getRawDocument() { - return this.rawDocument; - } - - /** - * /** - * Sets the raw JSON document. - * - * @param rawDocument The raw JSON document. - * @return the IndexAction object itself. - * / - */ - public IndexAction setRawDocument(String rawDocument) { - this.rawDocument = rawDocument; - return this; - } -} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/implementation/models/RequestOptions.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/implementation/models/RequestOptions.java deleted file mode 100644 index 63f17fe46a27..000000000000 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/implementation/models/RequestOptions.java +++ /dev/null @@ -1,47 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -package com.azure.search.documents.implementation.models; - -import com.azure.core.annotation.Fluent; -import java.util.UUID; - -/** - * Parameter group. - */ -@Fluent -public final class RequestOptions { - /* - * The tracking ID sent with the request to help with debugging. - */ - private UUID xMsClientRequestId; - - /** - * Creates an instance of RequestOptions class. - */ - public RequestOptions() { - } - - /** - * Get the xMsClientRequestId property: The tracking ID sent with the request to help with debugging. - * - * @return the xMsClientRequestId value. - */ - public UUID getXMsClientRequestId() { - return this.xMsClientRequestId; - } - - /** - * Set the xMsClientRequestId property: The tracking ID sent with the request to help with debugging. - * - * @param xMsClientRequestId the xMsClientRequestId value to set. - * @return the RequestOptions object itself. - */ - public RequestOptions setXMsClientRequestId(UUID xMsClientRequestId) { - this.xMsClientRequestId = xMsClientRequestId; - return this; - } -} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/implementation/models/SearchContinuationToken.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/implementation/models/SearchContinuationToken.java deleted file mode 100644 index ea1eebc39814..000000000000 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/implementation/models/SearchContinuationToken.java +++ /dev/null @@ -1,105 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.search.documents.implementation.models; - -import com.azure.json.JsonProviders; -import com.azure.json.JsonReader; -import com.azure.json.JsonToken; -import com.azure.json.JsonWriter; -import com.azure.search.documents.util.SearchPagedResponse; - -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.UncheckedIOException; -import java.util.Base64; -import java.util.Objects; - -/** - * Serialization and deserialization of search page continuation token. - */ -public final class SearchContinuationToken { - /** - * Api version which is used by continuation token. - */ - public static final String API_VERSION = "apiVersion"; - - /** - * Next link which is used by continuation token. - */ - public static final String NEXT_LINK = "nextLink"; - - /** - * Next page parameters which is used by continuation token. - */ - public static final String NEXT_PAGE_PARAMETERS = "nextPageParameters"; - - private SearchContinuationToken() { - } - - /** - * Serialize to search continuation token using {@code apiVersion}, {@code nextLink} and {@link SearchRequest} - * - * @param apiVersion The api version string. - * @param nextLink The next link from search document result. {@link SearchDocumentsResult} - * @param nextPageParameters {@link SearchRequest} The next page parameters which use to fetch next page. - * @return The search encoded continuation token. - */ - public static String serializeToken(String apiVersion, String nextLink, SearchRequest nextPageParameters) { - Objects.requireNonNull(apiVersion); - if (nextLink == null || nextPageParameters == null || nextPageParameters.getSkip() == null) { - return null; - } - - ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); - try (JsonWriter writer = JsonProviders.createWriter(outputStream)) { - writer.writeStartObject() - .writeStringField(API_VERSION, apiVersion) - .writeStringField(NEXT_LINK, nextLink) - .writeJsonField(NEXT_PAGE_PARAMETERS, nextPageParameters) - .writeEndObject() - .flush(); - - return Base64.getEncoder().encodeToString(outputStream.toByteArray()); - } catch (IOException ex) { - throw new UncheckedIOException(ex); - } - } - - /** - * Deserialize the continuation token to {@link SearchRequest} - * - * @param apiVersion The api version string. - * @param continuationToken The continuation token from {@link SearchPagedResponse} - * @return {@link SearchRequest} The search request used for fetching next page. - */ - public static SearchRequest deserializeToken(String apiVersion, String continuationToken) { - try (JsonReader jsonReader = JsonProviders.createReader(Base64.getDecoder().decode(continuationToken))) { - return jsonReader.readObject(reader -> { - String version = null; - SearchRequest token = null; - - while (reader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = reader.getFieldName(); - reader.nextToken(); - - if (API_VERSION.equals(fieldName)) { - version = reader.getString(); - } else if (NEXT_PAGE_PARAMETERS.equals(fieldName)) { - token = SearchRequest.fromJson(reader); - } else { - reader.skipChildren(); - } - } - - if (!Objects.equals(apiVersion, version)) { - throw new IllegalStateException("Continuation token uses invalid apiVersion" + apiVersion); - } - - return token; - }); - } catch (IOException ex) { - throw new UncheckedIOException(ex); - } - } -} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/implementation/models/SearchError.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/implementation/models/SearchError.java deleted file mode 100644 index 6045d8491d3e..000000000000 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/implementation/models/SearchError.java +++ /dev/null @@ -1,141 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. -package com.azure.search.documents.implementation.models; - -import com.azure.core.annotation.Immutable; -import com.azure.json.JsonReader; -import com.azure.json.JsonSerializable; -import com.azure.json.JsonToken; -import com.azure.json.JsonWriter; -import java.io.IOException; -import java.util.List; - -/** - * Describes an error condition for the API. - */ -@Immutable -public final class SearchError implements JsonSerializable { - - /* - * One of a server-defined set of error codes. - */ - private String code; - - /* - * A human-readable representation of the error. - */ - private final String message; - - /* - * An array of details about specific errors that led to this reported error. - */ - private List details; - - /** - * Creates an instance of SearchError class. - * - * @param message the message value to set. - */ - public SearchError(String message) { - this.message = message; - } - - /** - * Get the code property: One of a server-defined set of error codes. - * - * @return the code value. - */ - public String getCode() { - return this.code; - } - - /** - * Get the message property: A human-readable representation of the error. - * - * @return the message value. - */ - public String getMessage() { - return this.message; - } - - /** - * Get the details property: An array of details about specific errors that led to this reported error. - * - * @return the details value. - */ - public List getDetails() { - return this.details; - } - - @Override - public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { - jsonWriter.writeStartObject(); - return jsonWriter.writeEndObject(); - } - - /** - * Reads an instance of SearchError from the JsonReader. - * - * @param jsonReader The JsonReader being read. - * @return An instance of SearchError if the JsonReader was pointing to an instance of it, or null if it was - * pointing to JSON null. - * @throws IllegalStateException If the deserialized JSON object was missing any required properties. - * @throws IOException If an error occurs while reading the SearchError. - */ - public static SearchError fromJson(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - // Buffer the next JSON object as SearchError can take two forms: - // - // - A SearchError object - // - A SearchError object wrapped in an "error" node. - JsonReader bufferedReader = reader.bufferObject(); - // Get to the START_OBJECT token. - bufferedReader.nextToken(); - while (bufferedReader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = bufferedReader.getFieldName(); - bufferedReader.nextToken(); - if ("error".equals(fieldName)) { - // If the SearchError was wrapped in the "error" node begin reading it now. - return readSearchError(bufferedReader); - } else { - bufferedReader.skipChildren(); - } - } - // Otherwise reset the JsonReader and read the whole JSON object. - return readSearchError(bufferedReader.reset()); - }); - } - - private static SearchError readSearchError(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - boolean messageFound = false; - String message = null; - String code = null; - List details = null; - while (reader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = reader.getFieldName(); - reader.nextToken(); - if ("message".equals(fieldName)) { - message = reader.getString(); - messageFound = true; - } else if ("code".equals(fieldName)) { - code = reader.getString(); - } else if ("details".equals(fieldName)) { - details = reader.readArray(reader1 -> SearchError.fromJson(reader1)); - } else { - reader.skipChildren(); - } - } - if (messageFound) { - SearchError deserializedSearchError = new SearchError(message); - deserializedSearchError.code = code; - deserializedSearchError.details = details; - return deserializedSearchError; - } - throw new IllegalStateException("Missing required property: message"); - }); - } -} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/implementation/models/SearchFirstPageResponseWrapper.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/implementation/models/SearchFirstPageResponseWrapper.java deleted file mode 100644 index 274af8587a4b..000000000000 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/implementation/models/SearchFirstPageResponseWrapper.java +++ /dev/null @@ -1,33 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.search.documents.implementation.models; - -import com.azure.search.documents.util.SearchPagedResponse; - -/** - * This class is a wrapper on first page response from search result. - */ -public class SearchFirstPageResponseWrapper { - private SearchPagedResponse firstPageResponse; - - /** - * Gets the first page response. - * - * @return The first page response. - */ - public SearchPagedResponse getFirstPageResponse() { - return firstPageResponse; - } - - /** - * Sets the first page response. - * - * @param firstPageResponse The first page response. - * @return The {@link SearchFirstPageResponseWrapper} object itself. - */ - public SearchFirstPageResponseWrapper setFirstPageResponse(SearchPagedResponse firstPageResponse) { - this.firstPageResponse = firstPageResponse; - return this; - } -} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/implementation/models/SearchOptions.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/implementation/models/SearchOptions.java deleted file mode 100644 index b71ae2b393e6..000000000000 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/implementation/models/SearchOptions.java +++ /dev/null @@ -1,959 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. -package com.azure.search.documents.implementation.models; - -import com.azure.core.annotation.Fluent; -import com.azure.search.documents.models.QueryDebugMode; -import com.azure.search.documents.models.QueryLanguage; -import com.azure.search.documents.models.QuerySpellerType; -import com.azure.search.documents.models.QueryType; -import com.azure.search.documents.models.ScoringStatistics; -import com.azure.search.documents.models.SearchMode; -import com.azure.search.documents.models.SemanticErrorMode; -import java.util.Arrays; -import java.util.List; - -/** - * Parameter group. - */ -@Fluent -public final class SearchOptions { - - /* - * 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. - */ - private Boolean includeTotalCount; - - /* - * 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. - */ - private List facets; - - /* - * The OData $filter expression to apply to the search query. - */ - private String filter; - - /* - * The list of field names to use for hit highlights. Only searchable fields can be used for hit highlighting. - */ - private List highlightFields; - - /* - * A string tag that is appended to hit highlights. Must be set with highlightPreTag. Default is </em>. - */ - private String highlightPostTag; - - /* - * A string tag that is prepended to hit highlights. Must be set with highlightPostTag. Default is <em>. - */ - private String highlightPreTag; - - /* - * 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. - */ - private Double minimumCoverage; - - /* - * 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. - */ - private List orderBy; - - /* - * A value that specifies the syntax of the search query. The default is 'simple'. Use 'full' if your query uses the - * Lucene query syntax. - */ - private QueryType queryType; - - /* - * 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). - */ - private List scoringParameters; - - /* - * The name of a scoring profile to evaluate match scores for matching documents in order to sort the results. - */ - private String scoringProfile; - - /* - * 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. - */ - private List searchFields; - - /* - * A value that specifies whether any or all of the search terms must be matched in order to count the document as a - * match. - */ - private SearchMode searchMode; - - /* - * 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. - */ - private ScoringStatistics scoringStatistics; - - /* - * 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. - */ - private String sessionId; - - /* - * The list of fields to retrieve. If unspecified, all fields marked as retrievable in the schema are included. - */ - private List select; - - /* - * 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. - */ - private Integer skip; - - /* - * 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. - */ - private Integer top; - - /* - * The name of the semantic configuration that lists which fields should be used for semantic ranking, captions, - * highlights, and answers - */ - private String semanticConfiguration; - - /* - * Allows the user to choose whether a semantic call should fail completely, or to return partial results (default). - */ - private SemanticErrorMode semanticErrorHandling; - - /* - * 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. - */ - private Integer semanticMaxWaitInMilliseconds; - - /* - * 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'. - */ - private String answers; - - /* - * 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'. - */ - private String captions; - - /* - * 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. - */ - private String semanticQuery; - - /* - * 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`. - */ - private String queryRewrites; - - /* - * Enables a debugging tool that can be used to further explore your search results. - */ - private QueryDebugMode debug; - - /* - * The language of the query. - */ - private QueryLanguage queryLanguage; - - /* - * Improve search recall by spell-correcting individual search query terms. - */ - private QuerySpellerType speller; - - /* - * The list of field names used for semantic ranking. - */ - private List semanticFields; - - /** - * Creates an instance of SearchOptions class. - */ - public SearchOptions() { - } - - /** - * Get the includeTotalCount property: 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. - * - * @return the includeTotalCount value. - */ - public Boolean isTotalCountIncluded() { - return this.includeTotalCount; - } - - /** - * Set the includeTotalCount property: 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. - * - * @param includeTotalCount the includeTotalCount value to set. - * @return the SearchOptions object itself. - */ - public SearchOptions setIncludeTotalCount(Boolean includeTotalCount) { - this.includeTotalCount = includeTotalCount; - return this; - } - - /** - * Get the facets property: 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. - * - * @return the facets value. - */ - public List getFacets() { - return this.facets; - } - - /** - * Set the facets property: 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. - * - * @param facets the facets value to set. - * @return the SearchOptions object itself. - */ - public SearchOptions setFacets(List facets) { - this.facets = facets; - return this; - } - - /** - * Get the filter property: The OData $filter expression to apply to the search query. - * - * @return the filter value. - */ - public String getFilter() { - return this.filter; - } - - /** - * Set the filter property: The OData $filter expression to apply to the search query. - * - * @param filter the filter value to set. - * @return the SearchOptions object itself. - */ - public SearchOptions setFilter(String filter) { - this.filter = filter; - return this; - } - - /** - * Get the highlightFields property: The list of field names to use for hit highlights. Only searchable fields can - * be used for hit highlighting. - * - * @return the highlightFields value. - */ - public List getHighlightFields() { - return this.highlightFields; - } - - /** - * Set the highlightFields property: The list of field names to use for hit highlights. Only searchable fields can - * be used for hit highlighting. - * - * @param highlightFields the highlightFields value to set. - * @return the SearchOptions object itself. - */ - public SearchOptions setHighlightFields(List highlightFields) { - this.highlightFields = highlightFields; - return this; - } - - /** - * Get the highlightPostTag property: A string tag that is appended to hit highlights. Must be set with - * highlightPreTag. Default is &lt;/em&gt;. - * - * @return the highlightPostTag value. - */ - public String getHighlightPostTag() { - return this.highlightPostTag; - } - - /** - * Set the highlightPostTag property: A string tag that is appended to hit highlights. Must be set with - * highlightPreTag. Default is &lt;/em&gt;. - * - * @param highlightPostTag the highlightPostTag value to set. - * @return the SearchOptions object itself. - */ - public SearchOptions setHighlightPostTag(String highlightPostTag) { - this.highlightPostTag = highlightPostTag; - return this; - } - - /** - * Get the highlightPreTag property: A string tag that is prepended to hit highlights. Must be set with - * highlightPostTag. Default is &lt;em&gt;. - * - * @return the highlightPreTag value. - */ - public String getHighlightPreTag() { - return this.highlightPreTag; - } - - /** - * Set the highlightPreTag property: A string tag that is prepended to hit highlights. Must be set with - * highlightPostTag. Default is &lt;em&gt;. - * - * @param highlightPreTag the highlightPreTag value to set. - * @return the SearchOptions object itself. - */ - public SearchOptions setHighlightPreTag(String highlightPreTag) { - this.highlightPreTag = highlightPreTag; - return this; - } - - /** - * Get the minimumCoverage property: 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. - * - * @return the minimumCoverage value. - */ - public Double getMinimumCoverage() { - return this.minimumCoverage; - } - - /** - * Set the minimumCoverage property: 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. - * - * @param minimumCoverage the minimumCoverage value to set. - * @return the SearchOptions object itself. - */ - public SearchOptions setMinimumCoverage(Double minimumCoverage) { - this.minimumCoverage = minimumCoverage; - return this; - } - - /** - * Get the orderBy property: 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. - * - * @return the orderBy value. - */ - public List getOrderBy() { - return this.orderBy; - } - - /** - * Set the orderBy property: 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. - * - * @param orderBy the orderBy value to set. - * @return the SearchOptions object itself. - */ - public SearchOptions setOrderBy(List orderBy) { - this.orderBy = orderBy; - return this; - } - - /** - * Get the queryType property: A value that specifies the syntax of the search query. The default is 'simple'. Use - * 'full' if your query uses the Lucene query syntax. - * - * @return the queryType value. - */ - public QueryType getQueryType() { - return this.queryType; - } - - /** - * Set the queryType property: A value that specifies the syntax of the search query. The default is 'simple'. Use - * 'full' if your query uses the Lucene query syntax. - * - * @param queryType the queryType value to set. - * @return the SearchOptions object itself. - */ - public SearchOptions setQueryType(QueryType queryType) { - this.queryType = queryType; - return this; - } - - /** - * Get the scoringParameters property: 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). - * - * @return the scoringParameters value. - */ - public List getScoringParameters() { - return this.scoringParameters; - } - - /** - * Set the scoringParameters property: 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). - * - * @param scoringParameters the scoringParameters value to set. - * @return the SearchOptions object itself. - */ - public SearchOptions setScoringParameters(List scoringParameters) { - this.scoringParameters = scoringParameters; - return this; - } - - /** - * Get the scoringProfile property: The name of a scoring profile to evaluate match scores for matching documents in - * order to sort the results. - * - * @return the scoringProfile value. - */ - public String getScoringProfile() { - return this.scoringProfile; - } - - /** - * Set the scoringProfile property: The name of a scoring profile to evaluate match scores for matching documents in - * order to sort the results. - * - * @param scoringProfile the scoringProfile value to set. - * @return the SearchOptions object itself. - */ - public SearchOptions setScoringProfile(String scoringProfile) { - this.scoringProfile = scoringProfile; - return this; - } - - /** - * Get the searchFields property: 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. - * - * @return the searchFields value. - */ - public List getSearchFields() { - return this.searchFields; - } - - /** - * Set the searchFields property: 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. - * - * @param searchFields the searchFields value to set. - * @return the SearchOptions object itself. - */ - public SearchOptions setSearchFields(List searchFields) { - this.searchFields = searchFields; - return this; - } - - /** - * Get the searchMode property: A value that specifies whether any or all of the search terms must be matched in - * order to count the document as a match. - * - * @return the searchMode value. - */ - public SearchMode getSearchMode() { - return this.searchMode; - } - - /** - * Set the searchMode property: A value that specifies whether any or all of the search terms must be matched in - * order to count the document as a match. - * - * @param searchMode the searchMode value to set. - * @return the SearchOptions object itself. - */ - public SearchOptions setSearchMode(SearchMode searchMode) { - this.searchMode = searchMode; - return this; - } - - /** - * Get the scoringStatistics property: 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. - * - * @return the scoringStatistics value. - */ - public ScoringStatistics getScoringStatistics() { - return this.scoringStatistics; - } - - /** - * Set the scoringStatistics property: 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. - * - * @param scoringStatistics the scoringStatistics value to set. - * @return the SearchOptions object itself. - */ - public SearchOptions setScoringStatistics(ScoringStatistics scoringStatistics) { - this.scoringStatistics = scoringStatistics; - return this; - } - - /** - * Get the sessionId property: 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. - * - * @return the sessionId value. - */ - public String getSessionId() { - return this.sessionId; - } - - /** - * Set the sessionId property: 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. - * - * @param sessionId the sessionId value to set. - * @return the SearchOptions object itself. - */ - public SearchOptions setSessionId(String sessionId) { - this.sessionId = sessionId; - return this; - } - - /** - * Get the select property: The list of fields to retrieve. If unspecified, all fields marked as retrievable in the - * schema are included. - * - * @return the select value. - */ - public List getSelect() { - return this.select; - } - - /** - * Set the select property: The list of fields to retrieve. If unspecified, all fields marked as retrievable in the - * schema are included. - * - * @param select the select value to set. - * @return the SearchOptions object itself. - */ - public SearchOptions setSelect(List select) { - this.select = select; - return this; - } - - /** - * Get the skip property: 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. - * - * @return the skip value. - */ - public Integer getSkip() { - return this.skip; - } - - /** - * Set the skip property: 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. - * - * @param skip the skip value to set. - * @return the SearchOptions object itself. - */ - public SearchOptions setSkip(Integer skip) { - this.skip = skip; - return this; - } - - /** - * Get the top property: 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. - * - * @return the top value. - */ - public Integer getTop() { - return this.top; - } - - /** - * Set the top property: 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. - * - * @param top the top value to set. - * @return the SearchOptions object itself. - */ - public SearchOptions setTop(Integer top) { - this.top = top; - return this; - } - - /** - * Get the semanticConfiguration property: The name of the semantic configuration that lists which fields should be - * used for semantic ranking, captions, highlights, and answers. - * - * @return the semanticConfiguration value. - */ - public String getSemanticConfiguration() { - return this.semanticConfiguration; - } - - /** - * Set the semanticConfiguration property: The name of the semantic configuration that lists which fields should be - * used for semantic ranking, captions, highlights, and answers. - * - * @param semanticConfiguration the semanticConfiguration value to set. - * @return the SearchOptions object itself. - */ - public SearchOptions setSemanticConfiguration(String semanticConfiguration) { - this.semanticConfiguration = semanticConfiguration; - return this; - } - - /** - * Get the semanticErrorHandling property: Allows the user to choose whether a semantic call should fail completely, - * or to return partial results (default). - * - * @return the semanticErrorHandling value. - */ - public SemanticErrorMode getSemanticErrorHandling() { - return this.semanticErrorHandling; - } - - /** - * Set the semanticErrorHandling property: Allows the user to choose whether a semantic call should fail completely, - * or to return partial results (default). - * - * @param semanticErrorHandling the semanticErrorHandling value to set. - * @return the SearchOptions object itself. - */ - public SearchOptions setSemanticErrorHandling(SemanticErrorMode semanticErrorHandling) { - this.semanticErrorHandling = semanticErrorHandling; - return this; - } - - /** - * Get the semanticMaxWaitInMilliseconds property: 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. - * - * @return the semanticMaxWaitInMilliseconds value. - */ - public Integer getSemanticMaxWaitInMilliseconds() { - return this.semanticMaxWaitInMilliseconds; - } - - /** - * Set the semanticMaxWaitInMilliseconds property: 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. - * - * @param semanticMaxWaitInMilliseconds the semanticMaxWaitInMilliseconds value to set. - * @return the SearchOptions object itself. - */ - public SearchOptions setSemanticMaxWaitInMilliseconds(Integer semanticMaxWaitInMilliseconds) { - this.semanticMaxWaitInMilliseconds = semanticMaxWaitInMilliseconds; - return this; - } - - /** - * Get the answers property: 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-<number of answers>` 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-<confidence 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-<number of maximum character length>', such as 'extractive|maxcharlength-600'. - * - * @return the answers value. - */ - public String getAnswers() { - return this.answers; - } - - /** - * Set the answers property: 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-<number of answers>` 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-<confidence 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-<number of maximum character length>', such as 'extractive|maxcharlength-600'. - * - * @param answers the answers value to set. - * @return the SearchOptions object itself. - */ - public SearchOptions setAnswers(String answers) { - this.answers = answers; - return this; - } - - /** - * Get the captions property: 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-<true/false>` 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-<number of maximum character length>', such as 'extractive|maxcharlength-600'. - * - * @return the captions value. - */ - public String getCaptions() { - return this.captions; - } - - /** - * Set the captions property: 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-<true/false>` 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-<number of maximum character length>', such as 'extractive|maxcharlength-600'. - * - * @param captions the captions value to set. - * @return the SearchOptions object itself. - */ - public SearchOptions setCaptions(String captions) { - this.captions = captions; - return this; - } - - /** - * Get the semanticQuery property: 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. - * - * @return the semanticQuery value. - */ - public String getSemanticQuery() { - return this.semanticQuery; - } - - /** - * Set the semanticQuery property: 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. - * - * @param semanticQuery the semanticQuery value to set. - * @return the SearchOptions object itself. - */ - public SearchOptions setSemanticQuery(String semanticQuery) { - this.semanticQuery = semanticQuery; - return this; - } - - /** - * Get the queryRewrites property: 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-<number of rewrites>` option, - * such as `generative|count-3`. Defaults to `None`. This parameter is only valid if the query type is `semantic`. - * - * @return the queryRewrites value. - */ - public String getQueryRewrites() { - return this.queryRewrites; - } - - /** - * Set the queryRewrites property: 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-<number of rewrites>` option, - * such as `generative|count-3`. Defaults to `None`. This parameter is only valid if the query type is `semantic`. - * - * @param queryRewrites the queryRewrites value to set. - * @return the SearchOptions object itself. - */ - public SearchOptions setQueryRewrites(String queryRewrites) { - this.queryRewrites = queryRewrites; - return this; - } - - /** - * Get the debug property: Enables a debugging tool that can be used to further explore your search results. - * - * @return the debug value. - */ - public QueryDebugMode getDebug() { - return this.debug; - } - - /** - * Set the debug property: Enables a debugging tool that can be used to further explore your search results. - * - * @param debug the debug value to set. - * @return the SearchOptions object itself. - */ - public SearchOptions setDebug(QueryDebugMode debug) { - this.debug = debug; - return this; - } - - /** - * Get the queryLanguage property: The language of the query. - * - * @return the queryLanguage value. - */ - public QueryLanguage getQueryLanguage() { - return this.queryLanguage; - } - - /** - * Set the queryLanguage property: The language of the query. - * - * @param queryLanguage the queryLanguage value to set. - * @return the SearchOptions object itself. - */ - public SearchOptions setQueryLanguage(QueryLanguage queryLanguage) { - this.queryLanguage = queryLanguage; - return this; - } - - /** - * Get the speller property: Improve search recall by spell-correcting individual search query terms. - * - * @return the speller value. - */ - public QuerySpellerType getSpeller() { - return this.speller; - } - - /** - * Set the speller property: Improve search recall by spell-correcting individual search query terms. - * - * @param speller the speller value to set. - * @return the SearchOptions object itself. - */ - public SearchOptions setSpeller(QuerySpellerType speller) { - this.speller = speller; - return this; - } - - /** - * Get the semanticFields property: The list of field names used for semantic ranking. - * - * @return the semanticFields value. - */ - public List getSemanticFields() { - return this.semanticFields; - } - - /** - * Set the semanticFields property: The list of field names used for semantic ranking. - * - * @param semanticFields the semanticFields value to set. - * @return the SearchOptions object itself. - */ - public SearchOptions setSemanticFields(List semanticFields) { - this.semanticFields = semanticFields; - return this; - } - - /** - * Set the facets property: 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. - * - * @param facets the facets value to set. - * @return the SearchOptions object itself. - */ - public SearchOptions setFacets(String... facets) { - this.facets = (facets == null) ? null : Arrays.asList(facets); - return this; - } - - /** - * Set the orderBy property: 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. - * - * @param orderBy the orderBy value to set. - * @return the SearchOptions object itself. - */ - public SearchOptions setOrderBy(String... orderBy) { - this.orderBy = (orderBy == null) ? null : Arrays.asList(orderBy); - return this; - } - - /** - * Set the searchFields property: 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. - * - * @param searchFields the searchFields value to set. - * @return the SearchOptions object itself. - */ - public SearchOptions setSearchFields(String... searchFields) { - this.searchFields = (searchFields == null) ? null : Arrays.asList(searchFields); - return this; - } - - /** - * Set the select property: The list of fields to retrieve. If unspecified, all fields marked as retrievable in the - * schema are included. - * - * @param select the select value to set. - * @return the SearchOptions object itself. - */ - public SearchOptions setSelect(String... select) { - this.select = (select == null) ? null : Arrays.asList(select); - return this; - } - - /** - * Set the highlightFields property: The list of field names to use for hit highlights. Only searchable fields can - * be used for hit highlighting. - * - * @param highlightFields the highlightFields value to set. - * @return the SearchOptions object itself. - */ - public SearchOptions setHighlightFields(String... highlightFields) { - this.highlightFields = (highlightFields == null) ? null : Arrays.asList(highlightFields); - return this; - } -} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/implementation/models/SearchResult.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/implementation/models/SearchResult.java deleted file mode 100644 index 8fc8485eedd9..000000000000 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/implementation/models/SearchResult.java +++ /dev/null @@ -1,206 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -package com.azure.search.documents.implementation.models; - -import com.azure.core.annotation.Fluent; -import com.azure.json.JsonReader; -import com.azure.json.JsonSerializable; -import com.azure.json.JsonToken; -import com.azure.json.JsonWriter; -import com.azure.search.documents.models.DocumentDebugInfo; -import com.azure.search.documents.models.QueryCaptionResult; -import java.io.IOException; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; - -/** - * Contains a document found by a search query, plus associated metadata. - */ -@Fluent -public final class SearchResult implements JsonSerializable { - /* - * The relevance score of the document compared to other documents returned by the query. - */ - private final double 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'. - */ - private Double rerankerScore; - - /* - * 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. - */ - private Map> highlights; - - /* - * 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'. - */ - private List captions; - - /* - * Contains debugging information that can be used to further explore your search results. - */ - private DocumentDebugInfo documentDebugInfo; - - /* - * Contains a document found by a search query, plus associated metadata. - */ - private Map additionalProperties; - - /** - * Creates an instance of SearchResult class. - * - * @param score the score value to set. - */ - public SearchResult(double score) { - this.score = score; - } - - /** - * Get the score property: The relevance score of the document compared to other documents returned by the query. - * - * @return the score value. - */ - public double getScore() { - return this.score; - } - - /** - * Get the rerankerScore property: 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'. - * - * @return the rerankerScore value. - */ - public Double getRerankerScore() { - return this.rerankerScore; - } - - /** - * Get the highlights property: 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. - * - * @return the highlights value. - */ - public Map> getHighlights() { - return this.highlights; - } - - /** - * Get the captions property: 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'. - * - * @return the captions value. - */ - public List getCaptions() { - return this.captions; - } - - /** - * Get the documentDebugInfo property: Contains debugging information that can be used to further explore your - * search results. - * - * @return the documentDebugInfo value. - */ - public DocumentDebugInfo getDocumentDebugInfo() { - return this.documentDebugInfo; - } - - /** - * Get the additionalProperties property: Contains a document found by a search query, plus associated metadata. - * - * @return the additionalProperties value. - */ - public Map getAdditionalProperties() { - return this.additionalProperties; - } - - /** - * Set the additionalProperties property: Contains a document found by a search query, plus associated metadata. - * - * @param additionalProperties the additionalProperties value to set. - * @return the SearchResult object itself. - */ - public SearchResult setAdditionalProperties(Map additionalProperties) { - this.additionalProperties = additionalProperties; - return this; - } - - /** - * {@inheritDoc} - */ - @Override - public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { - jsonWriter.writeStartObject(); - if (additionalProperties != null) { - for (Map.Entry additionalProperty : additionalProperties.entrySet()) { - jsonWriter.writeUntypedField(additionalProperty.getKey(), additionalProperty.getValue()); - } - } - return jsonWriter.writeEndObject(); - } - - /** - * Reads an instance of SearchResult from the JsonReader. - * - * @param jsonReader The JsonReader being read. - * @return An instance of SearchResult if the JsonReader was pointing to an instance of it, or null if it was - * pointing to JSON null. - * @throws IllegalStateException If the deserialized JSON object was missing any required properties. - * @throws IOException If an error occurs while reading the SearchResult. - */ - public static SearchResult fromJson(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - boolean scoreFound = false; - double score = 0.0; - Double rerankerScore = null; - Map> highlights = null; - List captions = null; - DocumentDebugInfo documentDebugInfo = null; - Map additionalProperties = null; - while (reader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = reader.getFieldName(); - reader.nextToken(); - - if ("@search.score".equals(fieldName)) { - score = reader.getDouble(); - scoreFound = true; - } else if ("@search.rerankerScore".equals(fieldName)) { - rerankerScore = reader.getNullable(JsonReader::getDouble); - } else if ("@search.highlights".equals(fieldName)) { - highlights = reader.readMap(reader1 -> reader1.readArray(reader2 -> reader2.getString())); - } else if ("@search.captions".equals(fieldName)) { - captions = reader.readArray(reader1 -> QueryCaptionResult.fromJson(reader1)); - } else if ("@search.documentDebugInfo".equals(fieldName)) { - documentDebugInfo = DocumentDebugInfo.fromJson(reader); - } else { - if (additionalProperties == null) { - additionalProperties = new LinkedHashMap<>(); - } - - additionalProperties.put(fieldName, reader.readUntyped()); - } - } - if (scoreFound) { - SearchResult deserializedSearchResult = new SearchResult(score); - deserializedSearchResult.rerankerScore = rerankerScore; - deserializedSearchResult.highlights = highlights; - deserializedSearchResult.captions = captions; - deserializedSearchResult.documentDebugInfo = documentDebugInfo; - deserializedSearchResult.additionalProperties = additionalProperties; - - return deserializedSearchResult; - } - throw new IllegalStateException("Missing required property: @search.score"); - }); - } -} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/implementation/models/Speller.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/implementation/models/Speller.java deleted file mode 100644 index c489094f84f2..000000000000 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/implementation/models/Speller.java +++ /dev/null @@ -1,54 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -package com.azure.search.documents.implementation.models; - -import com.azure.core.util.ExpandableStringEnum; -import java.util.Collection; - -/** - * Defines values for Speller. - */ -public final class Speller extends ExpandableStringEnum { - /** - * Speller not enabled. - */ - public static final Speller NONE = fromString("none"); - - /** - * Speller corrects individual query terms using a static lexicon for the language specified by the queryLanguage - * parameter. - */ - public static final Speller LEXICON = fromString("lexicon"); - - /** - * Creates a new instance of Speller value. - * - * @deprecated Use the {@link #fromString(String)} factory method. - */ - @Deprecated - public Speller() { - } - - /** - * Creates or finds a Speller from its string representation. - * - * @param name a name to look for. - * @return the corresponding Speller. - */ - public static Speller fromString(String name) { - return fromString(name, Speller.class); - } - - /** - * Gets known Speller values. - * - * @return known Speller values. - */ - public static Collection values() { - return values(Speller.class); - } -} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/implementation/models/SuggestResult.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/implementation/models/SuggestResult.java deleted file mode 100644 index 2a24fa01fec9..000000000000 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/implementation/models/SuggestResult.java +++ /dev/null @@ -1,125 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -package com.azure.search.documents.implementation.models; - -import com.azure.core.annotation.Fluent; -import com.azure.json.JsonReader; -import com.azure.json.JsonSerializable; -import com.azure.json.JsonToken; -import com.azure.json.JsonWriter; -import java.io.IOException; -import java.util.LinkedHashMap; -import java.util.Map; - -/** - * A result containing a document found by a suggestion query, plus associated metadata. - */ -@Fluent -public final class SuggestResult implements JsonSerializable { - /* - * The text of the suggestion result. - */ - private final String text; - - /* - * A result containing a document found by a suggestion query, plus associated metadata. - */ - private Map additionalProperties; - - /** - * Creates an instance of SuggestResult class. - * - * @param text the text value to set. - */ - public SuggestResult(String text) { - this.text = text; - } - - /** - * Get the text property: The text of the suggestion result. - * - * @return the text value. - */ - public String getText() { - return this.text; - } - - /** - * Get the additionalProperties property: A result containing a document found by a suggestion query, plus - * associated metadata. - * - * @return the additionalProperties value. - */ - public Map getAdditionalProperties() { - return this.additionalProperties; - } - - /** - * Set the additionalProperties property: A result containing a document found by a suggestion query, plus - * associated metadata. - * - * @param additionalProperties the additionalProperties value to set. - * @return the SuggestResult object itself. - */ - public SuggestResult setAdditionalProperties(Map additionalProperties) { - this.additionalProperties = additionalProperties; - return this; - } - - /** - * {@inheritDoc} - */ - @Override - public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { - jsonWriter.writeStartObject(); - if (additionalProperties != null) { - for (Map.Entry additionalProperty : additionalProperties.entrySet()) { - jsonWriter.writeUntypedField(additionalProperty.getKey(), additionalProperty.getValue()); - } - } - return jsonWriter.writeEndObject(); - } - - /** - * Reads an instance of SuggestResult from the JsonReader. - * - * @param jsonReader The JsonReader being read. - * @return An instance of SuggestResult if the JsonReader was pointing to an instance of it, or null if it was - * pointing to JSON null. - * @throws IllegalStateException If the deserialized JSON object was missing any required properties. - * @throws IOException If an error occurs while reading the SuggestResult. - */ - public static SuggestResult fromJson(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - boolean textFound = false; - String text = null; - Map additionalProperties = null; - while (reader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = reader.getFieldName(); - reader.nextToken(); - - if ("@search.text".equals(fieldName)) { - text = reader.getString(); - textFound = true; - } else { - if (additionalProperties == null) { - additionalProperties = new LinkedHashMap<>(); - } - - additionalProperties.put(fieldName, reader.readUntyped()); - } - } - if (textFound) { - SuggestResult deserializedSuggestResult = new SuggestResult(text); - deserializedSuggestResult.additionalProperties = additionalProperties; - - return deserializedSuggestResult; - } - throw new IllegalStateException("Missing required property: @search.text"); - }); - } -} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/implementation/models/package-info.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/implementation/models/package-info.java deleted file mode 100644 index 6909eb5abf62..000000000000 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/implementation/models/package-info.java +++ /dev/null @@ -1,11 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -/** - * Package containing the data models for SearchIndexClient. - * Client that can be used to query an index and upload, merge, or delete documents. - */ -package com.azure.search.documents.implementation.models; diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/implementation/package-info.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/implementation/package-info.java index 4a4b3d694fd4..9d11ae7e1aa4 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/implementation/package-info.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/implementation/package-info.java @@ -1,11 +1,10 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) TypeSpec Code Generator. /** - * Package containing the implementations for SearchIndexClient. - * Client that can be used to query an index and upload, merge, or delete documents. + * Package containing the implementations for Search. + * Client that can be used to manage and query indexes and documents, as well as + * manage other resources, on a search service. */ package com.azure.search.documents.implementation; diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/implementation/util/Constants.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/implementation/util/Constants.java deleted file mode 100644 index 68e43ed506d4..000000000000 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/implementation/util/Constants.java +++ /dev/null @@ -1,38 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.search.documents.implementation.util; - -import com.azure.core.http.policy.HttpLogOptions; - -import java.util.function.Supplier; - -public class Constants { - public static final Supplier DEFAULT_LOG_OPTIONS_SUPPLIER = () -> { - HttpLogOptions logOptions = new HttpLogOptions(); - - logOptions.addAllowedHeaderName("Access-Control-Allow-Credentials"); - logOptions.addAllowedHeaderName("Access-Control-Allow-Headers"); - logOptions.addAllowedHeaderName("Access-Control-Allow-Methods"); - logOptions.addAllowedHeaderName("Access-Control-Allow-Origin"); - logOptions.addAllowedHeaderName("Access-Control-Expose-Headers"); - logOptions.addAllowedHeaderName("Access-Control-Max-Age"); - logOptions.addAllowedHeaderName("Access-Control-Request-Headers"); - logOptions.addAllowedHeaderName("Access-Control-Request-Method"); - logOptions.addAllowedHeaderName("client-request-id"); - logOptions.addAllowedHeaderName("elapsed-time"); - logOptions.addAllowedHeaderName("Location"); - logOptions.addAllowedHeaderName("OData-MaxVersion"); - logOptions.addAllowedHeaderName("OData-Version"); - logOptions.addAllowedHeaderName("Origin"); - logOptions.addAllowedHeaderName("Prefer"); - logOptions.addAllowedHeaderName("request-id"); - logOptions.addAllowedHeaderName("return-client-request-id"); - logOptions.addAllowedHeaderName("throttle-reason"); - - logOptions.addAllowedQueryParamName("api-version"); - logOptions.addAllowedQueryParamName("allowIndexDowntime"); - - return logOptions; - }; -} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/implementation/util/FieldBuilder.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/implementation/util/FieldBuilder.java deleted file mode 100644 index bad235ad4e31..000000000000 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/implementation/util/FieldBuilder.java +++ /dev/null @@ -1,437 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.search.documents.implementation.util; - -import com.azure.core.models.GeoPoint; -import com.azure.core.util.CoreUtils; -import com.azure.core.util.logging.ClientLogger; -import com.azure.core.util.serializer.JsonSerializer; -import com.azure.core.util.serializer.MemberNameConverter; -import com.azure.core.util.serializer.MemberNameConverterProviders; -import com.azure.core.util.serializer.ObjectSerializer; -import com.azure.search.documents.indexes.FieldBuilderIgnore; -import com.azure.search.documents.indexes.SearchableField; -import com.azure.search.documents.indexes.SimpleField; -import com.azure.search.documents.indexes.models.FieldBuilderOptions; -import com.azure.search.documents.indexes.models.LexicalAnalyzerName; -import com.azure.search.documents.indexes.models.SearchField; -import com.azure.search.documents.indexes.models.SearchFieldDataType; -import com.azure.search.documents.indexes.models.VectorEncodingFormat; -import reactor.util.annotation.Nullable; - -import java.lang.annotation.Annotation; -import java.lang.reflect.Field; -import java.lang.reflect.Member; -import java.lang.reflect.Method; -import java.lang.reflect.ParameterizedType; -import java.lang.reflect.Type; -import java.time.OffsetDateTime; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Date; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Objects; -import java.util.Set; -import java.util.Stack; -import java.util.stream.Collectors; -import java.util.stream.Stream; - -/** - * Helper to convert model class to Search {@link SearchField fields}. - *

- * {@link FieldBuilder} currently only read fields of Java model class. If passed a custom {@link ObjectSerializer} in - * API, please remember the helper class is only able to read the rename annotation on the field instead of - * getter/setter methods. - */ -public final class FieldBuilder { - private static final ClientLogger LOGGER = new ClientLogger(FieldBuilder.class); - - private static final int MAX_DEPTH = 10000; - private static final Map SUPPORTED_NONE_PARAMETERIZED_TYPE = new HashMap<>(); - private static final Set UNSUPPORTED_TYPES = new HashSet<>(); - private static final Set UNSUPPORTED_SERVICE_TYPES = new HashSet<>(); - - private static final SearchFieldDataType COLLECTION_STRING - = SearchFieldDataType.collection(SearchFieldDataType.STRING); - private static final SearchFieldDataType COLLECTION_SINGLE - = SearchFieldDataType.collection(SearchFieldDataType.SINGLE); - - static { - SUPPORTED_NONE_PARAMETERIZED_TYPE.put(Integer.class, SearchFieldDataType.INT32); - SUPPORTED_NONE_PARAMETERIZED_TYPE.put(int.class, SearchFieldDataType.INT32); - SUPPORTED_NONE_PARAMETERIZED_TYPE.put(Long.class, SearchFieldDataType.INT64); - SUPPORTED_NONE_PARAMETERIZED_TYPE.put(long.class, SearchFieldDataType.INT64); - SUPPORTED_NONE_PARAMETERIZED_TYPE.put(Double.class, SearchFieldDataType.DOUBLE); - SUPPORTED_NONE_PARAMETERIZED_TYPE.put(double.class, SearchFieldDataType.DOUBLE); - SUPPORTED_NONE_PARAMETERIZED_TYPE.put(Boolean.class, SearchFieldDataType.BOOLEAN); - SUPPORTED_NONE_PARAMETERIZED_TYPE.put(boolean.class, SearchFieldDataType.BOOLEAN); - SUPPORTED_NONE_PARAMETERIZED_TYPE.put(String.class, SearchFieldDataType.STRING); - SUPPORTED_NONE_PARAMETERIZED_TYPE.put(CharSequence.class, SearchFieldDataType.STRING); - SUPPORTED_NONE_PARAMETERIZED_TYPE.put(Character.class, SearchFieldDataType.STRING); - SUPPORTED_NONE_PARAMETERIZED_TYPE.put(char.class, SearchFieldDataType.STRING); - //noinspection UseOfObsoleteDateTimeApi - SUPPORTED_NONE_PARAMETERIZED_TYPE.put(Date.class, SearchFieldDataType.DATE_TIME_OFFSET); - SUPPORTED_NONE_PARAMETERIZED_TYPE.put(OffsetDateTime.class, SearchFieldDataType.DATE_TIME_OFFSET); - SUPPORTED_NONE_PARAMETERIZED_TYPE.put(GeoPoint.class, SearchFieldDataType.GEOGRAPHY_POINT); - SUPPORTED_NONE_PARAMETERIZED_TYPE.put(Float.class, SearchFieldDataType.SINGLE); - SUPPORTED_NONE_PARAMETERIZED_TYPE.put(float.class, SearchFieldDataType.SINGLE); - SUPPORTED_NONE_PARAMETERIZED_TYPE.put(byte.class, SearchFieldDataType.SBYTE); - SUPPORTED_NONE_PARAMETERIZED_TYPE.put(Byte.class, SearchFieldDataType.SBYTE); - SUPPORTED_NONE_PARAMETERIZED_TYPE.put(short.class, SearchFieldDataType.INT16); - SUPPORTED_NONE_PARAMETERIZED_TYPE.put(Short.class, SearchFieldDataType.INT16); - UNSUPPORTED_SERVICE_TYPES.add(SearchFieldDataType.BYTE); - } - - /** - * Creates a collection of {@link SearchField} objects corresponding to the properties of the type supplied. - * - * @param modelClass The class for which fields will be created, based on its properties. - * @param options Configuration used to determine generation of the {@link SearchField SearchFields}. - * @param The generic type of the model class. - * @return A collection of fields. - */ - public static List build(Class modelClass, FieldBuilderOptions options) { - MemberNameConverter converter; - if (options == null || options.getJsonSerializer() == null) { - converter = MemberNameConverterProviders.createInstance(); - } else { - JsonSerializer serializer = options.getJsonSerializer(); - if (serializer instanceof MemberNameConverter) { - converter = (MemberNameConverter) serializer; - } else { - converter = MemberNameConverterProviders.createInstance(); - } - } - - return build(modelClass, new Stack<>(), converter); - } - - /** - * Recursive class to build complex data type. - * - * @param currentClass Current class to be built. - * @param classChain A class chain from {@code modelClass} to prior of {@code currentClass}. - * @return A list of {@link SearchField} that currentClass is built to. - */ - private static List build(Class currentClass, Stack> classChain, - MemberNameConverter serializer) { - if (classChain.contains(currentClass)) { - LOGGER.warning("There is circular dependencies {}, {}", classChain, currentClass); - return null; - } - - if (classChain.size() > MAX_DEPTH) { - throw LOGGER.logExceptionAsError( - new RuntimeException("The dependency graph is too deep. Please review your schema.")); - } - - classChain.push(currentClass); - List searchFields - = getDeclaredFieldsAndMethods(currentClass).filter(FieldBuilder::fieldOrMethodIgnored) - .map(classField -> buildSearchField(classField, classChain, serializer)) - .filter(Objects::nonNull) - .collect(Collectors.toList()); - classChain.pop(); - return searchFields; - } - - /* - * Retrieves all declared fields and methods from the passed Class. - */ - private static Stream getDeclaredFieldsAndMethods(Class model) { - List fieldsAndMethods = new ArrayList<>(Arrays.asList(model.getDeclaredFields())); - fieldsAndMethods.addAll(Arrays.asList(model.getDeclaredMethods())); - - return fieldsAndMethods.stream(); - } - - /* - * Indicates if the Member, should be a Field or Method, is annotated with FieldBuilderIgnore indicating that it - * shouldn't have a SearchField created for it. - */ - private static boolean fieldOrMethodIgnored(Member member) { - if (member instanceof Field) { - return !((Field) member).isAnnotationPresent(FieldBuilderIgnore.class); - } else if (member instanceof Method) { - return !((Method) member).isAnnotationPresent(FieldBuilderIgnore.class); - } else { - return false; - } - } - - private static SearchField buildSearchField(Member member, Stack> classChain, - MemberNameConverter serializer) { - String fieldName = serializer.convertMemberName(member); - if (fieldName == null) { - return null; - } - - Type type = getFieldOrMethodReturnType(member); - if (SUPPORTED_NONE_PARAMETERIZED_TYPE.containsKey(type)) { - return buildNoneParameterizedType(fieldName, member, type); - } - - if (isArrayOrList(type)) { - return buildCollectionField(fieldName, member, type, classChain, serializer); - } - - return getSearchField(type, classChain, serializer, fieldName, (Class) type); - } - - private static Type getFieldOrMethodReturnType(Member member) { - if (member instanceof Field) { - return ((Field) member).getGenericType(); - } else if (member instanceof Method) { - return ((Method) member).getGenericReturnType(); - } else { - throw LOGGER.logExceptionAsError(new IllegalStateException("Member isn't instance of Field or Method.")); - } - } - - @Nullable - private static SearchField getSearchField(Type type, Stack> classChain, MemberNameConverter serializer, - String fieldName, Class clazz) { - SearchField searchField = convertToBasicSearchField(fieldName, type); - if (searchField == null) { - return null; - } - - return searchField.setFields(build(clazz, classChain, serializer)); - } - - private static SearchField buildNoneParameterizedType(String fieldName, Member member, Type type) { - SearchField searchField = convertToBasicSearchField(fieldName, type); - - return (searchField == null) ? null : enrichWithAnnotation(searchField, member); - } - - private static boolean isArrayOrList(Type type) { - return isList(type) || ((Class) type).isArray(); - } - - private static boolean isList(Type type) { - if (!(type instanceof ParameterizedType)) { - return false; - } - - Type rawType = ((ParameterizedType) type).getRawType(); - - return List.class.isAssignableFrom((Class) rawType); - } - - private static SearchField buildCollectionField(String fieldName, Member member, Type type, - Stack> classChain, MemberNameConverter serializer) { - Type componentOrElementType = getComponentOrElementType(type); - - validateType(componentOrElementType, true); - if (SUPPORTED_NONE_PARAMETERIZED_TYPE.containsKey(componentOrElementType)) { - SearchField searchField = convertToBasicSearchField(fieldName, type); - if (searchField == null) { - return null; - } - return enrichWithAnnotation(searchField, member); - } - return getSearchField(type, classChain, serializer, fieldName, (Class) componentOrElementType); - } - - private static Type getComponentOrElementType(Type arrayOrListType) { - if (isList(arrayOrListType)) { - ParameterizedType pt = (ParameterizedType) arrayOrListType; - return pt.getActualTypeArguments()[0]; - } - - if (((Class) arrayOrListType).isArray()) { - return ((Class) arrayOrListType).getComponentType(); - } - - throw LOGGER - .logExceptionAsError(new RuntimeException("Collection type '" + arrayOrListType + "' is not supported.")); - } - - private static SearchField convertToBasicSearchField(String fieldName, Type type) { - SearchFieldDataType dataType = covertToSearchFieldDataType(type, false); - - return (dataType == null) ? null : new SearchField(fieldName, dataType); - } - - private static SearchField enrichWithAnnotation(SearchField searchField, Member member) { - SimpleField simpleField = getDeclaredAnnotation(member, SimpleField.class); - SearchableField searchableField = getDeclaredAnnotation(member, SearchableField.class); - - if (simpleField != null && searchableField != null) { - throw LOGGER.logExceptionAsError(new IllegalArgumentException( - "@SimpleField and @SearchableField cannot be present simultaneously for " + member.getName())); - } - - if (simpleField == null && searchableField == null) { - return searchField; - } - - boolean key; - boolean hidden; - boolean filterable; - boolean sortable; - boolean facetable; - boolean stored; - boolean searchable = searchableField != null; - String analyzerName = null; - String searchAnalyzerName = null; - String indexAnalyzerName = null; - String[] synonymMapNames = null; - Integer vectorSearchDimensions = null; - String vectorSearchProfileName = null; - String vectorEncodingFormat = null; - - if (simpleField != null) { - key = simpleField.isKey(); - hidden = simpleField.isHidden(); - stored = true; - filterable = simpleField.isFilterable(); - sortable = simpleField.isSortable(); - facetable = simpleField.isFacetable(); - } else { - key = searchableField.isKey(); - hidden = searchableField.isHidden(); - stored = searchableField.isStored(); - filterable = searchableField.isFilterable(); - sortable = searchableField.isSortable(); - facetable = searchableField.isFacetable(); - analyzerName = searchableField.analyzerName(); - searchAnalyzerName = searchableField.searchAnalyzerName(); - indexAnalyzerName = searchableField.indexAnalyzerName(); - synonymMapNames = searchableField.synonymMapNames(); - vectorSearchDimensions - = searchableField.vectorSearchDimensions() > 0 ? searchableField.vectorSearchDimensions() : null; - vectorSearchProfileName = CoreUtils.isNullOrEmpty(searchableField.vectorSearchProfileName()) - ? null - : searchableField.vectorSearchProfileName(); - vectorEncodingFormat = CoreUtils.isNullOrEmpty(searchableField.vectorEncodingFormat()) - ? null - : searchableField.vectorEncodingFormat(); - } - - StringBuilder errorMessage = new StringBuilder(); - boolean isStringOrCollectionString - = searchField.getType() == SearchFieldDataType.STRING || searchField.getType() == COLLECTION_STRING; - boolean isSearchableType = isStringOrCollectionString || searchField.getType() == COLLECTION_SINGLE; - boolean hasAnalyzerName = !CoreUtils.isNullOrEmpty(analyzerName); - boolean hasSearchAnalyzerName = !CoreUtils.isNullOrEmpty(searchAnalyzerName); - boolean hasIndexAnalyzerName = !CoreUtils.isNullOrEmpty(indexAnalyzerName); - boolean hasVectorEncodingFormat = !CoreUtils.isNullOrEmpty(vectorEncodingFormat); - if (searchable) { - if (!isSearchableType) { - errorMessage - .append("SearchField can only be used on 'Edm.String', 'Collection(Edm.String)', or " - + "'Collection(Edm.Single)' types. Property '") - .append(member.getName()) - .append("' returns a '") - .append(searchField.getType()) - .append("' value. "); - } - - // Searchable fields are allowed to have either no analyzer names configure or one of the following - // analyzerName is set and searchAnalyzerName and indexAnalyzerName are not set - // searchAnalyzerName and indexAnalyzerName are set and analyzerName is not set - if ((!hasAnalyzerName && (hasSearchAnalyzerName != hasIndexAnalyzerName)) - || (hasAnalyzerName && (hasSearchAnalyzerName || hasIndexAnalyzerName))) { - errorMessage.append("Please specify either analyzer or both searchAnalyzer and indexAnalyzer. "); - } - } - - if (searchField.getType() == COLLECTION_SINGLE - && (vectorSearchDimensions == null || vectorSearchProfileName == null)) { - errorMessage.append( - "Please specify both vectorSearchDimensions and vectorSearchProfileName for Collection(Edm.Single) type. "); - } - - if (errorMessage.length() > 0) { - throw LOGGER.logExceptionAsError(new RuntimeException(errorMessage.toString())); - } - - searchField.setKey(key) - .setHidden(hidden) - .setSearchable(searchable) - .setFilterable(filterable) - .setSortable(sortable) - .setFacetable(facetable) - .setStored(stored) - .setVectorSearchDimensions(vectorSearchDimensions) - .setVectorSearchProfileName(vectorSearchProfileName); - - if (hasAnalyzerName) { - searchField.setAnalyzerName(LexicalAnalyzerName.fromString(analyzerName)); - } else if (hasSearchAnalyzerName || hasIndexAnalyzerName) { - searchField.setSearchAnalyzerName(LexicalAnalyzerName.fromString(searchAnalyzerName)); - searchField.setIndexAnalyzerName(LexicalAnalyzerName.fromString(indexAnalyzerName)); - } - - if (hasVectorEncodingFormat) { - searchField.setVectorEncodingFormat(VectorEncodingFormat.fromString(vectorEncodingFormat)); - } - - if (!CoreUtils.isNullOrEmpty(synonymMapNames)) { - List synonymMaps = Arrays.stream(searchableField.synonymMapNames()) - .filter(synonym -> !synonym.trim().isEmpty()) - .collect(Collectors.toList()); - searchField.setSynonymMapNames(synonymMaps); - } - - return searchField; - } - - private static T getDeclaredAnnotation(Member member, Class annotationType) { - if (member instanceof Field) { - return ((Field) member).getAnnotation(annotationType); - } else if (member instanceof Method) { - return ((Method) member).getAnnotation(annotationType); - } else { - return null; - } - } - - private static void validateType(Type type, boolean hasArrayOrCollectionWrapped) { - if (!(type instanceof ParameterizedType)) { - if (UNSUPPORTED_TYPES.contains(type)) { - throw LOGGER.logExceptionAsError(new IllegalArgumentException( - "Type '" + type + "' is not supported. Please use @FieldIgnore to exclude the field and manually " - + "build SearchField to the list if the field is needed. For more information, refer to link: " - + "aka.ms/azsdk/java/search/fieldbuilder")); - } - return; - } - - ParameterizedType parameterizedType = (ParameterizedType) type; - if (Map.class.isAssignableFrom((Class) parameterizedType.getRawType())) { - throw LOGGER.logExceptionAsError(new IllegalArgumentException("Map and its subclasses are not supported")); - } - - if (hasArrayOrCollectionWrapped) { - throw LOGGER - .logExceptionAsError(new IllegalArgumentException("Only single-dimensional array is supported.")); - } - - if (!List.class.isAssignableFrom((Class) parameterizedType.getRawType())) { - throw LOGGER - .logExceptionAsError(new IllegalArgumentException("Collection type '" + type + "' is not supported")); - } - } - - private static SearchFieldDataType covertToSearchFieldDataType(Type type, boolean hasArrayOrCollectionWrapped) { - validateType(type, hasArrayOrCollectionWrapped); - - if (SUPPORTED_NONE_PARAMETERIZED_TYPE.containsKey(type)) { - return SUPPORTED_NONE_PARAMETERIZED_TYPE.get(type); - } - - if (isArrayOrList(type)) { - Type componentOrElementType = getComponentOrElementType(type); - return SearchFieldDataType.collection(covertToSearchFieldDataType(componentOrElementType, true)); - } - - return SearchFieldDataType.COMPLEX; - } -} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/implementation/util/MappingUtils.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/implementation/util/MappingUtils.java deleted file mode 100644 index b99775a50e5a..000000000000 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/implementation/util/MappingUtils.java +++ /dev/null @@ -1,278 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.search.documents.implementation.util; - -import com.azure.core.exception.HttpResponseException; -import com.azure.core.http.HttpHeaders; -import com.azure.core.http.rest.PagedResponse; -import com.azure.core.http.rest.PagedResponseBase; -import com.azure.core.http.rest.Response; -import com.azure.core.util.CoreUtils; -import com.azure.search.documents.implementation.models.ErrorResponseException; -import com.azure.search.documents.indexes.implementation.models.AnalyzeResult; -import com.azure.search.documents.indexes.implementation.models.ListDataSourcesResult; -import com.azure.search.documents.indexes.implementation.models.ListIndexersResult; -import com.azure.search.documents.indexes.implementation.models.ListSkillsetsResult; -import com.azure.search.documents.indexes.implementation.models.ListSynonymMapsResult; -import com.azure.search.documents.indexes.models.AnalyzedTokenInfo; -import com.azure.search.documents.indexes.models.BlobIndexerDataToExtract; -import com.azure.search.documents.indexes.models.BlobIndexerImageAction; -import com.azure.search.documents.indexes.models.BlobIndexerParsingMode; -import com.azure.search.documents.indexes.models.BlobIndexerPdfTextRotationAlgorithm; -import com.azure.search.documents.indexes.models.IndexerExecutionEnvironment; -import com.azure.search.documents.indexes.models.IndexingParametersConfiguration; -import com.azure.search.documents.indexes.models.SearchIndex; -import com.azure.search.documents.indexes.models.SearchIndexer; -import com.azure.search.documents.indexes.models.SearchIndexerDataSourceConnection; -import com.azure.search.documents.indexes.models.SearchIndexerSkillset; -import com.azure.search.documents.indexes.models.SynonymMap; - -import java.util.ArrayList; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import java.util.function.Function; - -import static java.util.stream.Collectors.toList; - -public class MappingUtils { - - public static PagedResponse - mappingPagingDataSource(Response dataSourceResponse) { - List dataSourceMaps = dataSourceResponse.getValue().getDataSources(); - return new PagedResponseBase(dataSourceResponse.getRequest(), - dataSourceResponse.getStatusCode(), dataSourceResponse.getHeaders(), dataSourceMaps, null, null); - } - - public static PagedResponse - mappingPagingDataSourceNames(Response dataSourceResponse) { - List dataSourceNames = dataSourceResponse.getValue() - .getDataSources() - .stream() - .map(SearchIndexerDataSourceConnection::getName) - .collect(toList()); - return new PagedResponseBase(dataSourceResponse.getRequest(), - dataSourceResponse.getStatusCode(), dataSourceResponse.getHeaders(), dataSourceNames, null, null); - } - - public static PagedResponse mappingPagingSearchIndexNames(PagedResponse searchIndexResponse) { - List pageItems = new ArrayList<>(); - searchIndexResponse.getValue().forEach(item -> pageItems.add(item.getName())); - return new PagedResponseBase(searchIndexResponse.getRequest(), - searchIndexResponse.getStatusCode(), searchIndexResponse.getHeaders(), pageItems, - searchIndexResponse.getContinuationToken(), null); - } - - public static PagedResponse - mappingPagingSearchIndexer(Response searchIndexerResponse) { - List searchIndexers = searchIndexerResponse.getValue().getIndexers(); - return new PagedResponseBase(searchIndexerResponse.getRequest(), - searchIndexerResponse.getStatusCode(), searchIndexerResponse.getHeaders(), searchIndexers, null, null); - } - - public static PagedResponse - mappingPagingSearchIndexerNames(Response searchIndexerResponse) { - List searchIndexerNames - = searchIndexerResponse.getValue().getIndexers().stream().map(SearchIndexer::getName).collect(toList()); - return new PagedResponseBase(searchIndexerResponse.getRequest(), - searchIndexerResponse.getStatusCode(), searchIndexerResponse.getHeaders(), searchIndexerNames, null, null); - } - - public static PagedResponse - mappingPagingSkillset(Response skillsetResponse) { - return new PagedResponseBase(skillsetResponse.getRequest(), - skillsetResponse.getStatusCode(), skillsetResponse.getHeaders(), skillsetResponse.getValue().getSkillsets(), - null, null); - } - - public static PagedResponse mappingPagingSkillsetNames(Response skillsetResponse) { - List skillsetNames - = skillsetResponse.getValue().getSkillsets().stream().map(SearchIndexerSkillset::getName).collect(toList()); - return new PagedResponseBase(skillsetResponse.getRequest(), - skillsetResponse.getStatusCode(), skillsetResponse.getHeaders(), skillsetNames, null, null); - } - - public static PagedResponse - mappingPagingSynonymMap(Response synonymMapResponse) { - return new PagedResponseBase(synonymMapResponse.getRequest(), - synonymMapResponse.getStatusCode(), synonymMapResponse.getHeaders(), - synonymMapResponse.getValue().getSynonymMaps(), null, null); - } - - public static PagedResponse - mappingPagingSynonymMapNames(Response synonymMapsResponse) { - List synonymMapNames - = synonymMapsResponse.getValue().getSynonymMaps().stream().map(SynonymMap::getName).collect(toList()); - return new PagedResponseBase(synonymMapsResponse.getRequest(), - synonymMapsResponse.getStatusCode(), synonymMapsResponse.getHeaders(), synonymMapNames, null, null); - } - - public static PagedResponse mappingTokenInfo(Response resultResponse) { - List tokenInfos = resultResponse.getValue().getTokens(); - return new PagedResponseBase(resultResponse.getRequest(), - resultResponse.getStatusCode(), resultResponse.getHeaders(), tokenInfos, null, null); - } - - public static Throwable exceptionMapper(Throwable throwable) { - if (throwable instanceof ErrorResponseException) { - ErrorResponseException exception = (ErrorResponseException) throwable; - return new HttpResponseException(exception.getMessage(), exception.getResponse()); - } - - if (throwable instanceof com.azure.search.documents.indexes.implementation.models.ErrorResponseException) { - com.azure.search.documents.indexes.implementation.models.ErrorResponseException exception - = (com.azure.search.documents.indexes.implementation.models.ErrorResponseException) throwable; - return new HttpResponseException(exception.getMessage(), exception.getResponse()); - } - - return throwable; - } - - /** - * Helper method to convert a {@link Map} of configurations to an {@link IndexingParametersConfiguration}. - * - * @param configuration The Map of configurations. - * @return An {@link IndexingParametersConfiguration} based on the Map of configurations or null if the Map was - * null or empty. - */ - public static IndexingParametersConfiguration - mapToIndexingParametersConfiguration(Map configuration) { - if (CoreUtils.isNullOrEmpty(configuration)) { - return null; - } - - IndexingParametersConfiguration config = new IndexingParametersConfiguration(); - - Map additionalProperties = null; - for (Map.Entry kvp : configuration.entrySet()) { - String key = kvp.getKey(); - if (key == null) { - continue; - } - - Object value = kvp.getValue(); - switch (key) { - case "parsingMode": - config.setParsingMode(converter(value, BlobIndexerParsingMode::fromString)); - break; - - case "excludedFileNameExtensions": - config.setExcludedFileNameExtensions(converter(value, Function.identity())); - break; - - case "indexedFileNameExtensions": - config.setIndexedFileNameExtensions(converter(value, Function.identity())); - break; - - case "failOnUnsupportedContentType": - config.setFailOnUnsupportedContentType(converter(value, Boolean::parseBoolean)); - break; - - case "failOnUnprocessableDocument": - config.setFailOnUnprocessableDocument(converter(value, Boolean::parseBoolean)); - break; - - case "indexStorageMetadataOnlyForOversizedDocuments": - config.setIndexStorageMetadataOnlyForOversizedDocuments(converter(value, Boolean::parseBoolean)); - break; - - case "delimitedTextHeaders": - config.setDelimitedTextHeaders(converter(value, Function.identity())); - break; - - case "delimitedTextDelimiter": - config.setDelimitedTextDelimiter(converter(value, Function.identity())); - break; - - case "firstLineContainsHeaders": - config.setFirstLineContainsHeaders(converter(value, Boolean::parseBoolean)); - break; - - case "documentRoot": - config.setDocumentRoot(converter(value, Function.identity())); - break; - - case "dataToExtract": - config.setDataToExtract(converter(value, BlobIndexerDataToExtract::fromString)); - break; - - case "imageAction": - config.setImageAction(converter(value, BlobIndexerImageAction::fromString)); - break; - - case "allowSkillsetToReadFileData": - config.setAllowSkillsetToReadFileData(converter(value, Boolean::parseBoolean)); - break; - - case "pdfTextRotationAlgorithm": - config - .setPdfTextRotationAlgorithm(converter(value, BlobIndexerPdfTextRotationAlgorithm::fromString)); - break; - - case "executionEnvironment": - config.setExecutionEnvironment(converter(value, IndexerExecutionEnvironment::fromString)); - break; - - case "queryTimeout": - config.setQueryTimeout(converter(value, Function.identity())); - break; - - default: - if (additionalProperties == null) { - additionalProperties = new LinkedHashMap<>(); - } - - additionalProperties.put(key, value); - break; - } - } - - return config.setAdditionalProperties(additionalProperties); - } - - private static T converter(Object value, Function conv) { - return value == null ? null : conv.apply(String.valueOf(value)); - } - - public static Map indexingParametersConfigurationToMap(IndexingParametersConfiguration params) { - if (params == null) { - return null; - } - - Map configuration = new LinkedHashMap<>(); - - setConfigurationValue(params.getParsingMode(), "parsingMode", configuration); - setConfigurationValue(params.getExcludedFileNameExtensions(), "excludedFileNameExtensions", configuration); - setConfigurationValue(params.getIndexedFileNameExtensions(), "indexedFileNameExtensions", configuration); - setConfigurationValue(params.isFailOnUnsupportedContentType(), "failOnUnsupportedContentType", configuration); - setConfigurationValue(params.isFailOnUnprocessableDocument(), "failOnUnprocessableDocument", configuration); - setConfigurationValue(params.isIndexStorageMetadataOnlyForOversizedDocuments(), - "indexStorageMetadataOnlyForOversizedDocuments", configuration); - setConfigurationValue(params.getDelimitedTextHeaders(), "delimitedTextHeaders", configuration); - setConfigurationValue(params.getDelimitedTextDelimiter(), "delimitedTextDelimiter", configuration); - setConfigurationValue(params.isFirstLineContainsHeaders(), "firstLineContainsHeaders", configuration); - setConfigurationValue(params.getDocumentRoot(), "documentRoot", configuration); - setConfigurationValue(params.getDataToExtract(), "dataToExtract", configuration); - setConfigurationValue(params.getImageAction(), "imageAction", configuration); - setConfigurationValue(params.isAllowSkillsetToReadFileData(), "allowSkillsetToReadFileData", configuration); - setConfigurationValue(params.getPdfTextRotationAlgorithm(), "pdfTextRotationAlgorithm", configuration); - setConfigurationValue(params.getExecutionEnvironment(), "executionEnvironment", configuration); - setConfigurationValue(params.getQueryTimeout(), "queryTimeout", configuration); - - Map additionalProperties = params.getAdditionalProperties(); - if (!CoreUtils.isNullOrEmpty(additionalProperties)) { - configuration.putAll(additionalProperties); - } - - return configuration; - } - - private static void setConfigurationValue(Object value, String key, Map configuration) { - if (value == null) { - return; - } - - configuration.put(key, String.valueOf(value)); - } -} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/implementation/util/SearchPagedResponseAccessHelper.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/implementation/util/SearchPagedResponseAccessHelper.java deleted file mode 100644 index 4dc45d01252f..000000000000 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/implementation/util/SearchPagedResponseAccessHelper.java +++ /dev/null @@ -1,193 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.search.documents.implementation.util; - -import com.azure.search.documents.models.DebugInfo; -import com.azure.search.documents.models.FacetResult; -import com.azure.search.documents.models.QueryAnswerResult; -import com.azure.search.documents.models.SemanticErrorReason; -import com.azure.search.documents.models.SemanticQueryRewritesResultType; -import com.azure.search.documents.models.SemanticSearchResultsType; -import com.azure.search.documents.util.SearchPagedResponse; - -import java.util.List; -import java.util.Map; - -/** - * Helper class to access internal values of {@link SearchPagedResponse}. - */ -public final class SearchPagedResponseAccessHelper { - private SearchPagedResponseAccessHelper() { - } - - private static SearchPagedResponseAccessor accessor; - - public interface SearchPagedResponseAccessor { - /** - * The percentage of the index covered in the search request. - *

- * If {@code minimumCoverage} wasn't supplied in the request this will be null. - * - * @param response The {@link SearchPagedResponse} being accessed. - * @return The percentage of the index covered in the search request if {@code minimumCoverage} was set in the - * request, otherwise null. - */ - Double getCoverage(SearchPagedResponse response); - - /** - * The facet query results based on the search request. - *

- * If {@code facets} weren't supplied in the request this will be null. - * - * @param response The {@link SearchPagedResponse} being accessed. - * @return The facet query results if {@code facets} were supplied in the request, otherwise null. - */ - Map> getFacets(SearchPagedResponse response); - - /** - * The approximate number of documents that matched the search and filter parameters in the request. - *

- * If {@code count} is set to {@code false} in the request this will be null. - * - * @param response The {@link SearchPagedResponse} being accessed. - * @return The approximate number of documents that match the request if {@code count} is {@code true}, otherwise - * null. - */ - Long getCount(SearchPagedResponse response); - - /** - * The answer results based on the search request. - *

- * If {@code answers} wasn't supplied in the request this will be null. - * - * @param response The {@link SearchPagedResponse} being accessed. - * @return The answer results if {@code answers} were supplied in the request, otherwise null. - */ - List getQueryAnswers(SearchPagedResponse response); - - /** - * The reason that a partial response was returned for a semantic search request. - * - * @param response The {@link SearchPagedResponse} being accessed. - * @return The reason that a partial response was returned for a semantic search request. - */ - SemanticErrorReason getSemanticErrorReason(SearchPagedResponse response); - - /** - * Get the semanticPartialResponseType property: Type of partial response that was returned for a semantic search - * request. - * - * @param response The {@link SearchPagedResponse} being accessed. - * @return the semanticPartialResponseType value. - */ - SemanticSearchResultsType getSemanticSearchResultsType(SearchPagedResponse response); - - /** - * Get the debugInfo property: Contains debugging information that can be used to further explore your search - * results. - * - * @param response The {@link SearchPagedResponse} being accessed. - * @return the debugInfo value. - */ - DebugInfo getDebugInfo(SearchPagedResponse response); - - /** - * Get the semanticQueryRewritesResultType property: Type of query rewrite that was used to retrieve documents. - * - * @param response The {@link SearchPagedResponse} being accessed. - * @return the semanticQueryRewritesResultType value. - */ - SemanticQueryRewritesResultType getSemanticQueryRewritesResultType(SearchPagedResponse response); - } - - /** - * The percentage of the index covered in the search request. - *

- * If {@code minimumCoverage} wasn't supplied in the request this will be null. - * - * @param response The {@link SearchPagedResponse} being accessed. - * @return The percentage of the index covered in the search request if {@code minimumCoverage} was set in the - * request, otherwise null. - */ - public static Double getCoverage(SearchPagedResponse response) { - return accessor.getCoverage(response); - } - - /** - * The facet query results based on the search request. - *

- * If {@code facets} weren't supplied in the request this will be null. - * - * @param response The {@link SearchPagedResponse} being accessed. - * @return The facet query results if {@code facets} were supplied in the request, otherwise null. - */ - public static Map> getFacets(SearchPagedResponse response) { - return accessor.getFacets(response); - } - - /** - * The approximate number of documents that matched the search and filter parameters in the request. - *

- * If {@code count} is set to {@code false} in the request this will be null. - * - * @param response The {@link SearchPagedResponse} being accessed. - * @return The approximate number of documents that match the request if {@code count} is {@code true}, otherwise - * null. - */ - public static Long getCount(SearchPagedResponse response) { - return accessor.getCount(response); - } - - /** - * The answer results based on the search request. - *

- * If {@code answers} wasn't supplied in the request this will be null. - * - * @param response The {@link SearchPagedResponse} being accessed. - * @return The answer results if {@code answers} were supplied in the request, otherwise null. - */ - public static List getQueryAnswers(SearchPagedResponse response) { - return accessor.getQueryAnswers(response); - } - - /** - * The reason that a partial response was returned for a semantic search request. - * @param response The {@link SearchPagedResponse} being accessed. - * @return The reason that a partial response was returned for a semantic search request. - */ - public static SemanticErrorReason getSemanticErrorReason(SearchPagedResponse response) { - return accessor.getSemanticErrorReason(response); - } - - /** - * The type of partial response that was returned for a semantic search request. - * @param response The {@link SearchPagedResponse} being accessed. - * @return The type of partial response that was returned for a semantic search request. - */ - public static SemanticSearchResultsType getSemanticSearchResultsType(SearchPagedResponse response) { - return accessor.getSemanticSearchResultsType(response); - } - - /** - * Contains debugging information that can be used to further explore your search results. - * @param response The {@link SearchPagedResponse} being accessed. - * @return The debugging information that can be used to further explore your search results. - */ - public static DebugInfo getDebugInfo(SearchPagedResponse response) { - return accessor.getDebugInfo(response); - } - - /** - * Type of query rewrite that was used to retrieve documents. - * @param response The {@link SearchPagedResponse} being accessed. - * @return The type of query rewrite that was used to retrieve documents. - */ - public static SemanticQueryRewritesResultType getSemanticQueryRewritesResultType(SearchPagedResponse response) { - return accessor.getSemanticQueryRewritesResultType(response); - } - - public static void setAccessor(SearchPagedResponseAccessor searchPagedResponseAccessor) { - accessor = searchPagedResponseAccessor; - } -} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/implementation/util/SemanticSearchResultsAccessHelper.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/implementation/util/SemanticSearchResultsAccessHelper.java deleted file mode 100644 index 4a4651ddb23c..000000000000 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/implementation/util/SemanticSearchResultsAccessHelper.java +++ /dev/null @@ -1,38 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -package com.azure.search.documents.implementation.util; - -import com.azure.search.documents.models.SemanticSearchResults; -import com.azure.search.documents.util.SearchPagedResponse; - -/** - * Helper class to access internals of {@link SemanticSearchResults}. - */ -public final class SemanticSearchResultsAccessHelper { - private SemanticSearchResultsAccessHelper() { - } - - private static SemanticSearchResultsAccessor accessor; - - public interface SemanticSearchResultsAccessor { - SemanticSearchResults create(SearchPagedResponse pagedResponse); - } - - public static void setAccessor(final SemanticSearchResultsAccessor newAccessor) { - accessor = newAccessor; - } - - public static SemanticSearchResults create(SearchPagedResponse pagedResponse) { - if (accessor == null) { - try { - Class.forName(SemanticSearchResults.class.getName(), true, - SemanticSearchResultsAccessHelper.class.getClassLoader()); - } catch (ClassNotFoundException e) { - throw new RuntimeException(e); - } - } - - assert accessor != null; - return accessor.create(pagedResponse); - } -} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/implementation/util/SpatialFormatter.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/implementation/util/SpatialFormatter.java deleted file mode 100644 index 0fcbe1bae8a2..000000000000 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/implementation/util/SpatialFormatter.java +++ /dev/null @@ -1,126 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.search.documents.implementation.util; - -import com.azure.core.models.GeoLineString; -import com.azure.core.models.GeoLinearRing; -import com.azure.core.models.GeoPoint; -import com.azure.core.models.GeoPolygon; -import com.azure.core.models.GeoPosition; -import com.azure.core.util.logging.ClientLogger; - -import java.util.List; -import java.util.Objects; - -/** - * Helper class containing methods which encode geographic types for use in OData filters. - */ -public final class SpatialFormatter { - /* - * This is the maximum length of a longitude-latitude pair in a geography OData expression. - * - * Each double is allowed 17 characters, 15 digits of precision, 1 digit for a decimal, and 1 digit for a sign, and - * 1 character for the space between the pair. - */ - private static final int LONGITUDE_LATITUDE_MAX_LENGTH = 2 * 17 + 1; - - /* - * The length of the point OData expression identifier. - */ - private static final int POINT_EXPRESSION_IDENTIFIER_LENGTH = "geography'POINT()".length(); - - private static final int POLYGON_EXPRESSION_IDENTIFIER_LENGTH = "geography'POLYGON(())".length(); - - /** - * Encodes a {@link GeoPoint} into an OData expression. - * - * @param longitude Longitude of the point. - * @param latitude Latitude of the point. - * @return An OData expression representing the {@link GeoPoint}. - */ - public static String encodePoint(double longitude, double latitude) { - StringBuilder builder = new StringBuilder(POINT_EXPRESSION_IDENTIFIER_LENGTH + LONGITUDE_LATITUDE_MAX_LENGTH); - - return addPoint(builder.append("geography'POINT("), longitude, latitude).append(")'").toString(); - } - - /** - * Encodes a closed {@link GeoLineString} into an OData expression. - *

- * The {@link GeoLineString} is expected to contain at least four points and the first and last points have the same - * longitudinal and latitudinal values. - * - * @param line The {@link GeoLineString}. - * @param logger A logger that will log any exceptions thrown. - * @return An OData expression representing the {@link GeoLineString}. - * @throws NullPointerException If {@code line} is null. - * @throws IllegalArgumentException If the {@link GeoLineString} contains less than four points and the first and - * last points don't use the same longitudinal and latitudinal values. - */ - public static String encodePolygon(GeoLineString line, ClientLogger logger) { - Objects.requireNonNull(line, "'line' cannot be null."); - - List coordinates = line.getCoordinates(); - if (coordinates.size() < 4) { - throw logger.logExceptionAsError(new IllegalArgumentException( - "'line' must have at least four coordinates to form a searchable polygon.")); - } - - if (!Objects.equals(coordinates.get(0), coordinates.get(coordinates.size() - 1))) { - throw logger.logExceptionAsError(new IllegalArgumentException( - "'line' must have matching first and last coordinates to form a searchable polygon.")); - } - - return encodePolygon(coordinates); - } - - /** - * Encodes a {@link GeoPolygon} into an OData expression. - *

- * The {@link GeoPolygon} is expected to contain a single {@link GeoLinearRing} representing it. - * - * @param polygon The {@link GeoPolygon}. - * @param logger A logger that will log any exceptions thrown. - * @return An OData expression representing the {@link GeoPolygon}. - * @throws NullPointerException If {@code polygon} is null. - * @throws IllegalArgumentException If the {@link GeoPolygon} is represented by multiple {@link GeoLinearRing - * GeoLinearRings}. - */ - public static String encodePolygon(GeoPolygon polygon, ClientLogger logger) { - Objects.requireNonNull(polygon, "'polygon' cannot be null."); - - if (polygon.getRings().size() != 1) { - throw logger.logExceptionAsError( - new IllegalArgumentException("'polygon' must have exactly one ring to form a searchable polygon.")); - } - - return encodePolygon(polygon.getOuterRing().getCoordinates()); - } - - private static String encodePolygon(List ring) { - int approximateODataExpressionSize - = POLYGON_EXPRESSION_IDENTIFIER_LENGTH + ring.size() * LONGITUDE_LATITUDE_MAX_LENGTH + ring.size(); - - StringBuilder builder = new StringBuilder(approximateODataExpressionSize).append("geography'POLYGON(("); - - boolean first = true; - for (GeoPosition position : ring) { - if (!first) { - builder.append(","); - } else { - first = false; - } - - addPoint(builder, position.getLongitude(), position.getLatitude()); - } - - return builder.append("))'").toString(); - } - - private static StringBuilder addPoint(StringBuilder builder, double longitude, double latitude) { - return builder.append(Utility.formatCoordinate(longitude)) - .append(' ') - .append(Utility.formatCoordinate(latitude)); - } -} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/implementation/util/Utility.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/implementation/util/Utility.java deleted file mode 100644 index 07dcd0542f9a..000000000000 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/implementation/util/Utility.java +++ /dev/null @@ -1,238 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.search.documents.implementation.util; - -import com.azure.core.credential.AzureKeyCredential; -import com.azure.core.credential.TokenCredential; -import com.azure.core.exception.HttpResponseException; -import com.azure.core.exception.ResourceNotFoundException; -import com.azure.core.http.HttpClient; -import com.azure.core.http.HttpHeaders; -import com.azure.core.http.HttpPipeline; -import com.azure.core.http.HttpPipelineBuilder; -import com.azure.core.http.policy.AddDatePolicy; -import com.azure.core.http.policy.AddHeadersFromContextPolicy; -import com.azure.core.http.policy.AddHeadersPolicy; -import com.azure.core.http.policy.AzureKeyCredentialPolicy; -import com.azure.core.http.policy.BearerTokenAuthenticationPolicy; -import com.azure.core.http.policy.HttpLogOptions; -import com.azure.core.http.policy.HttpLoggingPolicy; -import com.azure.core.http.policy.HttpPipelinePolicy; -import com.azure.core.http.policy.HttpPolicyProviders; -import com.azure.core.http.policy.RequestIdPolicy; -import com.azure.core.http.policy.RetryOptions; -import com.azure.core.http.policy.RetryPolicy; -import com.azure.core.http.policy.UserAgentPolicy; -import com.azure.core.http.rest.Response; -import com.azure.core.util.ClientOptions; -import com.azure.core.util.Configuration; -import com.azure.core.util.Context; -import com.azure.core.util.CoreUtils; -import com.azure.core.util.builder.ClientBuilderUtil; -import com.azure.core.util.logging.ClientLogger; -import com.azure.search.documents.SearchDocument; -import com.azure.search.documents.SearchServiceVersion; -import com.azure.search.documents.implementation.SearchIndexClientImpl; -import com.azure.search.documents.implementation.models.ErrorResponseException; -import com.azure.search.documents.implementation.models.IndexBatch; -import com.azure.search.documents.models.IndexBatchException; -import com.azure.search.documents.models.IndexDocumentsResult; -import com.azure.search.documents.models.SearchAudience; -import com.azure.search.documents.models.SuggestOptions; -import reactor.core.publisher.Mono; - -import java.io.IOException; -import java.io.UncheckedIOException; -import java.nio.charset.StandardCharsets; -import java.nio.file.Files; -import java.nio.file.Path; -import java.text.DecimalFormat; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.function.Supplier; - -import static com.azure.core.util.FluxUtil.monoError; - -public final class Utility { - private static final ClientLogger LOGGER = new ClientLogger(Utility.class); - private static final ClientOptions DEFAULT_CLIENT_OPTIONS = new ClientOptions(); - private static final HttpLogOptions DEFAULT_LOG_OPTIONS = Constants.DEFAULT_LOG_OPTIONS_SUPPLIER.get(); - private static final HttpHeaders HTTP_HEADERS = new HttpHeaders().set("return-client-request-id", "true"); - - private static final ThreadLocal COORDINATE_FORMATTER = ThreadLocal.withInitial(DecimalFormat::new); - - /* - * Representation of the Multi-Status HTTP response code. - */ - private static final int MULTI_STATUS_CODE = 207; - - /* - * Exception message to use if the document isn't found. - */ - private static final String DOCUMENT_NOT_FOUND = "Document not found."; - - private static final String CLIENT_NAME; - private static final String CLIENT_VERSION; - - static { - Map properties = CoreUtils.getProperties("azure-search-documents.properties"); - CLIENT_NAME = properties.getOrDefault("name", "UnknownName"); - CLIENT_VERSION = properties.getOrDefault("version", "UnknownVersion"); - } - - public static HttpPipeline buildHttpPipeline(ClientOptions clientOptions, HttpLogOptions logOptions, - Configuration configuration, RetryPolicy retryPolicy, RetryOptions retryOptions, - AzureKeyCredential azureKeyCredential, TokenCredential tokenCredential, SearchAudience audience, - List perCallPolicies, List perRetryPolicies, HttpClient httpClient, - ClientLogger logger) { - Configuration buildConfiguration - = (configuration == null) ? Configuration.getGlobalConfiguration() : configuration; - - ClientOptions buildClientOptions = (clientOptions == null) ? DEFAULT_CLIENT_OPTIONS : clientOptions; - HttpLogOptions buildLogOptions = (logOptions == null) ? DEFAULT_LOG_OPTIONS : logOptions; - - String applicationId = CoreUtils.getApplicationId(buildClientOptions, buildLogOptions); - - // Closest to API goes first, closest to wire goes last. - final List httpPipelinePolicies = new ArrayList<>(); - httpPipelinePolicies.add(new AddHeadersPolicy(HTTP_HEADERS)); - httpPipelinePolicies.add(new AddHeadersFromContextPolicy()); - httpPipelinePolicies.add(new UserAgentPolicy(applicationId, CLIENT_NAME, CLIENT_VERSION, buildConfiguration)); - httpPipelinePolicies.add(new RequestIdPolicy()); - - httpPipelinePolicies.addAll(perCallPolicies); - HttpPolicyProviders.addBeforeRetryPolicies(httpPipelinePolicies); - httpPipelinePolicies.add(ClientBuilderUtil.validateAndGetRetryPolicy(retryPolicy, retryOptions)); - - httpPipelinePolicies.add(new AddDatePolicy()); - - if (azureKeyCredential != null && tokenCredential != null) { - throw logger.logExceptionAsError(new IllegalArgumentException( - "Builder has both AzureKeyCredential and TokenCredential supplied. Only one may be supplied.")); - } else if (azureKeyCredential != null) { - httpPipelinePolicies.add(new AzureKeyCredentialPolicy("api-key", azureKeyCredential)); - } else if (tokenCredential != null) { - String audienceUrl = audience == null ? SearchAudience.AZURE_PUBLIC_CLOUD.toString() : audience.toString(); - httpPipelinePolicies.add(new BearerTokenAuthenticationPolicy(tokenCredential, audienceUrl + "/.default")); - } else { - throw logger.logExceptionAsError(new IllegalArgumentException("Builder doesn't have a credential " - + "configured. Supply either an AzureKeyCredential or TokenCredential.")); - } - - httpPipelinePolicies.addAll(perRetryPolicies); - HttpPolicyProviders.addAfterRetryPolicies(httpPipelinePolicies); - - HttpHeaders headers = CoreUtils.createHttpHeadersFromClientOptions(buildClientOptions); - if (headers != null) { - httpPipelinePolicies.add(new AddHeadersPolicy(headers)); - } - - httpPipelinePolicies.add(new HttpLoggingPolicy(buildLogOptions)); - - return new HttpPipelineBuilder().clientOptions(buildClientOptions) - .httpClient(httpClient) - .policies(httpPipelinePolicies.toArray(new HttpPipelinePolicy[0])) - .build(); - } - - public static Mono> indexDocumentsWithResponseAsync(SearchIndexClientImpl restClient, - List actions, boolean throwOnAnyError, - Context context, ClientLogger logger) { - try { - return restClient.getDocuments() - .indexWithResponseAsync(new IndexBatch(actions), null, context) - .onErrorMap(MappingUtils::exceptionMapper) - .flatMap(response -> (response.getStatusCode() == MULTI_STATUS_CODE && throwOnAnyError) - ? Mono.error(new IndexBatchException(response.getValue())) - : Mono.just(response)); - } catch (RuntimeException ex) { - return monoError(logger, ex); - } - } - - public static Response indexDocumentsWithResponse(SearchIndexClientImpl restClient, - List actions, boolean throwOnAnyError, - Context context, ClientLogger logger) { - return executeRestCallWithExceptionHandling(() -> { - Response response - = restClient.getDocuments().indexWithResponse(new IndexBatch(actions), null, context); - if (response.getStatusCode() == MULTI_STATUS_CODE && throwOnAnyError) { - throw logger.logExceptionAsError(new IndexBatchException(response.getValue())); - } - return response; - }, logger); - } - - public static SearchIndexClientImpl buildRestClient(SearchServiceVersion serviceVersion, String endpoint, - String indexName, HttpPipeline httpPipeline) { - return new SearchIndexClientImpl(httpPipeline, endpoint, indexName, serviceVersion.getVersion()); - } - - public static String formatCoordinate(double coordinate) { - return COORDINATE_FORMATTER.get().format(coordinate); - } - - public static String readSynonymsFromFile(Path filePath) { - try { - return new String(Files.readAllBytes(filePath), StandardCharsets.UTF_8); - } catch (IOException ex) { - throw LOGGER.logExceptionAsError(new UncheckedIOException(ex)); - } - } - - public static T executeRestCallWithExceptionHandling(Supplier supplier, ClientLogger logger) { - try { - return supplier.get(); - } catch (com.azure.search.documents.indexes.implementation.models.ErrorResponseException exception) { - throw logger - .logExceptionAsError(new HttpResponseException(exception.getMessage(), exception.getResponse())); - } catch (com.azure.search.documents.implementation.models.ErrorResponseException exception) { - throw logger - .logExceptionAsError(new HttpResponseException(exception.getMessage(), exception.getResponse())); - } catch (RuntimeException ex) { - throw logger.logExceptionAsError(ex); - } - } - - /** - * Ensures that all suggest parameters are correctly set. This method should be used when {@link SuggestOptions} is - * passed to the Search service. - * - * @param suggestOptions suggest parameters - * @return SuggestOptions ensured suggest parameters - */ - public static SuggestOptions ensureSuggestOptions(SuggestOptions suggestOptions) { - if (suggestOptions == null) { - return null; - } - - return CoreUtils.isNullOrEmpty(suggestOptions.getSelect()) ? suggestOptions.setSelect("*") : suggestOptions; - } - - /** - * Converts the {@link Throwable} into a more descriptive exception type if the {@link SearchDocument} isn't found. - * - * @param throwable Throwable thrown during a API call. - * @return The {@link Throwable} mapped to a more descriptive exception type if the {@link SearchDocument} - * isn't found, otherwise the passed {@link Throwable} unmodified. - */ - public static Throwable exceptionMapper(Throwable throwable) { - if (!(throwable instanceof ErrorResponseException)) { - return throwable; - } - - return mapErrorResponseException((ErrorResponseException) throwable); - } - - public static HttpResponseException mapErrorResponseException(ErrorResponseException exception) { - if (exception.getResponse().getStatusCode() == 404) { - return new ResourceNotFoundException(DOCUMENT_NOT_FOUND, exception.getResponse()); - } - return new HttpResponseException(exception.getMessage(), exception.getResponse()); - } - - private Utility() { - } -} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/implementation/util/package-info.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/implementation/util/package-info.java deleted file mode 100644 index 44093e57cdf3..000000000000 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/implementation/util/package-info.java +++ /dev/null @@ -1,7 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -/** - * Package containing Search internal utility classes. - */ -package com.azure.search.documents.implementation.util; diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/FieldBuilderIgnore.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/FieldBuilderIgnore.java deleted file mode 100644 index f29cd037842f..000000000000 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/FieldBuilderIgnore.java +++ /dev/null @@ -1,23 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.search.documents.indexes; - -import com.azure.search.documents.indexes.models.SearchField; - -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -/** - * Marker annotation that indicates the field or method is to be ignored by converting to SearchField. The annotation is - * useful in situations where a property definition doesn't cleanly map to a {@link SearchField} object, but its values - * still need to be converted to and from JSON. In that case, ignore annotation in json serializer library can't be used - * since it would disable JSON conversion. An example of a scenario where this is useful is when mapping between a - * string field in Azure AI Search and an enum property. - */ -@Target({ ElementType.FIELD, ElementType.METHOD }) -@Retention(RetentionPolicy.RUNTIME) -public @interface FieldBuilderIgnore { -} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/SearchIndexAsyncClient.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/SearchIndexAsyncClient.java deleted file mode 100644 index e271b0fa86e7..000000000000 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/SearchIndexAsyncClient.java +++ /dev/null @@ -1,1244 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -package com.azure.search.documents.indexes; - -import com.azure.core.annotation.ReturnType; -import com.azure.core.annotation.ServiceClient; -import com.azure.core.annotation.ServiceMethod; -import com.azure.core.http.HttpPipeline; -import com.azure.core.http.rest.PagedFlux; -import com.azure.core.http.rest.PagedResponse; -import com.azure.core.http.rest.Response; -import com.azure.core.util.Context; -import com.azure.core.util.FluxUtil; -import com.azure.core.util.logging.ClientLogger; -import com.azure.core.util.serializer.JsonSerializer; -import com.azure.search.documents.SearchAsyncClient; -import com.azure.search.documents.SearchClientBuilder; -import com.azure.search.documents.SearchServiceVersion; -import com.azure.search.documents.implementation.converters.AnalyzeRequestConverter; -import com.azure.search.documents.implementation.util.FieldBuilder; -import com.azure.search.documents.implementation.util.MappingUtils; -import com.azure.search.documents.indexes.implementation.SearchServiceClientImpl; -import com.azure.search.documents.indexes.implementation.models.ListSynonymMapsResult; -import com.azure.search.documents.indexes.models.AnalyzeTextOptions; -import com.azure.search.documents.indexes.models.AnalyzedTokenInfo; -import com.azure.search.documents.indexes.models.FieldBuilderOptions; -import com.azure.search.documents.indexes.models.SearchField; -import com.azure.search.documents.indexes.models.SearchIndex; -import com.azure.search.documents.indexes.models.SearchIndexStatistics; -import com.azure.search.documents.indexes.models.SearchServiceStatistics; -import com.azure.search.documents.indexes.models.SynonymMap; -import reactor.core.publisher.Mono; - -import java.lang.reflect.Field; -import java.lang.reflect.Method; -import java.util.List; -import java.util.Objects; -import java.util.function.Function; - -import static com.azure.core.util.FluxUtil.monoError; -import static com.azure.core.util.FluxUtil.pagedFluxError; -import static com.azure.core.util.FluxUtil.withContext; - -/** - * This class provides a client that contains the operations for creating, getting, listing, updating, or deleting - * indexes or synonym map and analyzing text in an Azure AI Search service. - * - *

- * Overview - *

- * - *

- * An index is stored on your search service and populated with JSON documents that are indexed and tokenized for - * information retrieval. The fields collection of an index defines the structure of the search document. Fields - * have a name, data types, and attributes that determine how it's used. For example, searchable fields are used in - * full text search, and thus tokenized during indexing. An index also defines other constructs, such as scoring - * profiles for relevance tuning, suggesters, semantic configurations, and custom analyzers. - *

- * - *

- * A synonym map is service-level object that contains user-defined synonyms. This object is maintained - * independently from search indexes. Once uploaded, you can point any searchable field to the synonym map (one per field). - *

- * - *

- * This client provides an asynchronous API for accessing indexes. This client allows you to create, delete, update, - * and configure search indexes. The client also allows you to declare custom synonym maps to expand or rewrite - * queries. - *

- * - *

- * Getting Started - *

- * - *

- * Authenticating and building instances of this client are handled by {@link SearchIndexClientBuilder}. This - * sample shows you how to create an instance of the client: - *

- * - * - *
- * SearchIndexAsyncClient searchIndexAsyncClient = new SearchIndexClientBuilder()
- *     .credential(new AzureKeyCredential("{key}"))
- *     .endpoint("{endpoint}")
- *     .buildAsyncClient();
- * 
- * - * - *

- * For more information on authentication and building, see the documentation for {@link SearchIndexClientBuilder}. - *

- * - *
- * - *

- * Examples - *

- * - *

- * The following examples all use a simple Hotel - * data set that you can - * import into your own index from the Azure portal. - * These are just a few of the basics - please check out our Samples for much more. - *

- * - *

- * Create an Index - *

- * - *

- * The following sample creates an index. - *

- * - * - *
- * SearchIndex searchIndex = new SearchIndex("indexName", Arrays.asList(
- *     new SearchField("hotelId", SearchFieldDataType.STRING)
- *         .setKey(true)
- *         .setFilterable(true)
- *         .setSortable(true),
- *     new SearchField("hotelName", SearchFieldDataType.STRING)
- *         .setSearchable(true)
- *         .setFilterable(true)
- *         .setSortable(true),
- *     new SearchField("description", SearchFieldDataType.STRING)
- *         .setSearchable(true)
- *         .setAnalyzerName(LexicalAnalyzerName.EN_LUCENE),
- *     new SearchField("descriptionFr", SearchFieldDataType.STRING)
- *         .setSearchable(true)
- *         .setAnalyzerName(LexicalAnalyzerName.FR_LUCENE),
- *     new SearchField("tags", SearchFieldDataType.collection(SearchFieldDataType.STRING))
- *         .setSearchable(true)
- *         .setFilterable(true)
- *         .setFacetable(true),
- *     new SearchField("address", SearchFieldDataType.COMPLEX)
- *         .setFields(
- *             new SearchField("streetAddress", SearchFieldDataType.STRING)
- *                 .setSearchable(true),
- *             new SearchField("city", SearchFieldDataType.STRING)
- *                 .setFilterable(true)
- *                 .setSortable(true)
- *                 .setFacetable(true),
- *             new SearchField("stateProvince", SearchFieldDataType.STRING)
- *                 .setSearchable(true)
- *                 .setFilterable(true)
- *                 .setSortable(true)
- *                 .setFacetable(true),
- *             new SearchField("country", SearchFieldDataType.STRING)
- *                 .setSearchable(true)
- *                 .setSynonymMapNames("synonymMapName")
- *                 .setFilterable(true)
- *                 .setSortable(true)
- *                 .setFacetable(true),
- *             new SearchField("postalCode", SearchFieldDataType.STRING)
- *                 .setSearchable(true)
- *                 .setFilterable(true)
- *                 .setSortable(true)
- *                 .setFacetable(true))
- * ));
- *
- * searchIndexAsyncClient.createIndex(searchIndex).block();
- * 
- * - * - * - * For a synchronous sample see {@link SearchIndexClient#createIndex(SearchIndex)}. - * - * - *

- * List indexes - *

- * - *

- * The following sample lists all indexes. - *

- * - * - *
- * searchIndexAsyncClient.listIndexes().subscribe(index -> System.out.println("The index name is " + index.getName()));
- * 
- * - * - * - * For a synchronous sample see {@link SearchIndexClient#listIndexes()}. - * - * - *

- * Retrieve an Index - *

- * - *

- * The following sample retrieves an index. - *

- * - * - *
- * SearchIndex searchIndex = searchIndexAsyncClient.getIndex("indexName").block();
- * if (searchIndex != null) {
- *     System.out.println("The index name is " + searchIndex.getName());
- * }
- * 
- * - * - * - * For a synchronous sample see {@link SearchIndexClient#getIndex(String)}. - * - * - *

- * Update an Index - *

- * - *

- * The following sample updates an index. - *

- * - * - *
- * SearchIndex searchIndex = searchIndexAsyncClient.getIndex("indexName").block();
- * if (searchIndex != null) {
- *     searchIndex.setFields(new SearchField("newField", SearchFieldDataType.STRING));
- *     searchIndexAsyncClient.createOrUpdateIndex(searchIndex);
- * }
- * 
- * - * - * - * For a synchronous sample see {@link SearchIndexClient#createOrUpdateIndex(SearchIndex)}. - * - * - *

- * Delete an Index - *

- * - *

- * The following sample deletes an index. - *

- * - * - *
- * String indexName = "indexName";
- * searchIndexAsyncClient.deleteIndex(indexName).block();
- * 
- * - * - * - * For a synchronous sample see {@link SearchIndexClient#deleteIndex(String)}. - * - * - *

- * Create a Synonym Map - *

- * - *

- * The following sample creates a synonym map. - *

- * - * - *
- * SynonymMap synonymMap = new SynonymMap("synonymMapName", "hotel, motel, \"motor inn\"");
- * searchIndexAsyncClient.createSynonymMap(synonymMap).block();
- * 
- * - * - * - * For a synchronous sample see {@link SearchIndexClient#createSynonymMap(SynonymMap)}. - * - * - *

- * List Synonym Maps - *

- * - *

- * The following sample lists all synonym maps. - *

- * - * - * - *
- * searchIndexAsyncClient.listSynonymMaps().subscribe(synonymMap ->
- *     System.out.println("The synonymMap name is " + synonymMap.getName())
- * );
- * 
- * - * - * - * For a synchronous sample see {@link SearchIndexClient#listSynonymMaps()}. - * - * - *

- * Retrieve a Synonym Map - *

- * - *

- * The following sample retrieves a synonym map. - *

- * - * - *
- * SynonymMap synonymMap = searchIndexAsyncClient.getSynonymMap("synonymMapName").block();
- * if (synonymMap != null) {
- *     System.out.println("The synonymMap name is " + synonymMap.getName());
- * }
- * 
- * - * - * - * For a synchronous sample see {@link SearchIndexClient#getSynonymMap(String)}. - * - * - *

- * Update a Synonym Map - *

- * - *

- * The following sample updates a synonym map. - *

- * - * - * - *
- * SynonymMap synonymMap = searchIndexAsyncClient.getSynonymMap("synonymMapName").block();
- * if (synonymMap != null) {
- *     synonymMap.setSynonyms("hotel, motel, inn");
- *     searchIndexAsyncClient.createOrUpdateSynonymMap(synonymMap).block();
- * }
- * 
- * - * - * - * For a synchronous sample see {@link SearchIndexClient#createOrUpdateSynonymMap(SynonymMap)}. - * - * - *

- * Delete a Synonym Map - *

- * - *

- * The following sample deletes a synonym map. - *

- * - * - * - *
- * String synonymMapName = "synonymMapName";
- * searchIndexAsyncClient.deleteSynonymMap(synonymMapName).block();
- * 
- * - * - * - * For a synchronous sample see {@link SearchIndexClient#deleteSynonymMap(String)}. - * - * - * @see SearchIndexAsyncClient - * @see SearchIndexClientBuilder - * @see com.azure.search.documents.indexes - */ -@ServiceClient(builder = SearchIndexClientBuilder.class, isAsync = true) -public final class SearchIndexAsyncClient { - private static final ClientLogger LOGGER = new ClientLogger(SearchIndexAsyncClient.class); - - /** - * Search REST API Version - */ - private final SearchServiceVersion serviceVersion; - - /** - * The endpoint for the Azure AI Search service. - */ - private final String endpoint; - - /** - * The underlying AutoRest client used to interact with the Search service - */ - private final SearchServiceClientImpl restClient; - - private final JsonSerializer serializer; - - /** - * The pipeline that powers this client. - */ - private final HttpPipeline httpPipeline; - - SearchIndexAsyncClient(String endpoint, SearchServiceVersion serviceVersion, HttpPipeline httpPipeline, - JsonSerializer serializer) { - this.endpoint = endpoint; - this.serviceVersion = serviceVersion; - this.httpPipeline = httpPipeline; - this.serializer = serializer; - this.restClient = new SearchServiceClientImpl(httpPipeline, endpoint, serviceVersion.getVersion()); - } - - /** - * Gets the {@link HttpPipeline} powering this client. - * - * @return the pipeline. - */ - HttpPipeline getHttpPipeline() { - return this.httpPipeline; - } - - /** - * Gets the endpoint for the Azure AI Search service. - * - * @return the endpoint value. - */ - public String getEndpoint() { - return this.endpoint; - } - - /** - * Initializes a new {@link SearchAsyncClient} using the given Index name and the same configuration as the - * SearchServiceAsyncClient. - * - * @param indexName the name of the Index for the client - * @return a {@link SearchAsyncClient} created from the service client configuration - */ - public SearchAsyncClient getSearchAsyncClient(String indexName) { - return getSearchClientBuilder(indexName, endpoint, serviceVersion, httpPipeline, serializer).buildAsyncClient(); - } - - static SearchClientBuilder getSearchClientBuilder(String indexName, String endpoint, - SearchServiceVersion serviceVersion, HttpPipeline httpPipeline, JsonSerializer serializer) { - return new SearchClientBuilder().endpoint(endpoint) - .indexName(indexName) - .serviceVersion(serviceVersion) - .pipeline(httpPipeline) - .serializer(serializer); - } - - /** - * Creates a new Azure AI Search index. - * - *

Code Sample

- * - *

Create search index named "searchIndex".

- * - * - *
-     * List<SearchField> searchFields = Arrays.asList(
-     *     new SearchField("hotelId", SearchFieldDataType.STRING).setKey(true),
-     *     new SearchField("hotelName", SearchFieldDataType.STRING).setSearchable(true)
-     * );
-     * SearchIndex searchIndex = new SearchIndex("searchIndex", searchFields);
-     * SEARCH_INDEX_ASYNC_CLIENT.createIndex(searchIndex)
-     *     .subscribe(indexFromService ->
-     *         System.out.printf("The index name is %s. The ETag of index is %s.%n", indexFromService.getName(),
-     *         indexFromService.getETag()));
-     * 
- * - * - * @param index definition of the index to create. - * @return the created Index. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono createIndex(SearchIndex index) { - return createIndexWithResponse(index).map(Response::getValue); - } - - /** - * Creates a new Azure AI Search index. - * - *

Code Sample

- * - *

Create search index named "searchIndex".

- * - * - *
-     * List<SearchField> searchFields = Arrays.asList(
-     *     new SearchField("hotelId", SearchFieldDataType.STRING).setKey(true),
-     *     new SearchField("hotelName", SearchFieldDataType.STRING).setSearchable(true)
-     * );
-     * SearchIndex searchIndex = new SearchIndex("searchIndex", searchFields);
-     *
-     * SEARCH_INDEX_ASYNC_CLIENT.createIndexWithResponse(searchIndex)
-     *     .subscribe(indexFromServiceResponse ->
-     *         System.out.printf("The status code of the response is %s. The index name is %s.%n",
-     *         indexFromServiceResponse.getStatusCode(), indexFromServiceResponse.getValue().getName()));
-     * 
- * - * - * @param index definition of the index to create - * @return a response containing the created Index. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> createIndexWithResponse(SearchIndex index) { - return withContext(context -> createIndexWithResponse(index, context)); - } - - Mono> createIndexWithResponse(SearchIndex index, Context context) { - try { - Objects.requireNonNull(index, "'Index' cannot be null"); - return restClient.getIndexes() - .createWithResponseAsync(index, null, context) - .onErrorMap(MappingUtils::exceptionMapper); - } catch (RuntimeException ex) { - return monoError(LOGGER, ex); - } - } - - /** - * Retrieves an index definition from the Azure AI Search. - * - *

Code Sample

- * - *

Get search index with name "searchIndex".

- * - * - *
-     * SEARCH_INDEX_ASYNC_CLIENT.getIndex("searchIndex")
-     *     .subscribe(indexFromService ->
-     *         System.out.printf("The index name is %s. The ETag of index is %s.%n", indexFromService.getName(),
-     *             indexFromService.getETag()));
-     * 
- * - * - * @param indexName The name of the index to retrieve - * @return the Index. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono getIndex(String indexName) { - return getIndexWithResponse(indexName).map(Response::getValue); - } - - /** - * Retrieves an index definition from the Azure AI Search. - * - *

Code Sample

- * - *

Get search index with "searchIndex.

- * - * - *
-     * SEARCH_INDEX_ASYNC_CLIENT.getIndexWithResponse("searchIndex")
-     *     .subscribe(indexFromServiceResponse ->
-     *         System.out.printf("The status code of the response is %s. The index name is %s.%n",
-     *             indexFromServiceResponse.getStatusCode(), indexFromServiceResponse.getValue().getName()));
-     * 
- * - * - * @param indexName the name of the index to retrieve - * @return a response containing the Index. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> getIndexWithResponse(String indexName) { - return withContext(context -> getIndexWithResponse(indexName, context)); - } - - Mono> getIndexWithResponse(String indexName, Context context) { - try { - return restClient.getIndexes() - .getWithResponseAsync(indexName, null, context) - .onErrorMap(MappingUtils::exceptionMapper); - } catch (RuntimeException ex) { - return monoError(LOGGER, ex); - } - } - - /** - * Returns statistics for the given index, including a document count and storage usage. - * - *

Code Sample

- * - *

Get search index "searchIndex" statistics.

- * - * - *
-     * SEARCH_INDEX_ASYNC_CLIENT.getIndexStatistics("searchIndex")
-     *     .subscribe(statistics ->
-     *         System.out.printf("There are %d documents and storage size of %d available in 'searchIndex'.%n",
-     *         statistics.getDocumentCount(), statistics.getStorageSize()));
-     * 
- * - * - * @param indexName the name of the index for which to retrieve statistics - * @return the index statistics result. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono getIndexStatistics(String indexName) { - return getIndexStatisticsWithResponse(indexName).map(Response::getValue); - } - - /** - * Returns statistics for the given index, including a document count and storage usage. - * - *

Code Sample

- * - *

Get search index "searchIndex" statistics.

- * - * - *
-     * SEARCH_INDEX_ASYNC_CLIENT.getIndexStatisticsWithResponse("searchIndex")
-     *     .subscribe(statistics -> System.out.printf("The status code of the response is %s.%n"
-     *             + "There are %d documents and storage size of %d available in 'searchIndex'.%n",
-     *         statistics.getStatusCode(), statistics.getValue().getDocumentCount(),
-     *         statistics.getValue().getStorageSize()));
-     * 
- * - * - * @param indexName the name of the index for which to retrieve statistics - * @return a response containing the index statistics result. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> getIndexStatisticsWithResponse(String indexName) { - return withContext(context -> getIndexStatisticsWithResponse(indexName, context)); - } - - Mono> getIndexStatisticsWithResponse(String indexName, Context context) { - try { - return restClient.getIndexes() - .getStatisticsWithResponseAsync(indexName, null, context) - .onErrorMap(MappingUtils::exceptionMapper); - } catch (RuntimeException ex) { - return monoError(LOGGER, ex); - } - } - - /** - * Lists all indexes available for an Azure AI Search service. - * - *

Code Sample

- * - *

List all search indexes.

- * - * - *
-     * SEARCH_INDEX_ASYNC_CLIENT.listIndexes()
-     *     .subscribe(index ->
-     *         System.out.printf("The index name is %s. The ETag of index is %s.%n", index.getName(),
-     *             index.getETag()));
-     * 
- * - * - * @return a reactive response emitting the list of indexes. - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - public PagedFlux listIndexes() { - try { - return new PagedFlux<>(() -> withContext(context -> this.listIndexesWithResponse(null, context))); - } catch (RuntimeException ex) { - return pagedFluxError(LOGGER, ex); - } - } - - /** - * Lists all indexes names for an Azure AI Search service. - * - *

Code Sample

- * - *

List all search indexes names.

- * - * - *
-     * SEARCH_INDEX_ASYNC_CLIENT.listIndexNames()
-     *     .subscribe(indexName -> System.out.printf("The index name is %s.%n", indexName));
-     * 
- * - * - * @return a reactive response emitting the list of index names. - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - public PagedFlux listIndexNames() { - try { - return new PagedFlux<>(() -> withContext(context -> this.listIndexesWithResponse("name", context)) - .map(MappingUtils::mappingPagingSearchIndexNames)); - } catch (RuntimeException ex) { - return pagedFluxError(LOGGER, ex); - } - } - - private Mono> listIndexesWithResponse(String select, Context context) { - return restClient.getIndexes() - .listSinglePageAsync(select, null, context) - .onErrorMap(MappingUtils::exceptionMapper); - } - - /** - * Creates a new Azure AI Search index or updates an index if it already exists. - * - *

Code Sample

- * - *

Create or update search index named "searchIndex".

- * - * - *
-     * SEARCH_INDEX_ASYNC_CLIENT.getIndex("searchIndex")
-     *     .doOnNext(indexFromService -> indexFromService.setSuggesters(Collections.singletonList(
-     *         new SearchSuggester("sg", Collections.singletonList("hotelName")))))
-     *     .flatMap(SEARCH_INDEX_ASYNC_CLIENT::createOrUpdateIndex)
-     *     .subscribe(updatedIndex ->
-     *         System.out.printf("The index name is %s. The suggester name of index is %s.%n",
-     *             updatedIndex.getName(), updatedIndex.getSuggesters().get(0).getName()));
-     * 
- * - * - * @param index the definition of the {@link SearchIndex} to create or update. - * @return the index that was created or updated. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono createOrUpdateIndex(SearchIndex index) { - return createOrUpdateIndexWithResponse(index, false, false).map(Response::getValue); - } - - /** - * Creates a new Azure AI Search index or updates an index if it already exists. - * - *

Code Sample

- * - *

Create or update search index named "searchIndex".

- * - * - *
-     * SearchIndex indexFromService = SEARCH_INDEX_CLIENT.getIndex("searchIndex");
-     * indexFromService.setSuggesters(Collections.singletonList(new SearchSuggester("sg",
-     *     Collections.singletonList("hotelName"))));
-     * Response<SearchIndex> updatedIndexResponse = SEARCH_INDEX_CLIENT.createOrUpdateIndexWithResponse(indexFromService, true,
-     *     false, new Context(KEY_1, VALUE_1));
-     * System.out.printf("The status code of the normal response is %s.%n"
-     *         + "The index name is %s. The ETag of index is %s.%n", updatedIndexResponse.getStatusCode(),
-     *     updatedIndexResponse.getValue().getName(), updatedIndexResponse.getValue().getETag());
-     * 
- * - * - * @param index the definition of the index to create or update - * @param allowIndexDowntime 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 - * @param onlyIfUnchanged {@code true} to update if the {@code index} is the same as the current service value. - * {@code false} to always update existing value. - * @return a response containing the index that was created or updated - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> createOrUpdateIndexWithResponse(SearchIndex index, boolean allowIndexDowntime, - boolean onlyIfUnchanged) { - return withContext( - context -> createOrUpdateIndexWithResponse(index, allowIndexDowntime, onlyIfUnchanged, context)); - } - - Mono> createOrUpdateIndexWithResponse(SearchIndex index, boolean allowIndexDowntime, - boolean onlyIfUnchanged, Context context) { - try { - Objects.requireNonNull(index, "'Index' cannot null."); - String ifMatch = onlyIfUnchanged ? index.getETag() : null; - return restClient.getIndexes() - .createOrUpdateWithResponseAsync(index.getName(), index, allowIndexDowntime, ifMatch, null, null, - context) - .onErrorMap(MappingUtils::exceptionMapper); - } catch (RuntimeException ex) { - return monoError(LOGGER, ex); - } - } - - /** - * Deletes an Azure AI Search index and all the documents it contains. - * - *

Code Sample

- * - *

Delete search index with name "searchIndex".

- * - * - *
-     * SEARCH_INDEX_ASYNC_CLIENT.deleteIndex("searchIndex")
-     *     .subscribe();
-     * 
- * - * - * @param indexName the name of the index to delete - * @return a response signalling completion. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono deleteIndex(String indexName) { - return deleteIndexWithResponse(indexName, null, null).flatMap(FluxUtil::toMono); - } - - /** - * Deletes an Azure AI Search index and all the documents it contains. - * - *

Code Sample

- * - *

Delete search index with name "searchIndex".

- * - * - *
-     * SEARCH_INDEX_ASYNC_CLIENT.getIndex("searchIndex")
-     *     .flatMap(indexFromService -> SEARCH_INDEX_ASYNC_CLIENT.deleteIndexWithResponse(indexFromService, true))
-     *     .subscribe(deleteResponse ->
-     *         System.out.printf("The status code of the response is %d.%n", deleteResponse.getStatusCode()));
-     * 
- * - * - * @param index the {@link SearchIndex} to delete. - * @param onlyIfUnchanged {@code true} to delete if the {@code index} is the same as the current service value. - * {@code false} to always delete existing value. - * @return a response signalling completion. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> deleteIndexWithResponse(SearchIndex index, boolean onlyIfUnchanged) { - if (index == null) { - return monoError(LOGGER, new NullPointerException("'index' cannot be null.")); - } - - return withContext( - context -> deleteIndexWithResponse(index.getName(), onlyIfUnchanged ? index.getETag() : null, context)); - } - - Mono> deleteIndexWithResponse(String indexName, String eTag, Context context) { - try { - return restClient.getIndexes() - .deleteWithResponseAsync(indexName, eTag, null, null, context) - .onErrorMap(MappingUtils::exceptionMapper) - .map(Function.identity()); - } catch (RuntimeException ex) { - return monoError(LOGGER, ex); - } - } - - /** - * Shows how an analyzer breaks text into tokens. - * - *

Code Sample

- * - *

Analyzer text with LexicalTokenizerName "Classic" in search index "searchIndex".

- * - * - *
-     * SEARCH_INDEX_ASYNC_CLIENT.analyzeText("searchIndex",
-     *     new AnalyzeTextOptions("The quick brown fox", LexicalTokenizerName.CLASSIC))
-     *     .subscribe(tokenInfo ->
-     *         System.out.printf("The token emitted by the analyzer is %s.%n", tokenInfo.getToken()));
-     * 
- * - * - * @param indexName the name of the index for which to test an analyzer - * @param analyzeTextOptions the text and analyzer or analysis components to test - * @return a response containing analyze result. - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - public PagedFlux analyzeText(String indexName, AnalyzeTextOptions analyzeTextOptions) { - try { - return new PagedFlux<>( - () -> withContext(context -> analyzeTextWithResponse(indexName, analyzeTextOptions, context))); - } catch (RuntimeException ex) { - return pagedFluxError(LOGGER, ex); - } - } - - private Mono> analyzeTextWithResponse(String indexName, - AnalyzeTextOptions analyzeTextOptions, Context context) { - return restClient.getIndexes() - .analyzeWithResponseAsync(indexName, AnalyzeRequestConverter.map(analyzeTextOptions), null, context) - .onErrorMap(MappingUtils::exceptionMapper) - .map(MappingUtils::mappingTokenInfo); - } - - /** - * Creates a new Azure AI Search synonym map. - * - *

Code Sample

- * - *

Create synonym map named "synonymMap".

- * - * - *
-     * SynonymMap synonymMap = new SynonymMap("synonymMap",
-     *     "United States, United States of America, USA\nWashington, Wash. => WA");
-     * SEARCH_INDEX_ASYNC_CLIENT.createSynonymMap(synonymMap)
-     *     .subscribe(synonymMapFromService ->
-     *         System.out.printf("The synonym map name is %s. The ETag of synonym map is %s.%n",
-     *         synonymMapFromService.getName(), synonymMapFromService.getETag()));
-     * 
- * - * - * @param synonymMap the definition of the synonym map to create - * @return the created {@link SynonymMap}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono createSynonymMap(SynonymMap synonymMap) { - return createSynonymMapWithResponse(synonymMap).map(Response::getValue); - } - - /** - * Creates a new Azure AI Search synonym map. - * - *

Code Sample

- * - *

Create synonym map named "synonymMap".

- * - * - *
-     * SynonymMap synonymMap = new SynonymMap("synonymMap",
-     *     "United States, United States of America, USA\nWashington, Wash. => WA");
-     * SEARCH_INDEX_ASYNC_CLIENT.createSynonymMapWithResponse(synonymMap)
-     *     .subscribe(synonymMapFromService ->
-     *         System.out.printf("The status code of the response is %d.%n"
-     *             + "The synonym map name is %s. The ETag of synonym map is %s.%n",
-     *             synonymMapFromService.getStatusCode(),
-     *         synonymMapFromService.getValue().getName(), synonymMapFromService.getValue().getETag()));
-     * 
- * - * - * @param synonymMap the definition of the {@link SynonymMap} to create - * @return a response containing the created SynonymMap. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> createSynonymMapWithResponse(SynonymMap synonymMap) { - return withContext(context -> createSynonymMapWithResponse(synonymMap, context)); - } - - Mono> createSynonymMapWithResponse(SynonymMap synonymMap, Context context) { - try { - Objects.requireNonNull(synonymMap, "'synonymMap' cannot be null."); - return restClient.getSynonymMaps() - .createWithResponseAsync(synonymMap, null, context) - .onErrorMap(MappingUtils::exceptionMapper); - } catch (RuntimeException ex) { - return monoError(LOGGER, ex); - } - } - - /** - * Retrieves a synonym map definition. - * - *

Code Sample

- * - *

Get synonym map with name "synonymMap".

- * - * - *
-     * SEARCH_INDEX_ASYNC_CLIENT.getSynonymMap("synonymMap")
-     *     .subscribe(synonymMapFromService ->
-     *         System.out.printf("The synonym map is %s. The ETag of synonym map is %s.%n",
-     *             synonymMapFromService.getName(), synonymMapFromService.getETag()));
-     * 
- * - * - * @param synonymMapName name of the synonym map to retrieve - * @return the {@link SynonymMap} definition - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono getSynonymMap(String synonymMapName) { - return getSynonymMapWithResponse(synonymMapName).map(Response::getValue); - } - - /** - * Retrieves a synonym map definition. - * - *

Code Sample

- * - *

Get synonym map with name "synonymMap".

- * - * - *
-     * SEARCH_INDEX_ASYNC_CLIENT.getSynonymMap("synonymMap")
-     *     .subscribe(synonymMapFromService ->
-     *         System.out.printf("The synonym map is %s. The ETag of synonym map is %s.%n",
-     *             synonymMapFromService.getName(), synonymMapFromService.getETag()));
-     * 
- * - * - * @param synonymMapName name of the synonym map to retrieve - * @return a response containing the SynonymMap. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> getSynonymMapWithResponse(String synonymMapName) { - return withContext(context -> getSynonymMapWithResponse(synonymMapName, context)); - } - - Mono> getSynonymMapWithResponse(String synonymMapName, Context context) { - try { - return restClient.getSynonymMaps() - .getWithResponseAsync(synonymMapName, null, context) - .onErrorMap(MappingUtils::exceptionMapper); - } catch (RuntimeException ex) { - return monoError(LOGGER, ex); - } - } - - /** - * Lists all synonym maps available for an Azure AI Search service. - * - *

Code Sample

- * - *

List all synonym maps.

- * - * - *
-     * SEARCH_INDEX_ASYNC_CLIENT.listSynonymMaps()
-     *     .subscribe(synonymMap -> System.out.printf("The synonymMap name is %s. The ETag of synonymMap is %s.%n",
-     *         synonymMap.getName(), synonymMap.getETag()));
-     * 
- * - * - * @return a reactive response emitting the list of synonym maps. - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - public PagedFlux listSynonymMaps() { - try { - return new PagedFlux<>(() -> withContext(context -> listSynonymMapsWithResponse(null, context)) - .map(MappingUtils::mappingPagingSynonymMap)); - } catch (RuntimeException ex) { - return pagedFluxError(LOGGER, ex); - } - } - - /** - * Lists all synonym map names for an Azure AI Search service. - * - *

Code Sample

- * - *

List all synonym map names.

- * - * - *
-     * SEARCH_INDEX_ASYNC_CLIENT.listSynonymMapNames()
-     *     .subscribe(synonymMap -> System.out.printf("The synonymMap name is %s.%n", synonymMap));
-     * 
- * - * - * @return a reactive response emitting the list of synonym map names. - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - public PagedFlux listSynonymMapNames() { - try { - return new PagedFlux<>(() -> withContext(context -> listSynonymMapsWithResponse("name", context)) - .map(MappingUtils::mappingPagingSynonymMapNames)); - } catch (RuntimeException ex) { - return pagedFluxError(LOGGER, ex); - } - } - - private Mono> listSynonymMapsWithResponse(String select, Context context) { - return restClient.getSynonymMaps() - .listWithResponseAsync(select, null, context) - .onErrorMap(MappingUtils::exceptionMapper); - } - - /** - * Creates a new Azure AI Search synonym map or updates a synonym map if it already exists. - * - *

Code Sample

- * - *

Create or update synonym map named "synonymMap".

- * - * - *
-     * SEARCH_INDEX_ASYNC_CLIENT.getSynonymMap("searchIndex")
-     *     .doOnNext(synonymMap -> synonymMap
-     *         .setSynonyms("United States, United States of America, USA, America\nWashington, Wash. => WA"))
-     *     .flatMap(SEARCH_INDEX_ASYNC_CLIENT::createOrUpdateSynonymMap)
-     *     .subscribe(updatedSynonymMap ->
-     *         System.out.printf("The synonym map name is %s. The synonyms are %s.%n", updatedSynonymMap.getName(),
-     *         updatedSynonymMap.getSynonyms()));
-     * 
- * - * - * @param synonymMap the definition of the {@link SynonymMap} to create or update - * @return the synonym map that was created or updated. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono createOrUpdateSynonymMap(SynonymMap synonymMap) { - return createOrUpdateSynonymMapWithResponse(synonymMap, false).map(Response::getValue); - } - - /** - * Creates a new Azure AI Search synonym map or updates a synonym map if it already exists. - * - *

Code Sample

- * - *

Create or update synonym map named "synonymMap".

- * - * - *
-     * SEARCH_INDEX_ASYNC_CLIENT.getSynonymMap("searchIndex")
-     *     .flatMap(synonymMap -> {
-     *         synonymMap.setSynonyms(
-     *             "United States, United States of America, USA, America\nWashington, Wash. => WA");
-     *         return SEARCH_INDEX_ASYNC_CLIENT.createOrUpdateSynonymMapWithResponse(synonymMap, true);
-     *     })
-     *     .subscribe(updatedSynonymMap ->
-     *         System.out.printf("The status code of the normal response is %s.%n"
-     *             + "The synonym map name is %s. The synonyms are %s.%n", updatedSynonymMap.getStatusCode(),
-     *         updatedSynonymMap.getValue().getName(), updatedSynonymMap.getValue().getSynonyms()));
-     * 
- * - * - * @param synonymMap the definition of the {@link SynonymMap} to create or update - * @param onlyIfUnchanged {@code true} to update if the {@code synonymMap} is the same as the current service value. - * {@code false} to always update existing value. - * @return a response containing the synonym map that was created or updated. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> createOrUpdateSynonymMapWithResponse(SynonymMap synonymMap, - boolean onlyIfUnchanged) { - return withContext(context -> createOrUpdateSynonymMapWithResponse(synonymMap, onlyIfUnchanged, context)); - } - - Mono> createOrUpdateSynonymMapWithResponse(SynonymMap synonymMap, boolean onlyIfUnchanged, - Context context) { - try { - Objects.requireNonNull(synonymMap, "'synonymMap' cannot be null."); - String ifMatch = onlyIfUnchanged ? synonymMap.getETag() : null; - return restClient.getSynonymMaps() - .createOrUpdateWithResponseAsync(synonymMap.getName(), synonymMap, ifMatch, null, null, context) - .onErrorMap(MappingUtils::exceptionMapper); - } catch (RuntimeException ex) { - return monoError(LOGGER, ex); - } - } - - /** - * Deletes an Azure AI Search synonym map. - * - *

Code Sample

- * - *

Delete synonym map with name "synonymMap".

- * - * - *
-     * SEARCH_INDEX_ASYNC_CLIENT.deleteSynonymMap("synonymMap")
-     *     .subscribe();
-     * 
- * - * - * @param synonymMapName the name of the {@link SynonymMap} to delete - * @return a response signalling completion. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono deleteSynonymMap(String synonymMapName) { - return withContext( - context -> deleteSynonymMapWithResponse(synonymMapName, null, context).flatMap(FluxUtil::toMono)); - } - - /** - * Deletes an Azure AI Search synonym map. - * - *

Code Sample

- * - *

Delete synonym map with name "synonymMap".

- * - * - *
-     * SEARCH_INDEX_ASYNC_CLIENT.getSynonymMap("synonymMap")
-     *     .flatMap(synonymMap -> SEARCH_INDEX_ASYNC_CLIENT.deleteSynonymMapWithResponse(synonymMap, true))
-     *     .subscribe(response -> System.out.println("The status code of the response is" + response.getStatusCode()));
-     * 
- * - * - * @param synonymMap the {@link SynonymMap} to delete. - * @param onlyIfUnchanged {@code true} to delete if the {@code synonymMap} is the same as the current service value. - * {@code false} to always delete existing value. - * @return a response signalling completion. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> deleteSynonymMapWithResponse(SynonymMap synonymMap, boolean onlyIfUnchanged) { - if (synonymMap == null) { - return monoError(LOGGER, new NullPointerException("'synonymMap' cannot be null.")); - } - - return withContext(context -> deleteSynonymMapWithResponse(synonymMap.getName(), - onlyIfUnchanged ? synonymMap.getETag() : null, context)); - } - - /** - * Convenience method to convert a {@link Class Class's} {@link Field Fields} and {@link Method Methods} into {@link - * SearchField SearchFields} to help aid the creation of a {@link SearchField} which represents the {@link Class}. - * - * @param model The model {@link Class} that will have {@link SearchField SearchFields} generated from its - * structure. - * @param options Configuration used to determine generation of the {@link SearchField SearchFields}. - * @return A list {@link SearchField SearchFields} which represent the model {@link Class}. - */ - public static List buildSearchFields(Class model, FieldBuilderOptions options) { - return FieldBuilder.build(model, options); - } - - Mono> deleteSynonymMapWithResponse(String synonymMapName, String etag, Context context) { - try { - return restClient.getSynonymMaps() - .deleteWithResponseAsync(synonymMapName, etag, null, null, context) - .onErrorMap(MappingUtils::exceptionMapper) - .map(Function.identity()); - } catch (RuntimeException ex) { - return monoError(LOGGER, ex); - } - } - - /** - * Returns service level statistics for a search service, including service counters and limits. - *

- * Contains the tracking ID sent with the request to help with debugging - * - *

Code Sample

- * - *

Get service statistics.

- * - * - *
-     * SEARCH_INDEX_ASYNC_CLIENT.getServiceStatistics()
-     *     .subscribe(serviceStatistics -> System.out.printf("There are %s search indexes in your service.%n",
-     *         serviceStatistics.getCounters().getIndexCounter()));
-     * 
- * - * - * @return the search service statistics result. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono getServiceStatistics() { - return getServiceStatisticsWithResponse().map(Response::getValue); - } - - /** - * Returns service level statistics for a search service, including service counters and limits. - * - *

Code Sample

- * - *

Get service statistics.

- * - * - *
-     * SEARCH_INDEX_ASYNC_CLIENT.getServiceStatisticsWithResponse()
-     *     .subscribe(serviceStatistics ->
-     *         System.out.printf("The status code of the response is %s.%n"
-     *                 + "There are %s search indexes in your service.%n",
-     *         serviceStatistics.getStatusCode(),
-     *         serviceStatistics.getValue().getCounters().getIndexCounter()));
-     * 
- * - * - * @return the search service statistics result. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> getServiceStatisticsWithResponse() { - return withContext(this::getServiceStatisticsWithResponse); - } - - Mono> getServiceStatisticsWithResponse(Context context) { - try { - return restClient.getServiceStatisticsWithResponseAsync(null, context) - .onErrorMap(MappingUtils::exceptionMapper); - } catch (RuntimeException ex) { - return monoError(LOGGER, ex); - } - } -} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/SearchIndexClient.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/SearchIndexClient.java deleted file mode 100644 index 7c15ac68fa96..000000000000 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/SearchIndexClient.java +++ /dev/null @@ -1,1279 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -package com.azure.search.documents.indexes; - -import com.azure.core.annotation.ReturnType; -import com.azure.core.annotation.ServiceClient; -import com.azure.core.annotation.ServiceMethod; -import com.azure.core.http.HttpPipeline; -import com.azure.core.http.rest.PagedIterable; -import com.azure.core.http.rest.PagedResponse; -import com.azure.core.http.rest.Response; -import com.azure.core.util.Context; -import com.azure.core.util.logging.ClientLogger; -import com.azure.core.util.serializer.JsonSerializer; -import com.azure.search.documents.SearchClient; -import com.azure.search.documents.SearchServiceVersion; -import com.azure.search.documents.implementation.converters.AnalyzeRequestConverter; -import com.azure.search.documents.implementation.util.MappingUtils; -import com.azure.search.documents.implementation.util.Utility; -import com.azure.search.documents.indexes.implementation.SearchServiceClientImpl; -import com.azure.search.documents.indexes.implementation.models.ListSynonymMapsResult; -import com.azure.search.documents.indexes.models.AnalyzeTextOptions; -import com.azure.search.documents.indexes.models.AnalyzedTokenInfo; -import com.azure.search.documents.indexes.models.FieldBuilderOptions; -import com.azure.search.documents.indexes.models.LexicalAnalyzerName; -import com.azure.search.documents.indexes.models.LexicalTokenizerName; -import com.azure.search.documents.indexes.models.SearchField; -import com.azure.search.documents.indexes.models.SearchIndex; -import com.azure.search.documents.indexes.models.SearchIndexStatistics; -import com.azure.search.documents.indexes.models.SearchServiceStatistics; -import com.azure.search.documents.indexes.models.SynonymMap; - -import java.lang.reflect.Field; -import java.lang.reflect.Method; -import java.util.List; -import java.util.Objects; - -import static com.azure.search.documents.indexes.SearchIndexAsyncClient.getSearchClientBuilder; - -/** - * This class provides a client that contains the operations for creating, getting, listing, updating, or deleting - * indexes or synonym map and analyzing text in an Azure AI Search service. - * - *

- * Overview - *

- * - *

- * An index is stored on your search service and populated with JSON documents that are indexed and tokenized for - * information retrieval. The fields collection of an index defines the structure of the search document. Fields - * have a name, data types, and attributes that determine how it's used. For example, searchable fields are used in - * full text search, and thus tokenized during indexing. An index also defines other constructs, such as scoring - * profiles for relevance tuning, suggesters, semantic configurations, and custom analyzers. - *

- * - *

- * A synonym map is service-level object that contains user-defined synonyms. This object is maintained - * independently from search indexes. Once uploaded, you can point any searchable field to the synonym map (one per field). - *

- * - *

- * This client provides a synchronous API for accessing indexes. This client allows you to create, delete, update, - * and configure search indexes. The client also allows you to declare custom synonym maps to expand or rewrite - * queries. - *

- * - *

- * Getting Started - *

- * - *

- * Authenticating and building instances of this client are handled by {@link SearchIndexClientBuilder}. This - * sample shows you how to create an instance of the client: - *

- * - * - *
- * SearchIndexClient searchIndexClient = new SearchIndexClientBuilder()
- *     .credential(new AzureKeyCredential("{key}"))
- *     .endpoint("{endpoint}")
- *     .buildClient();
- * 
- * - *

- * For more information on authentication and building, see the documentation for {@link SearchIndexClientBuilder}. - *

- * - *
- * - *

- * Examples - *

- * - *

- * The following examples all use a simple Hotel - * data set that you can - * import into your own index from the Azure portal. - * These are just a few of the basics - please check out our Samples for much more. - *

- * - *

- * Create an Index - *

- * - *

- * The following sample creates an index. - *

- * - * - *
- * SearchIndex searchIndex = new SearchIndex("indexName", Arrays.asList(
- *     new SearchField("hotelId", SearchFieldDataType.STRING)
- *         .setKey(true)
- *         .setFilterable(true)
- *         .setSortable(true),
- *     new SearchField("hotelName", SearchFieldDataType.STRING)
- *         .setSearchable(true)
- *         .setFilterable(true)
- *         .setSortable(true),
- *     new SearchField("description", SearchFieldDataType.STRING)
- *         .setSearchable(true)
- *         .setAnalyzerName(LexicalAnalyzerName.EN_LUCENE),
- *     new SearchField("descriptionFr", SearchFieldDataType.STRING)
- *         .setSearchable(true)
- *         .setAnalyzerName(LexicalAnalyzerName.FR_LUCENE),
- *     new SearchField("tags", SearchFieldDataType.collection(SearchFieldDataType.STRING))
- *         .setSearchable(true)
- *         .setFilterable(true)
- *         .setFacetable(true),
- *     new SearchField("address", SearchFieldDataType.COMPLEX)
- *         .setFields(
- *             new SearchField("streetAddress", SearchFieldDataType.STRING)
- *                 .setSearchable(true),
- *             new SearchField("city", SearchFieldDataType.STRING)
- *                 .setFilterable(true)
- *                 .setSortable(true)
- *                 .setFacetable(true),
- *             new SearchField("stateProvince", SearchFieldDataType.STRING)
- *                 .setSearchable(true)
- *                 .setFilterable(true)
- *                 .setSortable(true)
- *                 .setFacetable(true),
- *             new SearchField("country", SearchFieldDataType.STRING)
- *                 .setSearchable(true)
- *                 .setSynonymMapNames("synonymMapName")
- *                 .setFilterable(true)
- *                 .setSortable(true)
- *                 .setFacetable(true),
- *             new SearchField("postalCode", SearchFieldDataType.STRING)
- *                 .setSearchable(true)
- *                 .setFilterable(true)
- *                 .setSortable(true)
- *                 .setFacetable(true))
- * ));
- *
- * searchIndexClient.createIndex(searchIndex);
- * 
- * - * - * For an asynchronous sample see {@link SearchIndexAsyncClient#createIndex(SearchIndex)}. - * - * - *

- * List indexes - *

- * - *

- * The following sample lists all indexes. - *

- * - * - *
- * searchIndexClient.listIndexes().forEach(index -> System.out.println(index.getName()));
- * 
- * - * - * For an asynchronous sample see {@link SearchIndexAsyncClient#listIndexes()}. - * - * - *

- * Retrieve an Index - *

- * - *

- * The following sample retrieves an index. - *

- * - * - *
- * SearchIndex searchIndex = searchIndexClient.getIndex("indexName");
- * if (searchIndex != null) {
- *     System.out.println("The ETag of the index is " + searchIndex.getETag());
- * }
- * 
- * - * - * - * For an asynchronous sample see {@link SearchIndexAsyncClient#getIndex(String)}. - * - * - * - * - *

- * Update an Index - *

- * - *

- * The following sample updates an index. - *

- * - * - *
- * SearchIndex searchIndex = searchIndexClient.getIndex("indexName");
- * if (searchIndex != null) {
- *     searchIndex.setFields(new SearchField("newField", SearchFieldDataType.STRING));
- *     searchIndexClient.createOrUpdateIndex(searchIndex);
- * }
- * 
- * - * - * - * For an asynchronous sample see {@link SearchIndexAsyncClient#createOrUpdateIndex(SearchIndex)}. - * - * - * - * - *

- * Delete an Index - *

- * - *

- * The following sample deletes an index. - *

- * - *
- * String indexName = "indexName";
- * searchIndexClient.deleteIndex(indexName);
- * 
- * - * - * For an asynchronous sample see {@link SearchIndexAsyncClient#deleteIndex(String)}. - * - * - * - * - *

- * Create a Synonym Map - *

- * - *

- * The following sample creates a synonym map. - *

- * - * - *
- * SynonymMap synonymMap = new SynonymMap("synonymMapName", "hotel, motel, \"motor inn\"");
- * searchIndexClient.createSynonymMap(synonymMap);
- * 
- * - * - * - * For an asynchronous sample see {@link SearchIndexAsyncClient#createSynonymMap(SynonymMap)}. - * - * - * - * - *

- * List Synonym Maps - *

- * - *

- * The following sample lists all synonym maps. - *

- * - * - *
- * searchIndexClient.listSynonymMaps().forEach(synonymMap -> System.out.println(synonymMap.getName()));
- * 
- * - * - * - * For an asynchronous sample see {@link SearchIndexAsyncClient#listSynonymMaps()}. - * - * - * - * - *

- * Retrieve a Synonym Map - *

- * - *

- * The following sample retrieves a synonym map. - *

- * - *
- * SynonymMap synonymMap = searchIndexClient.getSynonymMap("synonymMapName");
- * if (synonymMap != null) {
- *     System.out.println("The ETag of the synonymMap is " + synonymMap.getETag());
- * }
- * 
- * - * - * For an asynchronous sample see {@link SearchIndexAsyncClient#getSynonymMap(String)}. - * - * - * - * - *

- * Update a Synonym Map - *

- * - *

- * The following sample updates a synonym map. - *

- * - *
- * SynonymMap synonymMap = searchIndexClient.getSynonymMap("synonymMapName");
- * if (synonymMap != null) {
- *     synonymMap.setSynonyms("inn,hotel,motel");
- *     searchIndexClient.createOrUpdateSynonymMap(synonymMap);
- * }
- * 
- * - * - * For an asynchronous sample see {@link SearchIndexAsyncClient#createOrUpdateSynonymMap(SynonymMap)}. - * - * - * - * - *

- * Delete a Synonym Map - *

- * - *

- * The following sample deletes a synonym map. - *

- * - * - *
- * String synonymMapName = "synonymMapName";
- * searchIndexClient.deleteSynonymMap(synonymMapName);
- * 
- * - * - * - * For an asynchronous sample see {@link SearchIndexAsyncClient#deleteSynonymMap(String)}. - * - * - * - * @see SearchIndexAsyncClient - * @see SearchIndexClientBuilder - * @see com.azure.search.documents.indexes - */ -@ServiceClient(builder = SearchIndexClientBuilder.class) -public final class SearchIndexClient { - private static final ClientLogger LOGGER = new ClientLogger(SearchIndexClient.class); - - /** - * Search REST API Version - */ - private final SearchServiceVersion serviceVersion; - - /** - * The endpoint for the Azure AI Search service. - */ - private final String endpoint; - - /** - * The underlying AutoRest client used to interact with the Search service - */ - private final SearchServiceClientImpl restClient; - - private final JsonSerializer serializer; - - /** - * The pipeline that powers this client. - */ - private final HttpPipeline httpPipeline; - - SearchIndexClient(String endpoint, SearchServiceVersion serviceVersion, HttpPipeline httpPipeline, - JsonSerializer serializer) { - this.endpoint = endpoint; - this.serviceVersion = serviceVersion; - this.httpPipeline = httpPipeline; - this.serializer = serializer; - this.restClient = new SearchServiceClientImpl(httpPipeline, endpoint, serviceVersion.getVersion()); - } - - /** - * Gets the {@link HttpPipeline} powering this client. - * - * @return the pipeline. - */ - HttpPipeline getHttpPipeline() { - return this.httpPipeline; - } - - /** - * Gets the endpoint for the Azure AI Search service. - * - * @return the endpoint value. - */ - public String getEndpoint() { - return this.endpoint; - } - - /** - * Initializes a new {@link SearchClient} using the given Index name and the same configuration as the - * SearchServiceClient. - * - * @param indexName the name of the Index for the client - * @return a {@link SearchClient} created from the service client configuration - */ - public SearchClient getSearchClient(String indexName) { - return getSearchClientBuilder(indexName, endpoint, serviceVersion, httpPipeline, serializer).buildClient(); - } - - /** - * Creates a new Azure AI Search index - * - *

Code Sample

- * - *

Create search index named "searchIndex".

- * - * - *
-     * List<SearchField> searchFields = Arrays.asList(
-     *     new SearchField("hotelId", SearchFieldDataType.STRING).setKey(true),
-     *     new SearchField("hotelName", SearchFieldDataType.STRING).setSearchable(true)
-     * );
-     * SearchIndex searchIndex = new SearchIndex("searchIndex", searchFields);
-     * SearchIndex indexFromService = SEARCH_INDEX_CLIENT.createIndex(searchIndex);
-     * System.out.printf("The index name is %s. The ETag of index is %s.%n", indexFromService.getName(),
-     *     indexFromService.getETag());
-     * 
- * - * - * @param index definition of the index to create - * @return the created Index. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public SearchIndex createIndex(SearchIndex index) { - return createIndexWithResponse(index, Context.NONE).getValue(); - } - - /** - * Creates a new Azure AI Search index - * - *

Code Sample

- * - *

Create search index named "searchIndex".

- * - * - *
-     * List<SearchField> searchFields = Arrays.asList(
-     *     new SearchField("hotelId", SearchFieldDataType.STRING).setKey(true),
-     *     new SearchField("hotelName", SearchFieldDataType.STRING).setSearchable(true)
-     * );
-     * SearchIndex searchIndex = new SearchIndex("searchIndex", searchFields);
-     *
-     * Response<SearchIndex> indexFromServiceResponse =
-     *     SEARCH_INDEX_CLIENT.createIndexWithResponse(searchIndex, new Context(KEY_1, VALUE_1));
-     * System.out.printf("The status code of the response is %s. The index name is %s.%n",
-     *     indexFromServiceResponse.getStatusCode(), indexFromServiceResponse.getValue().getName());
-     * 
- * - * - * @param index definition of the index to create - * @param context additional context that is passed through the HTTP pipeline during the service call - * @return a response containing the created Index. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Response createIndexWithResponse(SearchIndex index, Context context) { - return Utility.executeRestCallWithExceptionHandling(() -> { - Objects.requireNonNull(index, "'Index' cannot be null"); - return restClient.getIndexes().createWithResponse(index, null, context); - }, LOGGER); - } - - /** - * Retrieves an index definition from the Azure AI Search. - * - *

Code Sample

- * - *

Get search index with name "searchIndex".

- * - * - *
-     * SearchIndex indexFromService =
-     *     SEARCH_INDEX_CLIENT.getIndex("searchIndex");
-     * System.out.printf("The index name is %s. The ETag of index is %s.%n", indexFromService.getName(),
-     *     indexFromService.getETag());
-     * 
- * - * - * @param indexName the name of the index to retrieve - * @return the Index. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public SearchIndex getIndex(String indexName) { - return getIndexWithResponse(indexName, Context.NONE).getValue(); - } - - /** - * Retrieves an index definition from the Azure AI Search. - * - *

Code Sample

- * - *

Get search index with "searchIndex.

- * - * - *
-     * Response<SearchIndex> indexFromServiceResponse =
-     *     SEARCH_INDEX_CLIENT.getIndexWithResponse("searchIndex", new Context(KEY_1, VALUE_1));
-     *
-     * System.out.printf("The status code of the response is %s. The index name is %s.%n",
-     *     indexFromServiceResponse.getStatusCode(), indexFromServiceResponse.getValue().getName());
-     * 
- * - * - * @param indexName the name of the index to retrieve - * @param context additional context that is passed through the HTTP pipeline during the service call - * @return a response containing the Index. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Response getIndexWithResponse(String indexName, Context context) { - return Utility.executeRestCallWithExceptionHandling( - () -> restClient.getIndexes().getWithResponse(indexName, null, context), LOGGER); - } - - /** - * Returns statistics for the given index, including a document count and storage usage. - * - *

Code Sample

- * - *

Get search index "searchIndex" statistics.

- * - * - *
-     * SearchIndexStatistics statistics = SEARCH_INDEX_CLIENT.getIndexStatistics("searchIndex");
-     * System.out.printf("There are %d documents and storage size of %d available in 'searchIndex'.%n",
-     *     statistics.getDocumentCount(), statistics.getStorageSize());
-     * 
- * - * - * @param indexName the name of the index for which to retrieve statistics - * @return the index statistics result. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public SearchIndexStatistics getIndexStatistics(String indexName) { - return getIndexStatisticsWithResponse(indexName, Context.NONE).getValue(); - } - - /** - * Returns statistics for the given index, including a document count and storage usage. - * - *

Code Sample

- * - *

Get search index "searchIndex" statistics.

- * - * - *
-     * Response<SearchIndexStatistics> statistics = SEARCH_INDEX_CLIENT.getIndexStatisticsWithResponse("searchIndex",
-     *     new Context(KEY_1, VALUE_1));
-     * System.out.printf("The status code of the response is %s.%n"
-     *         + "There are %d documents and storage size of %d available in 'searchIndex'.%n",
-     *     statistics.getStatusCode(), statistics.getValue().getDocumentCount(),
-     *     statistics.getValue().getStorageSize());
-     * 
- * - * - * @param indexName the name of the index for which to retrieve statistics - * @param context additional context that is passed through the HTTP pipeline during the service call - * @return a response containing the index statistics result. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Response getIndexStatisticsWithResponse(String indexName, Context context) { - return Utility.executeRestCallWithExceptionHandling( - () -> restClient.getIndexes().getStatisticsWithResponse(indexName, null, context), LOGGER); - } - - /** - * Lists all indexes available for an Azure AI Search service. - * - *

Code Sample

- * - *

List all search indexes.

- * - * - *
-     * PagedIterable<SearchIndex> indexes = SEARCH_INDEX_CLIENT.listIndexes();
-     * for (SearchIndex index: indexes) {
-     *     System.out.printf("The index name is %s. The ETag of index is %s.%n", index.getName(),
-     *         index.getETag());
-     * }
-     * 
- * - * - * @return the list of indexes. - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - public PagedIterable listIndexes() { - return listIndexes(Context.NONE); - } - - /** - * Lists all indexes available for an Azure AI Search service. - * - *

Code Sample

- * - *

List all search indexes.

- * - * - *
-     * PagedIterable<SearchIndex> indexes = SEARCH_INDEX_CLIENT.listIndexes(new Context(KEY_1, VALUE_1));
-     * System.out.println("The status code of the response is"
-     *     + indexes.iterableByPage().iterator().next().getStatusCode());
-     * for (SearchIndex index: indexes) {
-     *     System.out.printf("The index name is %s. The ETag of index is %s.%n", index.getName(), index.getETag());
-     * }
-     * 
- * - * - * @param context additional context that is passed through the HTTP pipeline during the service call - * @return the list of indexes. - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - public PagedIterable listIndexes(Context context) { - try { - return new PagedIterable<>(() -> this.listIndexesWithResponse(null, context)); - } catch (RuntimeException ex) { - throw LOGGER.logExceptionAsError(ex); - } - } - - private PagedResponse listIndexesWithResponse(String select, Context context) { - return Utility.executeRestCallWithExceptionHandling( - () -> restClient.getIndexes().listSinglePage(select, null, context), LOGGER); - } - - /** - * Lists all index names for an Azure AI Search service. - * - *

Code Sample

- * - *

List all search indexes names.

- * - * - *
-     * PagedIterable<String> indexes = SEARCH_INDEX_CLIENT.listIndexNames();
-     * for (String indexName: indexes) {
-     *     System.out.printf("The index name is %s.%n", indexName);
-     * }
-     * 
- * - * - * @return the list of index names. - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - public PagedIterable listIndexNames() { - return listIndexNames(Context.NONE); - } - - /** - * Lists all indexes names for an Azure AI Search service. - * - *

Code Sample

- * - *

List all search indexes names.

- * - * - *
-     * PagedIterable<String> indexes = SEARCH_INDEX_CLIENT.listIndexNames(new Context(KEY_1, VALUE_1));
-     * System.out.println("The status code of the response is"
-     *     + indexes.iterableByPage().iterator().next().getStatusCode());
-     * for (String indexName: indexes) {
-     *     System.out.printf("The index name is %s.%n", indexName);
-     * }
-     * 
- * - * - * @param context additional context that is passed through the HTTP pipeline during the service call - * @return the list of index names. - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - public PagedIterable listIndexNames(Context context) { - try { - return new PagedIterable<>( - () -> MappingUtils.mappingPagingSearchIndexNames(this.listIndexesWithResponse("name", context))); - } catch (RuntimeException ex) { - throw LOGGER.logExceptionAsError(ex); - } - } - - /** - * Creates a new Azure AI Search index or updates an index if it already exists. - * - *

Code Sample

- * - *

Create or update search index named "searchIndex".

- * - * - *
-     * SearchIndex indexFromService = SEARCH_INDEX_CLIENT.getIndex("searchIndex");
-     * indexFromService.setSuggesters(Collections.singletonList(new SearchSuggester("sg",
-     *     Collections.singletonList("hotelName"))));
-     * SearchIndex updatedIndex = SEARCH_INDEX_CLIENT.createOrUpdateIndex(indexFromService);
-     * System.out.printf("The index name is %s. The suggester name of index is %s.%n", updatedIndex.getName(),
-     *     updatedIndex.getSuggesters().get(0).getName());
-     * 
- * - * - * @param index the definition of the index to create or update - * @return the index that was created or updated. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public SearchIndex createOrUpdateIndex(SearchIndex index) { - return createOrUpdateIndexWithResponse(index, false, false, Context.NONE).getValue(); - } - - /** - * Creates a new Azure AI Search index or updates an index if it already exists. - * - *

Code Sample

- * - *

Create or update search index named "searchIndex".

- * - * - *
-     * SearchIndex indexFromService = SEARCH_INDEX_CLIENT.getIndex("searchIndex");
-     * indexFromService.setSuggesters(Collections.singletonList(new SearchSuggester("sg",
-     *     Collections.singletonList("hotelName"))));
-     * Response<SearchIndex> updatedIndexResponse = SEARCH_INDEX_CLIENT.createOrUpdateIndexWithResponse(indexFromService, true,
-     *     false, new Context(KEY_1, VALUE_1));
-     * System.out.printf("The status code of the normal response is %s.%n"
-     *         + "The index name is %s. The ETag of index is %s.%n", updatedIndexResponse.getStatusCode(),
-     *     updatedIndexResponse.getValue().getName(), updatedIndexResponse.getValue().getETag());
-     * 
- * - * - * @param index the {@link SearchIndex} to create or update - * @param allowIndexDowntime 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. - * @param onlyIfUnchanged {@code true} to update if the {@code index} is the same as the current service value. - * {@code false} to always update existing value. - * @param context additional context that is passed through the HTTP pipeline during the service call - * @return a response containing the Index that was created or updated. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Response createOrUpdateIndexWithResponse(SearchIndex index, boolean allowIndexDowntime, - boolean onlyIfUnchanged, Context context) { - return Utility.executeRestCallWithExceptionHandling(() -> { - Objects.requireNonNull(index, "'Index' cannot null."); - String ifMatch = onlyIfUnchanged ? index.getETag() : null; - return restClient.getIndexes() - .createOrUpdateWithResponse(index.getName(), index, allowIndexDowntime, ifMatch, null, null, context); - }, LOGGER); - } - - /** - * Deletes an Azure AI Search index and all the documents it contains. - * - *

Code Sample

- * - *

Delete search index with name "searchIndex".

- * - * - *
-     * SEARCH_INDEX_CLIENT.deleteIndex("searchIndex");
-     * 
- * - * - * @param indexName the name of the index to delete - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public void deleteIndex(String indexName) { - Utility.executeRestCallWithExceptionHandling( - () -> restClient.getIndexes().deleteWithResponse(indexName, null, null, null, Context.NONE), LOGGER); - } - - /** - * Deletes an Azure AI Search index and all the documents it contains. - * - *

Code Sample

- * - *

Delete search index with name "searchIndex".

- * - * - *
-     * SearchIndex indexFromService = SEARCH_INDEX_CLIENT.getIndex("searchIndex");
-     * Response<Void> deleteResponse = SEARCH_INDEX_CLIENT.deleteIndexWithResponse(indexFromService, true,
-     *     new Context(KEY_1, VALUE_1));
-     * System.out.printf("The status code of the response is %d.%n", deleteResponse.getStatusCode());
-     * 
- * - * - * @param index the Search {@link SearchIndex} to delete. - * @param onlyIfUnchanged {@code true} to delete if the {@code index} is the same as the current service value. - * {@code false} to always delete existing value. - * @param context additional context that is passed through the Http pipeline during the service call - * @return a response signalling completion. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Response deleteIndexWithResponse(SearchIndex index, boolean onlyIfUnchanged, Context context) { - return Utility.executeRestCallWithExceptionHandling(() -> { - String etag = onlyIfUnchanged ? index.getETag() : null; - return restClient.getIndexes().deleteWithResponse(index.getName(), etag, null, null, context); - }, LOGGER); - } - - /** - * Shows how an analyzer breaks text into tokens. - * - *

Code Sample

- * - *

Analyzer text with LexicalTokenizerName "Classic" in search index "searchIndex".

- * - * - *
-     * PagedIterable<AnalyzedTokenInfo> tokenInfos = SEARCH_INDEX_CLIENT.analyzeText("searchIndex",
-     *     new AnalyzeTextOptions("The quick brown fox", LexicalTokenizerName.CLASSIC));
-     * for (AnalyzedTokenInfo tokenInfo : tokenInfos) {
-     *     System.out.printf("The token emitted by the analyzer is %s.%n", tokenInfo.getToken());
-     * }
-     * 
- * - * - * @param indexName the name of the index for which to test an analyzer - * @param analyzeTextOptions the text and analyzer or analysis components to test. Requires to provide either {@link - * LexicalTokenizerName} or {@link LexicalAnalyzerName}. - * @return analyze result. - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - public PagedIterable analyzeText(String indexName, AnalyzeTextOptions analyzeTextOptions) { - return analyzeText(indexName, analyzeTextOptions, Context.NONE); - } - - /** - * Shows how an analyzer breaks text into tokens. - * - *

Code Sample

- * - *

Analyzer text response with LexicalTokenizerName "Classic" in search index "searchIndex".

- * - * - *
-     * PagedIterable<AnalyzedTokenInfo> tokenInfos = SEARCH_INDEX_CLIENT.analyzeText("searchIndex",
-     *     new AnalyzeTextOptions("The quick brown fox", LexicalTokenizerName.CLASSIC), new Context(KEY_1, VALUE_1));
-     * System.out.println("The status code of the response is "
-     *     + tokenInfos.iterableByPage().iterator().next().getStatusCode());
-     * for (AnalyzedTokenInfo tokenInfo : tokenInfos) {
-     *     System.out.printf("The token emitted by the analyzer is %s.%n", tokenInfo.getToken());
-     * }
-     * 
- * - * - * @param indexName the name of the index for which to test an analyzer - * @param analyzeTextOptions the text and analyzer or analysis components to test. Requires to provide either {@link - * LexicalTokenizerName} or {@link LexicalAnalyzerName}. - * @param context additional context that is passed through the HTTP pipeline during the service call - * @return analyze result. - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - public PagedIterable analyzeText(String indexName, AnalyzeTextOptions analyzeTextOptions, - Context context) { - try { - return new PagedIterable<>(() -> analyzeTextWithResponse(indexName, analyzeTextOptions, context)); - } catch (RuntimeException ex) { - throw LOGGER.logExceptionAsError(ex); - } - } - - private PagedResponse analyzeTextWithResponse(String indexName, - AnalyzeTextOptions analyzeTextOptions, Context context) { - return Utility.executeRestCallWithExceptionHandling( - () -> MappingUtils.mappingTokenInfo(restClient.getIndexes() - .analyzeWithResponse(indexName, AnalyzeRequestConverter.map(analyzeTextOptions), null, context)), - LOGGER); - } - - /** - * Creates a new Azure AI Search synonym map. - * - *

Code Sample

- * - *

Create synonym map named "synonymMap".

- * - * - *
-     * SynonymMap synonymMap = new SynonymMap("synonymMap",
-     *     "United States, United States of America, USA\nWashington, Wash. => WA");
-     * SynonymMap synonymMapFromService = SEARCH_INDEX_CLIENT.createSynonymMap(synonymMap);
-     * System.out.printf("The synonym map name is %s. The ETag of synonym map is %s.%n",
-     *     synonymMapFromService.getName(), synonymMapFromService.getETag());
-     * 
- * - * - * @param synonymMap the definition of the synonym map to create - * @return the created {@link SynonymMap}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public SynonymMap createSynonymMap(SynonymMap synonymMap) { - return createSynonymMapWithResponse(synonymMap, Context.NONE).getValue(); - } - - /** - * Creates a new Azure AI Search synonym map. - * - *

Code Sample

- * - *

Create synonym map named "synonymMap".

- * - * - *
-     * SynonymMap synonymMap = new SynonymMap("synonymMap",
-     *     "United States, United States of America, USA\nWashington, Wash. => WA");
-     * Response<SynonymMap> synonymMapFromService = SEARCH_INDEX_CLIENT.createSynonymMapWithResponse(synonymMap,
-     *     new Context(KEY_1, VALUE_1));
-     * System.out.printf("The status code of the response is %d.%n"
-     *         + "The synonym map name is %s. The ETag of synonym map is %s.%n", synonymMapFromService.getStatusCode(),
-     *     synonymMapFromService.getValue().getName(), synonymMapFromService.getValue().getETag());
-     * 
- * - * - * @param synonymMap the definition of the synonym map to create - * @param context additional context that is passed through the HTTP pipeline during the service call - * @return a response containing the created SynonymMap. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Response createSynonymMapWithResponse(SynonymMap synonymMap, Context context) { - return Utility.executeRestCallWithExceptionHandling(() -> { - Objects.requireNonNull(synonymMap, "'synonymMap' cannot be null."); - return restClient.getSynonymMaps().createWithResponse(synonymMap, null, context); - }, LOGGER); - } - - /** - * Retrieves a synonym map definition. - * - *

Code Sample

- * - *

Get synonym map with name "synonymMap".

- * - * - *
-     * SynonymMap synonymMapFromService =
-     *     SEARCH_INDEX_CLIENT.getSynonymMap("synonymMap");
-     * System.out.printf("The synonym map is %s. The ETag of synonym map is %s.%n", synonymMapFromService.getName(),
-     *     synonymMapFromService.getETag());
-     * 
- * - * - * @param synonymMapName name of the synonym map to retrieve - * @return the {@link SynonymMap} definition - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public SynonymMap getSynonymMap(String synonymMapName) { - return getSynonymMapWithResponse(synonymMapName, Context.NONE).getValue(); - } - - /** - * Retrieves a synonym map definition. - * - *

Code Sample

- * - *

Get synonym map with name "synonymMap".

- * - * - *
-     * Response<SynonymMap> synonymMapFromService =
-     *     SEARCH_INDEX_CLIENT.getSynonymMapWithResponse("synonymMap", new Context(KEY_1, VALUE_1));
-     * System.out.printf("The status code of the response is %d.%n"
-     *         + "The synonym map name is %s. The ETag of synonym map is %s.%n", synonymMapFromService.getStatusCode(),
-     *     synonymMapFromService.getValue().getName(), synonymMapFromService.getValue().getETag());
-     * 
- * - * - * @param synonymMapName name of the synonym map to retrieve - * @param context a context that is passed through the HTTP pipeline during the service call - * @return a response containing the SynonymMap. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Response getSynonymMapWithResponse(String synonymMapName, Context context) { - return Utility.executeRestCallWithExceptionHandling( - () -> restClient.getSynonymMaps().getWithResponse(synonymMapName, null, context), LOGGER); - } - - /** - * Lists all synonym maps available for an Azure AI Search service. - * - *

Code Sample

- * - *

List all synonym maps.

- * - * - *
-     * PagedIterable<SynonymMap> synonymMaps = SEARCH_INDEX_CLIENT.listSynonymMaps();
-     * for (SynonymMap synonymMap: synonymMaps) {
-     *     System.out.printf("The synonymMap name is %s. The ETag of synonymMap is %s.%n", synonymMap.getName(),
-     *         synonymMap.getETag());
-     * }
-     * 
- * - * - * @return the list of synonym maps. - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - public PagedIterable listSynonymMaps() { - return listSynonymMaps(Context.NONE); - } - - /** - * Lists all synonym maps available for an Azure AI Search service. - * - *

Code Sample

- * - *

List all synonym maps.

- * - * - *
-     * PagedIterable<SynonymMap> synonymMaps = SEARCH_INDEX_CLIENT.listSynonymMaps(new Context(KEY_1, VALUE_1));
-     * System.out.println("The status code of the response is"
-     *     + synonymMaps.iterableByPage().iterator().next().getStatusCode());
-     * for (SynonymMap index: synonymMaps) {
-     *     System.out.printf("The index name is %s. The ETag of index is %s.%n", index.getName(), index.getETag());
-     * }
-     * 
- * - * - * @param context additional context that is passed through the HTTP pipeline during the service call - * @return the list of synonym map names. - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - public PagedIterable listSynonymMaps(Context context) { - try { - return new PagedIterable<>( - () -> MappingUtils.mappingPagingSynonymMap(listSynonymMapsWithResponse(null, context))); - } catch (RuntimeException ex) { - throw LOGGER.logExceptionAsError(ex); - } - } - - private Response listSynonymMapsWithResponse(String select, Context context) { - return Utility.executeRestCallWithExceptionHandling( - () -> restClient.getSynonymMaps().listWithResponse(select, null, context), LOGGER); - } - - /** - * Lists all synonym maps names for an Azure AI Search service. - * - *

Code Sample

- * - *

List all synonym map names.

- * - * - *
-     * PagedIterable<String> synonymMaps = SEARCH_INDEX_CLIENT.listSynonymMapNames();
-     * for (String synonymMap: synonymMaps) {
-     *     System.out.printf("The synonymMap name is %s.%n", synonymMap);
-     * }
-     * 
- * - * - * @return the list of synonym maps. - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - public PagedIterable listSynonymMapNames() { - return listSynonymMapNames(Context.NONE); - } - - /** - * Lists all synonym maps names for an Azure AI Search service. - * - *

Code Sample

- * - *

List all synonym map names.

- * - * - *
-     * PagedIterable<String> synonymMaps = SEARCH_INDEX_CLIENT.listIndexNames(new Context(KEY_1, VALUE_1));
-     * System.out.println("The status code of the response is"
-     *     + synonymMaps.iterableByPage().iterator().next().getStatusCode());
-     * for (String synonymMapNames: synonymMaps) {
-     *     System.out.printf("The synonymMap name is %s.%n", synonymMapNames);
-     * }
-     * 
- * - * - * @param context additional context that is passed through the HTTP pipeline during the service call - * @return the list of synonym map names. - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - public PagedIterable listSynonymMapNames(Context context) { - try { - return new PagedIterable<>( - () -> MappingUtils.mappingPagingSynonymMapNames(listSynonymMapsWithResponse("name", context))); - } catch (RuntimeException ex) { - throw LOGGER.logExceptionAsError(ex); - } - } - - /** - * Creates a new Azure AI Search synonym map or updates a synonym map if it already exists. - * - *

Code Sample

- * - *

Create or update synonym map named "synonymMap".

- * - * - *
-     * SynonymMap synonymMap = SEARCH_INDEX_CLIENT.getSynonymMap("synonymMapName");
-     * synonymMap.setSynonyms("United States, United States of America, USA, America\nWashington, Wash. => WA");
-     * SynonymMap updatedSynonymMap = SEARCH_INDEX_CLIENT.createOrUpdateSynonymMap(synonymMap);
-     * System.out.printf("The synonym map name is %s. The synonyms are %s.%n", updatedSynonymMap.getName(),
-     *     updatedSynonymMap.getSynonyms());
-     * 
- * - * - * @param synonymMap the definition of the synonym map to create or update - * @return the synonym map that was created or updated. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public SynonymMap createOrUpdateSynonymMap(SynonymMap synonymMap) { - return createOrUpdateSynonymMapWithResponse(synonymMap, false, Context.NONE).getValue(); - } - - /** - * Creates a new Azure AI Search synonym map or updates a synonym map if it already exists. - * - *

Code Sample

- * - *

Create or update synonym map named "synonymMap".

- * - * - *
-     * SynonymMap synonymMap = SEARCH_INDEX_CLIENT.getSynonymMap("synonymMap");
-     * synonymMap.setSynonyms("United States, United States of America, USA, America\nWashington, Wash. => WA");
-     * Response<SynonymMap> updatedSynonymMap =
-     *     SEARCH_INDEX_CLIENT.createOrUpdateSynonymMapWithResponse(synonymMap, true,
-     *         new Context(KEY_1, VALUE_1));
-     * System.out.printf("The status code of the normal response is %s.%n"
-     *         + "The synonym map name is %s. The synonyms are %s.%n", updatedSynonymMap.getStatusCode(),
-     *     updatedSynonymMap.getValue().getName(), updatedSynonymMap.getValue().getSynonyms());
-     * 
- * - * - * @param synonymMap the definition of the synonym map to create or update - * @param onlyIfUnchanged {@code true} to update if the {@code synonymMap} is the same as the current service value. - * {@code false} to always update existing value. - * @param context additional context that is passed through the HTTP pipeline during the service call - * @return a response containing the synonym map that was created or updated. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Response createOrUpdateSynonymMapWithResponse(SynonymMap synonymMap, boolean onlyIfUnchanged, - Context context) { - return Utility.executeRestCallWithExceptionHandling(() -> { - Objects.requireNonNull(synonymMap, "'synonymMap' cannot be null."); - String ifMatch = onlyIfUnchanged ? synonymMap.getETag() : null; - return restClient.getSynonymMaps() - .createOrUpdateWithResponse(synonymMap.getName(), synonymMap, ifMatch, null, null, context); - }, LOGGER); - } - - /** - * Deletes an Azure AI Search synonym map. - * - *

Code Sample

- * - *

Delete synonym map with name "synonymMap".

- * - * - *
-     * SEARCH_INDEX_CLIENT.deleteSynonymMap("synonymMap");
-     * 
- * - * - * @param synonymMapName the name of the synonym map to delete - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public void deleteSynonymMap(String synonymMapName) { - Utility.executeRestCallWithExceptionHandling( - () -> restClient.getSynonymMaps().deleteWithResponse(synonymMapName, null, null, null, Context.NONE), - LOGGER); - } - - /** - * Deletes an Azure AI Search synonym map. - * - *

Code Sample

- * - *

Delete synonym map with name "synonymMap".

- * - * - *
-     * SynonymMap synonymMap = SEARCH_INDEX_CLIENT.getSynonymMap("synonymMap");
-     * Response<Void> response = SEARCH_INDEX_CLIENT.deleteSynonymMapWithResponse(synonymMap, true,
-     *     new Context(KEY_1, VALUE_1));
-     * System.out.println("The status code of the response is" + response.getStatusCode());
-     * 
- * - * - * @param synonymMap the {@link SynonymMap} to delete. - * @param onlyIfUnchanged {@code true} to delete if the {@code synonymMap} is the same as the current service value. - * {@code false} to always delete existing value. - * @param context additional context that is passed through the Http pipeline during the service call - * @return a response signalling completion. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Response deleteSynonymMapWithResponse(SynonymMap synonymMap, boolean onlyIfUnchanged, - Context context) { - String etag = onlyIfUnchanged ? synonymMap.getETag() : null; - return Utility.executeRestCallWithExceptionHandling( - () -> restClient.getSynonymMaps().deleteWithResponse(synonymMap.getName(), etag, null, null, context), - LOGGER); - } - - /** - * Returns service level statistics for a search service, including service counters and limits. - * - *

Code Sample

- * - *

Get service statistics.

- * - * - *
-     * SearchServiceStatistics serviceStatistics = SEARCH_INDEX_CLIENT.getServiceStatistics();
-     * System.out.printf("There are %s search indexes in your service.%n",
-     *     serviceStatistics.getCounters().getIndexCounter());
-     * 
- * - * - * @return the search service statistics result. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public SearchServiceStatistics getServiceStatistics() { - return getServiceStatisticsWithResponse(Context.NONE).getValue(); - } - - /** - * Returns service level statistics for a search service, including service counters and limits. - * - *

Code Sample

- * - *

Get service statistics.

- * - * - *
-     * Response<SearchServiceStatistics> serviceStatistics =
-     *     SEARCH_INDEX_CLIENT.getServiceStatisticsWithResponse(new Context(KEY_1, VALUE_1));
-     * System.out.printf("The status code of the response is %s.%nThere are %s search indexes in your service.%n",
-     *     serviceStatistics.getStatusCode(),
-     *     serviceStatistics.getValue().getCounters().getIndexCounter());
-     * 
- * - * - * @param context additional context that is passed through the HTTP pipeline during the service call - * @return the search service statistics result. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Response getServiceStatisticsWithResponse(Context context) { - return Utility.executeRestCallWithExceptionHandling( - () -> restClient.getServiceStatisticsWithResponse(null, context), LOGGER); - } - - /** - * Convenience method to convert a {@link Class Class's} {@link Field Fields} and {@link Method Methods} into {@link - * SearchField SearchFields} to help aid the creation of a {@link SearchField} which represents the {@link Class}. - * - * @param model The model {@link Class} that will have {@link SearchField SearchFields} generated from its - * structure. - * @param options Configuration used to determine generation of the {@link SearchField SearchFields}. - * @return A list {@link SearchField SearchFields} which represent the model {@link Class}. - */ - public static List buildSearchFields(Class model, FieldBuilderOptions options) { - return SearchIndexAsyncClient.buildSearchFields(model, options); - } -} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/SearchIndexClientBuilder.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/SearchIndexClientBuilder.java deleted file mode 100644 index 48a1ddeab62c..000000000000 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/SearchIndexClientBuilder.java +++ /dev/null @@ -1,531 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -package com.azure.search.documents.indexes; - -import com.azure.core.annotation.ServiceClientBuilder; -import com.azure.core.client.traits.AzureKeyCredentialTrait; -import com.azure.core.client.traits.ConfigurationTrait; -import com.azure.core.client.traits.EndpointTrait; -import com.azure.core.client.traits.HttpTrait; -import com.azure.core.client.traits.TokenCredentialTrait; -import com.azure.core.credential.AzureKeyCredential; -import com.azure.core.credential.TokenCredential; -import com.azure.core.http.HttpClient; -import com.azure.core.http.HttpPipeline; -import com.azure.core.http.HttpPipelinePosition; -import com.azure.core.http.policy.HttpLogDetailLevel; -import com.azure.core.http.policy.HttpLogOptions; -import com.azure.core.http.policy.HttpPipelinePolicy; -import com.azure.core.http.policy.RetryOptions; -import com.azure.core.http.policy.RetryPolicy; -import com.azure.core.util.ClientOptions; -import com.azure.core.util.Configuration; -import com.azure.core.util.HttpClientOptions; -import com.azure.core.util.logging.ClientLogger; -import com.azure.core.util.serializer.JsonSerializer; -import com.azure.search.documents.models.SearchAudience; -import com.azure.search.documents.SearchServiceVersion; -import com.azure.search.documents.implementation.util.Constants; -import com.azure.search.documents.implementation.util.Utility; - -import java.net.MalformedURLException; -import java.net.URL; -import java.util.ArrayList; -import java.util.List; -import java.util.Objects; - -/** - * This class provides a fluent builder API to help aid the configuration and instantiation of {@link SearchIndexClient - * SearchIndexClients} and {@link SearchIndexAsyncClient SearchIndexAsyncClients}. - * - *

- * Overview - *

- * - *

- * This client allows you to create instances of {@link SearchIndexClient} and {@link SearchIndexAsyncClient} to - * utilize synchronous and asynchronous APIs respectively to interact with Azure AI Search. - *

- * - *

- * Getting Started - *

- * - *

- * Authentication - *

- * - *

- * Azure AI Search supports - * Microsoft Entra ID (role-based) authentication and API keys for authentication. - *

- * - *

- * For more information about the scopes of authorization, see the Azure AI Search Security Overview documentation. - *

- * - *

- * Building and Authenticating a {@link SearchIndexClient} or {@link SearchIndexAsyncClient} using API keys - *

- * - *

- * To build an instance of {@link SearchIndexClient} or {@link SearchIndexAsyncClient} using API keys, call - * {@link #buildClient() buildClient} and {@link #buildAsyncClient() buildAsyncClient} respectively from the - * {@link SearchIndexClientBuilder}. - *

- * - *

- * The following must be provided to construct a client instance. - *

- * - *
    - *
  • - * The Azure AI Search service URL. - *
  • - *
  • - * An {@link AzureKeyCredential API Key} that grants access to the Azure AI Search service. - *
  • - *
- * - *

Instantiating a synchronous Search Index Client

- * - * - *
- * SearchIndexClient searchIndexClient = new SearchIndexClientBuilder()
- *     .credential(new AzureKeyCredential("{key}"))
- *     .endpoint("{endpoint}")
- *     .buildClient();
- * 
- * - * - *

Instantiating an asynchronous Search Index Client

- * - * - *
- * SearchIndexAsyncClient searchIndexAsyncClient = new SearchIndexClientBuilder()
- *     .credential(new AzureKeyCredential("{key}"))
- *     .endpoint("{endpoint}")
- *     .buildAsyncClient();
- * 
- * - * - * - *

- * Building and Authenticating a {@link SearchIndexClient} or {@link SearchIndexAsyncClient} using Microsoft Entra - *

- * - *

- * You can also create a {@link SearchIndexClient} or {@link SearchIndexAsyncClient} using Microsoft Entra ID - * authentication. Your user or service principal must be assigned the "Search Index Data Reader" role. Using Azure Identity - * you can authenticate a service using Managed Identity or a service principal, authenticate - * as a developer working on an application, and more all without changing code. Please refer the documentation for - * instructions on how to connect to Azure AI Search using Azure role-based access control (Azure RBAC). - *

- * - *

- * Before you can use any credential type from Azure.Identity, you'll first need to install the Azure.Identity package.
- * There are a variety of credentials types available in Azure.Identity. To better understand your authentication options, view the - * Azure Identity README. and - * Azure Identity Samples. - *

- * - *

- * Make sure you use the right namespace for DefaultAzureCredential at the top of your source file: - *

- * - * - *
- * import com.azure.identity.DefaultAzureCredential;
- * import com.azure.identity.DefaultAzureCredentialBuilder;
- * 
- * - * - *

- * Then you can create an instance of DefaultAzureCredential and pass it to a new instance of your client: - *

- * - *

Instantiating a synchronous Search Index Client

- * - * - *
- * DefaultAzureCredential credential = new DefaultAzureCredentialBuilder().build();
- *
- * SearchIndexClient searchIndexClient = new SearchIndexClientBuilder()
- *     .credential(credential)
- *     .endpoint("{endpoint}")
- *     .buildClient();
- * 
- * - * - *

Instantiating an asynchronous Search Index Client

- * - * - *
- * DefaultAzureCredential credential = new DefaultAzureCredentialBuilder().build();
- *
- * SearchIndexAsyncClient searchIndexAsyncClient = new SearchIndexClientBuilder()
- *     .credential(credential)
- *     .endpoint("{endpoint}")
- *     .buildAsyncClient();
- * 
- * - * - * @see SearchIndexClient - * @see SearchIndexAsyncClient - * @see com.azure.search.documents.indexes - */ -@ServiceClientBuilder(serviceClients = { SearchIndexClient.class, SearchIndexAsyncClient.class }) -public final class SearchIndexClientBuilder implements AzureKeyCredentialTrait, - ConfigurationTrait, EndpointTrait, - HttpTrait, TokenCredentialTrait { - private static final ClientLogger LOGGER = new ClientLogger(SearchIndexClientBuilder.class); - - private final List perCallPolicies = new ArrayList<>(); - private final List perRetryPolicies = new ArrayList<>(); - - private AzureKeyCredential azureKeyCredential; - private TokenCredential tokenCredential; - private SearchAudience audience; - - private SearchServiceVersion serviceVersion; - private String endpoint; - private HttpClient httpClient; - private HttpPipeline httpPipeline; - private HttpLogOptions httpLogOptions; - private ClientOptions clientOptions; - private Configuration configuration; - private RetryPolicy retryPolicy; - private RetryOptions retryOptions; - private JsonSerializer jsonSerializer; - - /** - * Creates a builder instance that is able to configure and construct {@link SearchIndexClient SearchIndexClients} - * and {@link SearchIndexAsyncClient SearchIndexAsyncClients}. - */ - public SearchIndexClientBuilder() { - } - - /** - * Creates a {@link SearchIndexClient} based on options set in the Builder. Every time {@code buildClient()} is - * called a new instance of {@link SearchIndexClient} is created. - *

- * If {@link #pipeline(HttpPipeline) pipeline} is set, then only the {@code pipeline} and {@link #endpoint(String) - * endpoint} are used to create the {@link SearchIndexClient client}. All other builder settings are ignored. - * - * @return A SearchIndexClient with the options set from the builder. - * @throws NullPointerException If {@code endpoint} are {@code null}. - * @throws IllegalStateException If both {@link #retryOptions(RetryOptions)} - * and {@link #retryPolicy(RetryPolicy)} have been set. - */ - public SearchIndexClient buildClient() { - Objects.requireNonNull(endpoint, "'endpoint' cannot be null."); - - SearchServiceVersion buildVersion - = (serviceVersion == null) ? SearchServiceVersion.getLatest() : serviceVersion; - - if (httpPipeline != null) { - return new SearchIndexClient(endpoint, buildVersion, httpPipeline, jsonSerializer); - } - - HttpPipeline pipeline - = Utility.buildHttpPipeline(clientOptions, httpLogOptions, configuration, retryPolicy, retryOptions, - azureKeyCredential, tokenCredential, audience, perCallPolicies, perRetryPolicies, httpClient, LOGGER); - - return new SearchIndexClient(endpoint, buildVersion, pipeline, jsonSerializer); - } - - /** - * Creates a {@link SearchIndexAsyncClient} based on options set in the Builder. Every time {@code - * buildAsyncClient()} is called a new instance of {@link SearchIndexAsyncClient} is created. - *

- * If {@link #pipeline(HttpPipeline) pipeline} is set, then only the {@code pipeline} and {@link #endpoint(String) - * endpoint} are used to create the {@link SearchIndexAsyncClient client}. All other builder settings are ignored. - * - * @return A SearchIndexAsyncClient with the options set from the builder. - * @throws NullPointerException If {@code endpoint} are {@code null}. - * @throws IllegalStateException If both {@link #retryOptions(RetryOptions)} - * and {@link #retryPolicy(RetryPolicy)} have been set. - */ - public SearchIndexAsyncClient buildAsyncClient() { - Objects.requireNonNull(endpoint, "'endpoint' cannot be null."); - - SearchServiceVersion buildVersion - = (serviceVersion == null) ? SearchServiceVersion.getLatest() : serviceVersion; - - if (httpPipeline != null) { - return new SearchIndexAsyncClient(endpoint, buildVersion, httpPipeline, jsonSerializer); - } - - HttpPipeline pipeline - = Utility.buildHttpPipeline(clientOptions, httpLogOptions, configuration, retryPolicy, retryOptions, - azureKeyCredential, tokenCredential, audience, perCallPolicies, perRetryPolicies, httpClient, LOGGER); - - return new SearchIndexAsyncClient(endpoint, buildVersion, pipeline, jsonSerializer); - } - - /** - * Sets the service endpoint for the Azure AI Search instance. - * - * @param endpoint The URL of the Azure AI Search instance. - * @return The updated SearchIndexClientBuilder object. - * @throws IllegalArgumentException If {@code endpoint} is null or it cannot be parsed into a valid URL. - */ - @Override - public SearchIndexClientBuilder endpoint(String endpoint) { - try { - new URL(endpoint); - } catch (MalformedURLException ex) { - throw LOGGER.logExceptionAsWarning(new IllegalArgumentException("'endpoint' must be a valid URL", ex)); - } - this.endpoint = endpoint; - return this; - } - - /** - * Sets the {@link AzureKeyCredential} used to authenticate HTTP requests. - * - * @param credential The {@link AzureKeyCredential} used to authenticate HTTP requests. - * @return The updated SearchIndexClientBuilder object. - */ - @Override - public SearchIndexClientBuilder credential(AzureKeyCredential credential) { - this.azureKeyCredential = credential; - return this; - } - - /** - * Sets the {@link TokenCredential} used to authorize requests sent to the service. Refer to the Azure SDK for Java - * identity and authentication - * documentation for more details on proper usage of the {@link TokenCredential} type. - * - * @param credential {@link TokenCredential} used to authorize requests sent to the service. - * @return The updated SearchIndexClientBuilder object. - */ - @Override - public SearchIndexClientBuilder credential(TokenCredential credential) { - this.tokenCredential = credential; - return this; - } - - /** - * Sets the Audience to use for authentication with Microsoft Entra ID. - *

- * The audience is not considered when using a {@link #credential(AzureKeyCredential) shared key}. - *

- * If {@code audience} is null the public cloud audience will be assumed. - * - * @param audience The Audience to use for authentication with Microsoft Entra ID. - * @return The updated SearchClientBuilder object. - */ - public SearchIndexClientBuilder audience(SearchAudience audience) { - this.audience = audience; - return this; - } - - /** - * Sets the {@link HttpLogOptions logging configuration} to use when sending and receiving requests to and from - * the service. If a {@code logLevel} is not provided, default value of {@link HttpLogDetailLevel#NONE} is set. - * - *

Note: It is important to understand the precedence order of the HttpTrait APIs. In - * particular, if a {@link HttpPipeline} is specified, this takes precedence over all other APIs in the trait, and - * they will be ignored. If no {@link HttpPipeline} is specified, a HTTP pipeline will be constructed internally - * based on the settings provided to this trait. Additionally, there may be other APIs in types that implement this - * trait that are also ignored if an {@link HttpPipeline} is specified, so please be sure to refer to the - * documentation of types that implement this trait to understand the full set of implications.

- * - * @param logOptions The {@link HttpLogOptions logging configuration} to use when sending and receiving requests to - * and from the service. - * @return The updated SearchIndexClientBuilder object. - */ - @Override - public SearchIndexClientBuilder httpLogOptions(HttpLogOptions logOptions) { - httpLogOptions = logOptions; - return this; - } - - /** - * Gets the default Azure Search headers and query parameters allow list. - * - * @return The default {@link HttpLogOptions} allow list. - */ - public static HttpLogOptions getDefaultLogOptions() { - return Constants.DEFAULT_LOG_OPTIONS_SUPPLIER.get(); - } - - /** - * Allows for setting common properties such as application ID, headers, proxy configuration, etc. Note that it is - * recommended that this method be called with an instance of the {@link HttpClientOptions} - * class (a subclass of the {@link ClientOptions} base class). The HttpClientOptions subclass provides more - * configuration options suitable for HTTP clients, which is applicable for any class that implements this HttpTrait - * interface. - * - *

Note: It is important to understand the precedence order of the HttpTrait APIs. In - * particular, if a {@link HttpPipeline} is specified, this takes precedence over all other APIs in the trait, and - * they will be ignored. If no {@link HttpPipeline} is specified, a HTTP pipeline will be constructed internally - * based on the settings provided to this trait. Additionally, there may be other APIs in types that implement this - * trait that are also ignored if an {@link HttpPipeline} is specified, so please be sure to refer to the - * documentation of types that implement this trait to understand the full set of implications.

- * - * @param clientOptions A configured instance of {@link HttpClientOptions}. - * @return The updated SearchIndexClientBuilder object. - * @see HttpClientOptions - */ - @Override - public SearchIndexClientBuilder clientOptions(ClientOptions clientOptions) { - this.clientOptions = clientOptions; - return this; - } - - /** - * Adds a {@link HttpPipelinePolicy pipeline policy} to apply on each request sent. - * - *

Note: It is important to understand the precedence order of the HttpTrait APIs. In - * particular, if a {@link HttpPipeline} is specified, this takes precedence over all other APIs in the trait, and - * they will be ignored. If no {@link HttpPipeline} is specified, a HTTP pipeline will be constructed internally - * based on the settings provided to this trait. Additionally, there may be other APIs in types that implement this - * trait that are also ignored if an {@link HttpPipeline} is specified, so please be sure to refer to the - * documentation of types that implement this trait to understand the full set of implications.

- * - * @param policy A {@link HttpPipelinePolicy pipeline policy}. - * @return The updated SearchIndexClientBuilder object. - * @throws NullPointerException If {@code policy} is {@code null}. - */ - @Override - public SearchIndexClientBuilder addPolicy(HttpPipelinePolicy policy) { - Objects.requireNonNull(policy, "'policy' cannot be null."); - - if (policy.getPipelinePosition() == HttpPipelinePosition.PER_CALL) { - perCallPolicies.add(policy); - } else { - perRetryPolicies.add(policy); - } - - return this; - } - - /** - * Custom JSON serializer that is used to handle model types that are not contained in the Azure Search Documents - * library. - * - * @param jsonSerializer The serializer to serialize user defined models. - * @return The updated SearchIndexClientBuilder object. - */ - public SearchIndexClientBuilder serializer(JsonSerializer jsonSerializer) { - this.jsonSerializer = jsonSerializer; - return this; - } - - /** - * Sets the {@link HttpClient} to use for sending and receiving requests to and from the service. - * - *

Note: It is important to understand the precedence order of the HttpTrait APIs. In - * particular, if a {@link HttpPipeline} is specified, this takes precedence over all other APIs in the trait, and - * they will be ignored. If no {@link HttpPipeline} is specified, a HTTP pipeline will be constructed internally - * based on the settings provided to this trait. Additionally, there may be other APIs in types that implement this - * trait that are also ignored if an {@link HttpPipeline} is specified, so please be sure to refer to the - * documentation of types that implement this trait to understand the full set of implications.

- * - * @param client The {@link HttpClient} to use for requests. - * @return The updated SearchIndexClientBuilder object. - */ - @Override - public SearchIndexClientBuilder httpClient(HttpClient client) { - if (this.httpClient != null && client == null) { - LOGGER.info("HttpClient is being set to 'null' when it was previously configured."); - } - - this.httpClient = client; - return this; - } - - /** - * Sets the {@link HttpPipeline} to use for the service client. - * - *

Note: It is important to understand the precedence order of the HttpTrait APIs. In - * particular, if a {@link HttpPipeline} is specified, this takes precedence over all other APIs in the trait, and - * they will be ignored. If no {@link HttpPipeline} is specified, a HTTP pipeline will be constructed internally - * based on the settings provided to this trait. Additionally, there may be other APIs in types that implement this - * trait that are also ignored if an {@link HttpPipeline} is specified, so please be sure to refer to the - * documentation of types that implement this trait to understand the full set of implications.

- *

- * If {@code pipeline} is set, all other settings are ignored, aside from {@link #endpoint(String) endpoint} when - * building a {@link SearchIndexClient} or {@link SearchIndexAsyncClient}. - * - * @param httpPipeline {@link HttpPipeline} to use for sending service requests and receiving responses. - * @return The updated SearchIndexClientBuilder object. - */ - @Override - public SearchIndexClientBuilder pipeline(HttpPipeline httpPipeline) { - if (this.httpPipeline != null && httpPipeline == null) { - LOGGER.info("HttpPipeline is being set to 'null' when it was previously configured."); - } - - this.httpPipeline = httpPipeline; - return this; - } - - /** - * Sets the configuration store that is used during construction of the service client. - *

- * The default configuration store is a clone of the {@link Configuration#getGlobalConfiguration() global - * configuration store}, use {@link Configuration#NONE} to bypass using configuration settings during construction. - * - * @param configuration The configuration store that will be used. - * @return The updated SearchIndexClientBuilder object. - */ - @Override - public SearchIndexClientBuilder configuration(Configuration configuration) { - this.configuration = configuration; - return this; - } - - /** - * Sets the {@link HttpPipelinePolicy} that will attempt to retry requests when needed. - *

- * A default retry policy will be supplied if one isn't provided. - *

- * Setting this is mutually exclusive with using {@link #retryOptions(RetryOptions)}. - * - * @param retryPolicy The {@link RetryPolicy} that will attempt to retry requests when needed. - * @return The updated SearchIndexClientBuilder object. - */ - public SearchIndexClientBuilder retryPolicy(RetryPolicy retryPolicy) { - this.retryPolicy = retryPolicy; - return this; - } - - /** - * Sets the {@link RetryOptions} for all the requests made through the client. - * - *

Note: It is important to understand the precedence order of the HttpTrait APIs. In - * particular, if a {@link HttpPipeline} is specified, this takes precedence over all other APIs in the trait, and - * they will be ignored. If no {@link HttpPipeline} is specified, a HTTP pipeline will be constructed internally - * based on the settings provided to this trait. Additionally, there may be other APIs in types that implement this - * trait that are also ignored if an {@link HttpPipeline} is specified, so please be sure to refer to the - * documentation of types that implement this trait to understand the full set of implications.

- *

- * Setting this is mutually exclusive with using {@link #retryPolicy(RetryPolicy)}. - * - * @param retryOptions The {@link RetryOptions} to use for all the requests made through the client. - * @return The updated SearchIndexClientBuilder object. - */ - @Override - public SearchIndexClientBuilder retryOptions(RetryOptions retryOptions) { - this.retryOptions = retryOptions; - return this; - } - - /** - * Sets the {@link SearchServiceVersion} that is used when making API requests. - *

- * If a service version is not provided, {@link SearchServiceVersion#getLatest()} will be used as a default. When - * this default is used updating to a newer client library may result in a newer version of the service being used. - * - * @param serviceVersion The version of the service to be used when making requests. - * @return The updated SearchIndexClientBuilder object. - */ - public SearchIndexClientBuilder serviceVersion(SearchServiceVersion serviceVersion) { - this.serviceVersion = serviceVersion; - return this; - } -} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/SearchIndexerAsyncClient.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/SearchIndexerAsyncClient.java deleted file mode 100644 index 20a9bf9d6e6d..000000000000 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/SearchIndexerAsyncClient.java +++ /dev/null @@ -1,1671 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.search.documents.indexes; - -import com.azure.core.annotation.ReturnType; -import com.azure.core.annotation.ServiceClient; -import com.azure.core.annotation.ServiceMethod; -import com.azure.core.http.HttpPipeline; -import com.azure.core.http.rest.PagedFlux; -import com.azure.core.http.rest.Response; -import com.azure.core.util.Context; -import com.azure.core.util.FluxUtil; -import com.azure.core.util.logging.ClientLogger; -import com.azure.search.documents.SearchServiceVersion; -import com.azure.search.documents.implementation.util.MappingUtils; -import com.azure.search.documents.indexes.implementation.SearchServiceClientImpl; -import com.azure.search.documents.indexes.implementation.models.ListDataSourcesResult; -import com.azure.search.documents.indexes.implementation.models.ListIndexersResult; -import com.azure.search.documents.indexes.implementation.models.ListSkillsetsResult; -import com.azure.search.documents.indexes.models.SearchIndexer; -import com.azure.search.documents.indexes.models.SearchIndexerDataSourceConnection; -import com.azure.search.documents.indexes.models.SearchIndexerSkillset; -import com.azure.search.documents.indexes.models.SearchIndexerStatus; -import reactor.core.publisher.Mono; - -import java.util.function.Function; - -import static com.azure.core.util.FluxUtil.monoError; -import static com.azure.core.util.FluxUtil.pagedFluxError; -import static com.azure.core.util.FluxUtil.withContext; - -/** - * This class provides a client that contains the operations for creating, getting, listing, updating, or deleting data - * source connections, indexers, or skillsets and running or resetting indexers in an Azure AI Search service. - * - *

- * Overview - *

- * - *

- * Indexers provide indexing automation. An indexer connects to a data source, reads in the data, and passes it to a - * skillset pipeline for indexing into a target search index. Indexers read from an external source using connection - * information in a data source, and serialize the incoming data into JSON search documents. In addition to a data - * source, an indexer also requires an index. The index specifies the fields and attributes of the search documents. - *

- * - *

- * A skillset adds external processing steps to indexer execution, and is usually used to add AI or deep learning - * models to analyze or transform content to make it searchable in an index. The contents of a skillset are one or - * more skills, which can be built-in skills - * created by Microsoft, custom skills, or a combination of both. Built-in skills exist for image analysis, - * including OCR, and natural language processing. Other examples of built-in skills include entity recognition, - * key phrase extraction, chunking text into logical pages, among others. A skillset is high-level standalone object - * that exists on a level equivalent to indexes, indexers, and data sources, but it's operational only within indexer - * processing. As a high-level object, you can design a skillset once, and then reference it in multiple indexers. - *

- * - *

- * This client provides an asynchronous API for accessing indexers and skillsets. This client allows you to create, - * update, list, or delete indexers and skillsets. It can also be used to run or reset indexers. - *

- * - *

- * Getting Started - *

- * - *

- * Authenticating and building instances of this client are handled by {@link SearchIndexerClientBuilder}. This - * sample shows you how to authenticate and build this client: - *

- * - * - *
- * SearchIndexerAsyncClient searchIndexerAsyncClient = new SearchIndexerClientBuilder()
- *     .endpoint("{endpoint}")
- *     .credential(new AzureKeyCredential("{admin-key}"))
- *     .buildAsyncClient();
- * 
- * - * - *

- * For more information on authentication and building, see the {@link SearchIndexerClientBuilder} documentation. - *

- * - *

- * Examples - *

- * - *

- * The following examples all use a simple Hotel - * data set that you can - * import into your own index from the Azure portal. - * These are just a few of the basics - please check out our Samples for much more. - *

- * - *

- * Create an Indexer - *

- * - *

- * The following sample creates an indexer. - *

- * - * - *
- * SearchIndexer indexer = new SearchIndexer("example-indexer", "example-datasource", "example-index");
- * SearchIndexer createdIndexer = searchIndexerAsyncClient.createIndexer(indexer).block();
- * if (createdIndexer != null) {
- *     System.out.printf("Created indexer name: %s%n", createdIndexer.getName());
- * }
- * 
- * - * - * - * For a synchronous sample, see {@link SearchIndexerClient#createIndexer(SearchIndexer)}. - * - * - *

- * List all Indexers - *

- * - *

- * The following sample lists all indexers. - *

- * - * - *
- * searchIndexerAsyncClient.listIndexers().subscribe(indexer ->
- *     System.out.printf("Retrieved indexer name: %s%n", indexer.getName())
- * );
- * 
- * - * - * For a synchronous sample, see {@link SearchIndexerClient#listIndexers()}. - * - * - *

- * Get an Indexer - *

- * - *

- * The following sample gets an indexer. - *

- * - * - *
- * SearchIndexer indexer = searchIndexerAsyncClient.getIndexer("example-indexer").block();
- * if (indexer != null) {
- *     System.out.printf("Retrieved indexer name: %s%n", indexer.getName());
- * }
- * 
- * - * - * For a synchronous sample, see {@link SearchIndexerClient#getIndexer(String)}. - * - * - *

- * Update an Indexer - *

- * - *

- * The following sample updates an indexer. - *

- * - * - *
- * SearchIndexer indexer = searchIndexerAsyncClient.getIndexer("example-indexer").block();
- * if (indexer != null) {
- *     System.out.printf("Retrieved indexer name: %s%n", indexer.getName());
- *     indexer.setDescription("This is a new description for this indexer");
- *     SearchIndexer updatedIndexer = searchIndexerAsyncClient.createOrUpdateIndexer(indexer).block();
- *
- *     if (updatedIndexer != null) {
- *         System.out.printf("Updated indexer name: %s, description: %s%n", updatedIndexer.getName(),
- *             updatedIndexer.getDescription());
- *     }
- * }
- *
- * 
- * - * - * - * For a synchronous sample, see {@link SearchIndexerClient#createOrUpdateIndexer(SearchIndexer)}. - * - * - *

- * Delete an Indexer - *

- * - *

- * The following sample deletes an indexer. - *

- * - * - *
- * searchIndexerAsyncClient.deleteIndexer("example-indexer");
- * 
- * - * - * - * For a synchronous sample, see {@link SearchIndexerClient#deleteIndexer(String)}. - * - * - *

- * Run an Indexer - *

- * - *

- * The following sample runs an indexer. - *

- * - * - *
- * searchIndexerAsyncClient.runIndexer("example-indexer");
- * 
- * - * - * - * For a synchronous sample, see {@link SearchIndexerClient#runIndexer(String)}. - * - * - *

- * Reset an Indexer - *

- * - *

- * The following sample resets an indexer. - *

- * - * - *
- * searchIndexerAsyncClient.resetIndexer("example-indexer");
- * 
- * - * - * - * For a synchronous sample, see {@link SearchIndexerClient#resetIndexer(String)}. - * - * - *

- * Create a Skillset - *

- * - *

- * The following sample creates a skillset. - *

- * - * - *
- * List<InputFieldMappingEntry> inputs = Collections.singletonList(
- *     new InputFieldMappingEntry("image")
- *         .setSource("/document/normalized_images/*")
- * );
- *
- * List<OutputFieldMappingEntry> outputs = Arrays.asList(
- *     new OutputFieldMappingEntry("text")
- *         .setTargetName("mytext"),
- *     new OutputFieldMappingEntry("layoutText")
- *         .setTargetName("myLayoutText")
- * );
- *
- * List<SearchIndexerSkill> skills = Collections.singletonList(
- *     new OcrSkill(inputs, outputs)
- *         .setShouldDetectOrientation(true)
- *         .setDefaultLanguageCode(null)
- *         .setName("myocr")
- *         .setDescription("Extracts text (plain and structured) from image.")
- *         .setContext("/document/normalized_images/*")
- * );
- *
- * SearchIndexerSkillset skillset = new SearchIndexerSkillset("skillsetName", skills)
- *     .setDescription("Extracts text (plain and structured) from image.");
- *
- * System.out.println(String.format("Creating OCR skillset '%s'", skillset.getName()));
- *
- * SearchIndexerSkillset createdSkillset = searchIndexerAsyncClient.createSkillset(skillset).block();
- *
- * if (createdSkillset != null) {
- *     System.out.println("Created OCR skillset");
- *     System.out.println(String.format("Name: %s", createdSkillset.getName()));
- *     System.out.println(String.format("ETag: %s", createdSkillset.getETag()));
- * }
- * 
- * - * - * - * For a synchronous sample, see {@link SearchIndexerClient#createSkillset(SearchIndexerSkillset)}. - * - * - *

- * List all Skillsets - *

- * - *

- * The following sample lists all skillsets. - *

- * - * - *
- * searchIndexerAsyncClient.listSkillsets().subscribe(skillset ->
- *     System.out.printf("Retrieved skillset name: %s%n", skillset.getName())
- * );
- * 
- * - * - * - * For a synchronous sample, see {@link SearchIndexerClient#listSkillsets()}. - * - * - *

- * Get a Skillset - *

- * - *

- * The following sample gets a skillset. - *

- * - * - *
- * SearchIndexerSkillset skillset = searchIndexerAsyncClient.getSkillset("example-skillset").block();
- * if (skillset != null) {
- *     System.out.printf("Retrieved skillset name: %s%n", skillset.getName());
- * }
- * 
- * - * - * - * For a synchronous sample, see {@link SearchIndexerClient#getSkillset(String)}. - * - * - *

- * Update a Skillset - *

- * - *

- * The following sample updates a skillset. - *

- * - * - *
- * SearchIndexerSkillset skillset = searchIndexerAsyncClient.getSkillset("example-skillset").block();
- * if (skillset != null) {
- *     System.out.printf("Retrieved skillset name: %s%n", skillset.getName());
- *     SearchIndexerSkillset updatedSkillset = searchIndexerAsyncClient.createOrUpdateSkillset(skillset).block();
- *
- *     if (updatedSkillset != null) {
- *         System.out.printf("Updated skillset name: %s, description: %s%n", updatedSkillset.getName(),
- *             updatedSkillset.getDescription());
- *     }
- * }
- * 
- * - * - * - * For a synchronous sample, see {@link SearchIndexerClient#createOrUpdateSkillset(SearchIndexerSkillset)}. - * - * - *

- * Delete a Skillset - *

- * - *

- * The following sample deletes a skillset. - *

- * - * - *
- * searchIndexerAsyncClient.deleteSkillset("example-skillset");
- * 
- * - * - * - * For a synchronous sample, see {@link SearchIndexerClient#deleteSkillset(String)}. - * - * - * @see SearchIndexerClient - * @see SearchIndexerClientBuilder - * @see com.azure.search.documents.indexes - */ -@ServiceClient(builder = SearchIndexerClientBuilder.class, isAsync = true) -public class SearchIndexerAsyncClient { - private static final ClientLogger LOGGER = new ClientLogger(SearchIndexerAsyncClient.class); - - /** - * Search REST API Version - */ - private final SearchServiceVersion serviceVersion; - - /** - * The endpoint for the Azure AI Search service. - */ - private final String endpoint; - - /** - * The underlying AutoRest client used to interact with the Search service - */ - private final SearchServiceClientImpl restClient; - - /** - * The pipeline that powers this client. - */ - private final HttpPipeline httpPipeline; - - SearchIndexerAsyncClient(String endpoint, SearchServiceVersion serviceVersion, HttpPipeline httpPipeline) { - this.endpoint = endpoint; - this.serviceVersion = serviceVersion; - this.httpPipeline = httpPipeline; - - this.restClient = new SearchServiceClientImpl(httpPipeline, endpoint, serviceVersion.getVersion()); - } - - /** - * Gets the {@link HttpPipeline} powering this client. - * - * @return the pipeline. - */ - HttpPipeline getHttpPipeline() { - return this.httpPipeline; - } - - /** - * Gets the endpoint for the Azure AI Search service. - * - * @return the endpoint value. - */ - public String getEndpoint() { - return this.endpoint; - } - - /** - * Creates a new Azure AI Search data source or updates a data source if it already exists. - * - *

Code Sample

- * - *

Create or update search indexer data source connection named "dataSource".

- * - * - *
-     * SearchIndexerDataSourceConnection dataSource = SEARCH_INDEXER_CLIENT.getDataSourceConnection("dataSource");
-     * dataSource.setContainer(new SearchIndexerDataContainer("updatecontainer"));
-     *
-     * SearchIndexerDataSourceConnection updateDataSource = SEARCH_INDEXER_CLIENT
-     *     .createOrUpdateDataSourceConnection(dataSource);
-     * System.out.printf("The dataSource name is %s. The container name of dataSource is %s.%n",
-     *     updateDataSource.getName(), updateDataSource.getContainer().getName());
-     * 
- * - * - * @param dataSource The definition of the {@link SearchIndexerDataSourceConnection} to create or update. - * @return the data source that was created or updated. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono - createOrUpdateDataSourceConnection(SearchIndexerDataSourceConnection dataSource) { - return createOrUpdateDataSourceConnectionWithResponse(dataSource, false).map(Response::getValue); - } - - /** - * Creates a new Azure AI Search data source or updates a data source if it already exists. - * - *

Code Sample

- * - *

Create or update search indexer data source connection named "dataSource".

- * - * - *
-     * SEARCH_INDEXER_ASYNC_CLIENT.getDataSourceConnection("dataSource")
-     *     .flatMap(dataSource -> {
-     *         dataSource.setContainer(new SearchIndexerDataContainer("updatecontainer"));
-     *         return SEARCH_INDEXER_ASYNC_CLIENT.createOrUpdateDataSourceConnectionWithResponse(dataSource, true);
-     *     })
-     *     .subscribe(updateDataSource ->
-     *         System.out.printf("The status code of the response is %s.%nThe dataSource name is %s. "
-     *             + "The container name of dataSource is %s.%n", updateDataSource.getStatusCode(),
-     *         updateDataSource.getValue().getName(), updateDataSource.getValue().getContainer().getName()));
-     * 
- * - * - * @param dataSource The definition of the {@link SearchIndexerDataSourceConnection} to create or update. - * @param onlyIfUnchanged {@code true} to update if the {@code dataSource} is the same as the current service value. - * {@code false} to always update existing value. - * @return a data source response. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> createOrUpdateDataSourceConnectionWithResponse( - SearchIndexerDataSourceConnection dataSource, boolean onlyIfUnchanged) { - return withContext( - context -> createOrUpdateDataSourceConnectionWithResponse(dataSource, onlyIfUnchanged, null, context)); - } - - Mono> createOrUpdateDataSourceConnectionWithResponse( - SearchIndexerDataSourceConnection dataSource, boolean onlyIfUnchanged, Boolean ignoreResetRequirements, - Context context) { - if (dataSource == null) { - return monoError(LOGGER, new NullPointerException("'dataSource' cannot be null.")); - } - String ifMatch = onlyIfUnchanged ? dataSource.getETag() : null; - if (dataSource.getConnectionString() == null) { - dataSource.setConnectionString(""); - } - try { - return restClient.getDataSources() - .createOrUpdateWithResponseAsync(dataSource.getName(), dataSource, ifMatch, null, - ignoreResetRequirements, null, context) - .onErrorMap(MappingUtils::exceptionMapper); - } catch (RuntimeException ex) { - return monoError(LOGGER, ex); - } - } - - /** - * Creates a new Azure AI Search data source - * - *

Code Sample

- * - *

Create search indexer data source connection named "dataSource".

- * - * - *
-     * SearchIndexerDataSourceConnection dataSource = new SearchIndexerDataSourceConnection("dataSource",
-     *     com.azure.search.documents.indexes.models.SearchIndexerDataSourceType.AZURE_BLOB, "{connectionString}",
-     *     new com.azure.search.documents.indexes.models.SearchIndexerDataContainer("container"));
-     * SEARCH_INDEXER_ASYNC_CLIENT.createDataSourceConnection(dataSource)
-     *     .subscribe(dataSourceFromService ->
-     *         System.out.printf("The data source name is %s. The ETag of data source is %s.%n",
-     *             dataSourceFromService.getName(), dataSourceFromService.getETag()));
-     * 
- * - * - * @param dataSource The definition of the dataSource to create. - * @return a Mono which performs the network request upon subscription. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono - createDataSourceConnection(SearchIndexerDataSourceConnection dataSource) { - return createDataSourceConnectionWithResponse(dataSource).map(Response::getValue); - } - - /** - * Creates a new Azure AI Search data source - * - *

Code Sample

- * - *

Create search indexer data source connection named "dataSource".

- * - * - *
-     * SearchIndexerDataSourceConnection dataSource = new SearchIndexerDataSourceConnection("dataSource",
-     *     SearchIndexerDataSourceType.AZURE_BLOB, "{connectionString}",
-     *     new SearchIndexerDataContainer("container"));
-     * SEARCH_INDEXER_ASYNC_CLIENT.createDataSourceConnectionWithResponse(dataSource)
-     *     .subscribe(dataSourceFromService ->
-     *         System.out.printf("The status code of the response is %s. The data source name is %s.%n",
-     *         dataSourceFromService.getStatusCode(), dataSourceFromService.getValue().getName()));
-     * 
- * - * - * @param dataSource The definition of the {@link SearchIndexerDataSourceConnection} to create. - * @return a Mono which performs the network request upon subscription. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> - createDataSourceConnectionWithResponse(SearchIndexerDataSourceConnection dataSource) { - return withContext(context -> this.createDataSourceConnectionWithResponse(dataSource, context)); - } - - Mono> - createDataSourceConnectionWithResponse(SearchIndexerDataSourceConnection dataSource, Context context) { - try { - return restClient.getDataSources() - .createWithResponseAsync(dataSource, null, context) - .onErrorMap(MappingUtils::exceptionMapper); - } catch (RuntimeException ex) { - return monoError(LOGGER, ex); - } - } - - /** - * Retrieves a DataSource from an Azure AI Search service. - * - *

Code Sample

- * - *

Get search indexer data source connection named "dataSource".

- * - * - *
-     * SEARCH_INDEXER_ASYNC_CLIENT.getDataSourceConnection("dataSource")
-     *     .subscribe(dataSource ->
-     *         System.out.printf("The dataSource name is %s. The ETag of dataSource is %s.%n", dataSource.getName(),
-     *         dataSource.getETag()));
-     * 
- * - * - * @param dataSourceName the name of the {@link SearchIndexerDataSourceConnection} to retrieve. - * @return the DataSource. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono getDataSourceConnection(String dataSourceName) { - return getDataSourceConnectionWithResponse(dataSourceName).map(Response::getValue); - } - - /** - * Retrieves a DataSource from an Azure AI Search service. - * - *

Code Sample

- * - *

Get search indexer data source connection named "dataSource".

- * - * - *
-     * SEARCH_INDEXER_ASYNC_CLIENT.getDataSourceConnectionWithResponse("dataSource")
-     *     .subscribe(dataSource ->
-     *         System.out.printf("The status code of the response is %s. The data source name is %s.%n",
-     *         dataSource.getStatusCode(), dataSource.getValue().getName()));
-     * 
- * - * - * @param dataSourceName the name of the {@link SearchIndexerDataSourceConnection} to retrieve. - * @return a response containing the DataSource. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> - getDataSourceConnectionWithResponse(String dataSourceName) { - return withContext(context -> getDataSourceConnectionWithResponse(dataSourceName, context)); - } - - Mono> getDataSourceConnectionWithResponse(String dataSourceName, - Context context) { - try { - return restClient.getDataSources() - .getWithResponseAsync(dataSourceName, null, context) - .onErrorMap(MappingUtils::exceptionMapper); - } catch (RuntimeException ex) { - return monoError(LOGGER, ex); - } - } - - /** - * List all DataSources from an Azure AI Search service. - * - *

Code Sample

- * - *

List all search indexer data source connections.

- * - * - *
-     * SEARCH_INDEXER_ASYNC_CLIENT.listDataSourceConnections()
-     *     .subscribe(dataSource ->
-     *         System.out.printf("The dataSource name is %s. The ETag of dataSource is %s.%n",
-     *             dataSource.getName(), dataSource.getETag())
-     *     );
-     * 
- * - * - * @return a list of DataSources - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - public PagedFlux listDataSourceConnections() { - try { - return new PagedFlux<>( - () -> withContext(context -> this.listDataSourceConnectionsWithResponse(null, context)) - .map(MappingUtils::mappingPagingDataSource)); - } catch (RuntimeException ex) { - return pagedFluxError(LOGGER, ex); - } - } - - /** - * List all DataSource names from an Azure AI Search service. - * - *

Code Sample

- * - *

List all search indexer data source connection names.

- * - * - *
-     * SEARCH_INDEXER_ASYNC_CLIENT.listDataSourceConnectionNames()
-     *     .subscribe(dataSourceName -> System.out.printf("The dataSource name is %s.%n", dataSourceName));
-     * 
- * - * - * @return a list of DataSource names - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - public PagedFlux listDataSourceConnectionNames() { - try { - return new PagedFlux<>( - () -> withContext(context -> this.listDataSourceConnectionsWithResponse("name", context)) - .map(MappingUtils::mappingPagingDataSourceNames)); - } catch (RuntimeException ex) { - return pagedFluxError(LOGGER, ex); - } - } - - private Mono> listDataSourceConnectionsWithResponse(String select, - Context context) { - return restClient.getDataSources() - .listWithResponseAsync(select, null, context) - .onErrorMap(MappingUtils::exceptionMapper); - } - - /** - * Delete a DataSource - * - *

Code Sample

- * - *

Delete the search indexer data source connection named "dataSource".

- * - * - *
-     * SEARCH_INDEXER_ASYNC_CLIENT.deleteDataSourceConnection("dataSource")
-     *     .subscribe();
-     * 
- * - * - * @param dataSourceName the name of the {@link SearchIndexerDataSourceConnection} for deletion - * @return a void Mono - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono deleteDataSourceConnection(String dataSourceName) { - return withContext( - context -> deleteDataSourceConnectionWithResponse(dataSourceName, null, context).flatMap(FluxUtil::toMono)); - } - - /** - * Deletes an Azure AI Search data source. - * - *

Code Sample

- * - *

Delete the search indexer data source connection named "dataSource".

- * - * - *
-     * SEARCH_INDEXER_ASYNC_CLIENT.getDataSourceConnection("dataSource")
-     *     .flatMap(dataSource -> SEARCH_INDEXER_ASYNC_CLIENT.deleteDataSourceConnectionWithResponse(dataSource, true))
-     *     .subscribe(deleteResponse ->
-     *         System.out.printf("The status code of the response is %d.%n", deleteResponse.getStatusCode()));
-     * 
- * - * - * @param dataSource The {@link SearchIndexerDataSourceConnection} to delete. - * @param onlyIfUnchanged {@code true} to delete if the {@code dataSource} is the same as the current service value. - * {@code false} to always delete existing value. - * @return a mono response - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> deleteDataSourceConnectionWithResponse(SearchIndexerDataSourceConnection dataSource, - boolean onlyIfUnchanged) { - if (dataSource == null) { - return monoError(LOGGER, new NullPointerException("'dataSource' cannot be null.")); - } - String eTag = onlyIfUnchanged ? dataSource.getETag() : null; - return withContext(context -> deleteDataSourceConnectionWithResponse(dataSource.getName(), eTag, context)); - } - - Mono> deleteDataSourceConnectionWithResponse(String dataSourceName, String eTag, Context context) { - try { - return restClient.getDataSources() - .deleteWithResponseAsync(dataSourceName, eTag, null, null, context) - .onErrorMap(MappingUtils::exceptionMapper) - .map(Function.identity()); - } catch (RuntimeException ex) { - return monoError(LOGGER, ex); - } - } - - /** - * Creates a new Azure AI Search indexer. - * - *

Code Sample

- * - *

Create search indexer named "searchIndexer".

- * - * - *
-     * SearchIndexer searchIndexer = new SearchIndexer("searchIndexer", "dataSource",
-     *     "searchIndex");
-     * SEARCH_INDEXER_ASYNC_CLIENT.createIndexer(searchIndexer)
-     *     .subscribe(indexerFromService ->
-     *         System.out.printf("The indexer name is %s. The ETag of indexer is %s.%n", indexerFromService.getName(),
-     *         indexerFromService.getETag()));
-     * 
- * - * - * @param indexer definition of the indexer to create. - * @return the created Indexer. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono createIndexer(SearchIndexer indexer) { - return createIndexerWithResponse(indexer).map(Response::getValue); - } - - /** - * Creates a new Azure AI Search indexer. - * - *

Code Sample

- * - *

Create search indexer named "searchIndexer".

- * - * - *
-     * SearchIndexer searchIndexer = new SearchIndexer("searchIndexer", "dataSource",
-     *     "searchIndex");
-     * SEARCH_INDEXER_ASYNC_CLIENT.createIndexerWithResponse(searchIndexer)
-     *     .subscribe(indexerFromServiceResponse ->
-     *         System.out.printf("The status code of the response is %s. The indexer name is %s.%n",
-     *             indexerFromServiceResponse.getStatusCode(), indexerFromServiceResponse.getValue().getName()));
-     * 
- * - * - * @param indexer definition of the indexer to create - * @return a response containing the created Indexer. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> createIndexerWithResponse(SearchIndexer indexer) { - return withContext(context -> createIndexerWithResponse(indexer, context)); - } - - Mono> createIndexerWithResponse(SearchIndexer indexer, Context context) { - try { - return restClient.getIndexers() - .createWithResponseAsync(indexer, null, context) - .onErrorMap(MappingUtils::exceptionMapper); - } catch (RuntimeException ex) { - return monoError(LOGGER, ex); - } - } - - /** - * Creates a new Azure AI Search indexer or updates an indexer if it already exists. - * - *

Code Sample

- * - *

Create or update search indexer named "searchIndexer".

- * - * - *
-     * SEARCH_INDEXER_ASYNC_CLIENT.getIndexer("searchIndexer")
-     *     .flatMap(searchIndexerFromService -> {
-     *         searchIndexerFromService.setFieldMappings(Collections.singletonList(
-     *             new FieldMapping("hotelName").setTargetFieldName("HotelName")));
-     *         return SEARCH_INDEXER_ASYNC_CLIENT.createOrUpdateIndexer(searchIndexerFromService);
-     *     })
-     *     .subscribe(updatedIndexer ->
-     *         System.out.printf("The indexer name is %s. The target field name of indexer is %s.%n",
-     *         updatedIndexer.getName(), updatedIndexer.getFieldMappings().get(0).getTargetFieldName()));
-     * 
- * - * - * @param indexer The definition of the indexer to create or update. - * @return a response containing the created Indexer. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono createOrUpdateIndexer(SearchIndexer indexer) { - return createOrUpdateIndexerWithResponse(indexer, false).map(Response::getValue); - } - - /** - * Creates a new Azure AI Search indexer or updates an indexer if it already exists. - * - *

Code Sample

- * - *

Create or update search indexer named "searchIndexer".

- * - * - *
-     * SEARCH_INDEXER_ASYNC_CLIENT.getIndexer("searchIndexer")
-     *     .flatMap(searchIndexerFromService -> {
-     *         searchIndexerFromService.setFieldMappings(Collections.singletonList(
-     *             new FieldMapping("hotelName").setTargetFieldName("HotelName")));
-     *         return SEARCH_INDEXER_ASYNC_CLIENT.createOrUpdateIndexerWithResponse(searchIndexerFromService, true);
-     *     })
-     *     .subscribe(indexerFromService ->
-     *         System.out.printf("The status code of the response is %s.%nThe indexer name is %s. "
-     *             + "The target field name of indexer is %s.%n", indexerFromService.getStatusCode(),
-     *         indexerFromService.getValue().getName(),
-     *         indexerFromService.getValue().getFieldMappings().get(0).getTargetFieldName()));
-     * 
- * - * - * @param indexer the definition of the {@link SearchIndexer} to create or update - * @param onlyIfUnchanged {@code true} to update if the {@code indexer} is the same as the current service value. - * {@code false} to always update existing value. - * @return a response containing the created Indexer. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> createOrUpdateIndexerWithResponse(SearchIndexer indexer, - boolean onlyIfUnchanged) { - return withContext(context -> createOrUpdateIndexerWithResponse(indexer, onlyIfUnchanged, null, null, context)); - } - - Mono> createOrUpdateIndexerWithResponse(SearchIndexer indexer, boolean onlyIfUnchanged, - Boolean disableCacheReprocessingChangeDetection, Boolean ignoreResetRequirements, Context context) { - if (indexer == null) { - return monoError(LOGGER, new NullPointerException("'indexer' cannot be null.")); - } - String ifMatch = onlyIfUnchanged ? indexer.getETag() : null; - try { - return restClient.getIndexers() - .createOrUpdateWithResponseAsync(indexer.getName(), indexer, ifMatch, null, ignoreResetRequirements, - disableCacheReprocessingChangeDetection, null, context) - .onErrorMap(MappingUtils::exceptionMapper); - } catch (RuntimeException ex) { - return monoError(LOGGER, ex); - } - } - - /** - * Retrieves an indexer definition. - * - *

Code Sample

- * - *

Get search indexer with name "searchIndexer".

- * - * - *
-     * SEARCH_INDEXER_ASYNC_CLIENT.getIndexer("searchIndexer")
-     *     .subscribe(indexerFromService ->
-     *         System.out.printf("The indexer name is %s. The ETag of indexer is %s.%n", indexerFromService.getName(),
-     *             indexerFromService.getETag()));
-     * 
- * - * - * @param indexerName the name of the indexer to retrieve - * @return the indexer. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono getIndexer(String indexerName) { - return getIndexerWithResponse(indexerName).map(Response::getValue); - } - - /** - * Retrieves an indexer definition. - * - *

Code Sample

- * - *

Get search indexer with name "searchIndexer".

- * - * - *
-     * SEARCH_INDEXER_ASYNC_CLIENT.getIndexerWithResponse("searchIndexer")
-     *     .subscribe(indexerFromServiceResponse ->
-     *         System.out.printf("The status code of the response is %s. The indexer name is %s.%n",
-     *         indexerFromServiceResponse.getStatusCode(), indexerFromServiceResponse.getValue().getName()));
-     * 
- * - * - * @param indexerName the name of the indexer to retrieve - * @return a response containing the indexer. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> getIndexerWithResponse(String indexerName) { - return withContext(context -> getIndexerWithResponse(indexerName, context)); - } - - Mono> getIndexerWithResponse(String indexerName, Context context) { - try { - return restClient.getIndexers() - .getWithResponseAsync(indexerName, null, context) - .onErrorMap(MappingUtils::exceptionMapper); - } catch (RuntimeException ex) { - return monoError(LOGGER, ex); - } - } - - /** - * Lists all indexers available for an Azure AI Search service. - * - *

Code Sample

- * - *

List all search indexers.

- * - * - *
-     * SEARCH_INDEXER_ASYNC_CLIENT.listIndexers()
-     *     .subscribe(indexer ->
-     *         System.out.printf("The indexer name is %s. The ETag of indexer is %s.%n", indexer.getName(),
-     *         indexer.getETag()));
-     * 
- * - * - * @return a response containing all Indexers from the Search service. - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - public PagedFlux listIndexers() { - try { - return new PagedFlux<>(() -> withContext(context -> this.listIndexersWithResponse(null, context)) - .map(MappingUtils::mappingPagingSearchIndexer)); - } catch (RuntimeException ex) { - return pagedFluxError(LOGGER, ex); - } - } - - /** - * Lists all indexers available for an Azure AI Search service. - * - *

Code Sample

- * - *

List all search indexer names.

- * - * - *
-     * SEARCH_INDEXER_ASYNC_CLIENT.listIndexerNames()
-     *     .subscribe(indexerName -> System.out.printf("The indexer name is %s.%n", indexerName));
-     * 
- * - * - * @return a response containing all Indexers from the Search service. - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - public PagedFlux listIndexerNames() { - try { - return new PagedFlux<>(() -> withContext(context -> this.listIndexersWithResponse("name", context)) - .map(MappingUtils::mappingPagingSearchIndexerNames)); - } catch (RuntimeException ex) { - return pagedFluxError(LOGGER, ex); - } - } - - private Mono> listIndexersWithResponse(String select, Context context) { - return restClient.getIndexers() - .listWithResponseAsync(select, null, context) - .onErrorMap(MappingUtils::exceptionMapper); - } - - /** - * Deletes an Azure AI Search indexer. - * - *

Code Sample

- * - *

Delete search indexer named "searchIndexer".

- * - * - *
-     * SEARCH_INDEXER_ASYNC_CLIENT.deleteIndexer("searchIndexer")
-     *     .subscribe();
-     * 
- * - * - * @param indexerName the name of the indexer to delete - * @return a response signalling completion. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono deleteIndexer(String indexerName) { - return withContext(context -> deleteIndexerWithResponse(indexerName, null, context).flatMap(FluxUtil::toMono)); - } - - /** - * Deletes an Azure AI Search indexer. - * - *

Code Sample

- * - *

Delete search indexer named "searchIndexer".

- * - * - *
-     * SEARCH_INDEXER_ASYNC_CLIENT.getIndexer("searchIndexer")
-     *     .flatMap(searchIndexer ->
-     *         SEARCH_INDEXER_ASYNC_CLIENT.deleteIndexerWithResponse(searchIndexer, true))
-     *     .subscribe(deleteResponse ->
-     *         System.out.printf("The status code of the response is %d.%n", deleteResponse.getStatusCode()));
-     * 
- * - * - * @param indexer the {@link SearchIndexer} to delete - * @param onlyIfUnchanged {@code true} to delete if the {@code indexer} is the same as the current service value. - * {@code false} to always delete existing value. - * @return a response signalling completion. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> deleteIndexerWithResponse(SearchIndexer indexer, boolean onlyIfUnchanged) { - if (indexer == null) { - return monoError(LOGGER, new NullPointerException("'indexer' cannot be null.")); - } - String eTag = onlyIfUnchanged ? indexer.getETag() : null; - return withContext(context -> deleteIndexerWithResponse(indexer.getName(), eTag, context)); - } - - /** - * Deletes an Azure AI Search indexer. - * - * @param indexerName the name of the indexer to delete - * @param eTag Optional. The eTag to match. - * @param context the context - * @return a response signalling completion. - */ - Mono> deleteIndexerWithResponse(String indexerName, String eTag, Context context) { - try { - return restClient.getIndexers() - .deleteWithResponseAsync(indexerName, eTag, null, null, context) - .onErrorMap(MappingUtils::exceptionMapper) - .map(Function.identity()); - } catch (RuntimeException ex) { - return monoError(LOGGER, ex); - } - } - - /** - * Resets the change tracking state associated with an indexer. - * - *

Code Sample

- * - *

Reset search indexer named "searchIndexer".

- * - * - *
-     * SEARCH_INDEXER_ASYNC_CLIENT.resetIndexer("searchIndexer")
-     *     .subscribe();
-     * 
- * - * - * @param indexerName the name of the indexer to reset - * @return a response signalling completion. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono resetIndexer(String indexerName) { - return resetIndexerWithResponse(indexerName).flatMap(FluxUtil::toMono); - } - - /** - * Resets the change tracking state associated with an indexer. - * - *

Code Sample

- * - *

Reset search indexer named "searchIndexer".

- * - * - *
-     * SEARCH_INDEXER_ASYNC_CLIENT.resetIndexerWithResponse("searchIndexer")
-     *     .subscribe(response ->
-     *         System.out.println("The status code of the response is " + response.getStatusCode()));
-     * 
- * - * - * @param indexerName the name of the indexer to reset - * @return a response signalling completion. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> resetIndexerWithResponse(String indexerName) { - return withContext(context -> resetIndexerWithResponse(indexerName, context)); - } - - Mono> resetIndexerWithResponse(String indexerName, Context context) { - try { - return restClient.getIndexers() - .resetWithResponseAsync(indexerName, null, context) - .onErrorMap(MappingUtils::exceptionMapper) - .map(Function.identity()); - } catch (RuntimeException ex) { - return monoError(LOGGER, ex); - } - } - - /** - * Runs an indexer on-demand. - * - *

Code Sample

- * - *

Run search indexer named "searchIndexer".

- * - * - *
-     * SEARCH_INDEXER_ASYNC_CLIENT.runIndexer("searchIndexer")
-     *     .subscribe();
-     * 
- * - * - * @param indexerName the name of the indexer to run - * @return a response signalling completion. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono runIndexer(String indexerName) { - return runIndexerWithResponse(indexerName).flatMap(FluxUtil::toMono); - } - - /** - * Runs an indexer on-demand. - * - *

Code Sample

- * - *

Run search indexer named "searchIndexer".

- * - * - *
-     * SEARCH_INDEXER_ASYNC_CLIENT.runIndexerWithResponse("searchIndexer")
-     *     .subscribe(response ->
-     *         System.out.println("The status code of the response is " + response.getStatusCode()));
-     * 
- * - * - * @param indexerName the name of the indexer to run - * @return a response signalling completion. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> runIndexerWithResponse(String indexerName) { - return withContext(context -> runIndexerWithResponse(indexerName, context)); - } - - Mono> runIndexerWithResponse(String indexerName, Context context) { - try { - return restClient.getIndexers() - .runWithResponseAsync(indexerName, null, context) - .onErrorMap(MappingUtils::exceptionMapper) - .map(Function.identity()); - } catch (RuntimeException ex) { - return monoError(LOGGER, ex); - } - } - - /** - * Returns the current status and execution history of an indexer. - * - *

Code Sample

- * - *

Get status for search indexer "searchIndexer".

- * - * - *
-     * SEARCH_INDEXER_ASYNC_CLIENT.getIndexerStatus("searchIndexer")
-     *     .subscribe(indexerStatus ->
-     *         System.out.printf("The indexer status is %s.%n", indexerStatus.getStatus()));
-     * 
- * - * - * @param indexerName the name of the indexer for which to retrieve status - * @return the indexer execution info. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono getIndexerStatus(String indexerName) { - return getIndexerStatusWithResponse(indexerName).map(Response::getValue); - } - - /** - * Returns the current status and execution history of an indexer. - * - *

Code Sample

- * - *

Get search indexer status.

- * - * - *
-     * SEARCH_INDEXER_ASYNC_CLIENT.getIndexerStatusWithResponse("searchIndexer")
-     *     .subscribe(response ->
-     *         System.out.printf("The status code of the response is %s.%nThe indexer status is %s.%n",
-     *         response.getStatusCode(), response.getValue().getStatus()));
-     * 
- * - * - * @param indexerName the name of the indexer for which to retrieve status - * @return a response with the indexer execution info. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> getIndexerStatusWithResponse(String indexerName) { - return withContext(context -> getIndexerStatusWithResponse(indexerName, context)); - } - - Mono> getIndexerStatusWithResponse(String indexerName, Context context) { - try { - return restClient.getIndexers() - .getStatusWithResponseAsync(indexerName, null, context) - .onErrorMap(MappingUtils::exceptionMapper); - } catch (RuntimeException ex) { - return monoError(LOGGER, ex); - } - } - - /** - * Creates a new skillset in an Azure AI Search service. - * - *

Code Sample

- * - *

Create search indexer skillset "searchIndexerSkillset".

- * - * - *
-     * List<InputFieldMappingEntry> inputs = Collections.singletonList(
-     *     new InputFieldMappingEntry("image")
-     *         .setSource("/document/normalized_images/*")
-     * );
-     *
-     * List<OutputFieldMappingEntry> outputs = Arrays.asList(
-     *     new OutputFieldMappingEntry("text")
-     *         .setTargetName("mytext"),
-     *     new OutputFieldMappingEntry("layoutText")
-     *         .setTargetName("myLayoutText")
-     * );
-     * SearchIndexerSkillset searchIndexerSkillset = new SearchIndexerSkillset("searchIndexerSkillset",
-     *     Collections.singletonList(new OcrSkill(inputs, outputs)
-     *         .setShouldDetectOrientation(true)
-     *         .setDefaultLanguageCode(null)
-     *         .setName("myocr")
-     *         .setDescription("Extracts text (plain and structured) from image.")
-     *         .setContext("/document/normalized_images/*")));
-     * SEARCH_INDEXER_ASYNC_CLIENT.createSkillset(searchIndexerSkillset)
-     *     .subscribe(skillset ->
-     *         System.out.printf("The indexer skillset name is %s. The ETag of indexer skillset is %s.%n",
-     *         skillset.getName(), skillset.getETag()));
-     * 
- * - * - * @param skillset definition of the skillset containing one or more cognitive skills - * @return the created Skillset. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono createSkillset(SearchIndexerSkillset skillset) { - return createSkillsetWithResponse(skillset).map(Response::getValue); - } - - /** - * Creates a new skillset in an Azure AI Search service. - * - *

Code Sample

- * - *

Create search indexer skillset "searchIndexerSkillset".

- * - * - *
-     * List<InputFieldMappingEntry> inputs = Collections.singletonList(
-     *     new InputFieldMappingEntry("image")
-     *         .setSource("/document/normalized_images/*")
-     * );
-     *
-     * List<OutputFieldMappingEntry> outputs = Arrays.asList(
-     *     new OutputFieldMappingEntry("text")
-     *         .setTargetName("mytext"),
-     *     new OutputFieldMappingEntry("layoutText")
-     *         .setTargetName("myLayoutText")
-     * );
-     * SearchIndexerSkillset searchIndexerSkillset = new SearchIndexerSkillset("searchIndexerSkillset",
-     *     Collections.singletonList(new OcrSkill(inputs, outputs)
-     *         .setShouldDetectOrientation(true)
-     *         .setDefaultLanguageCode(null)
-     *         .setName("myocr")
-     *         .setDescription("Extracts text (plain and structured) from image.")
-     *         .setContext("/document/normalized_images/*")));
-     * SEARCH_INDEXER_ASYNC_CLIENT.createSkillsetWithResponse(searchIndexerSkillset)
-     *     .subscribe(skillsetWithResponse ->
-     *         System.out.printf("The status code of the response is %s. The indexer skillset name is %s.%n",
-     *         skillsetWithResponse.getStatusCode(), skillsetWithResponse.getValue().getName()));
-     * 
- * - * - * @param skillset definition of the skillset containing one or more cognitive skills - * @return a response containing the created Skillset. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> createSkillsetWithResponse(SearchIndexerSkillset skillset) { - return withContext(context -> createSkillsetWithResponse(skillset, context)); - } - - Mono> createSkillsetWithResponse(SearchIndexerSkillset skillset, Context context) { - if (skillset == null) { - return monoError(LOGGER, new NullPointerException("'skillset' cannot be null.")); - } - try { - return restClient.getSkillsets() - .createWithResponseAsync(skillset, null, context) - .onErrorMap(MappingUtils::exceptionMapper); - } catch (RuntimeException ex) { - return monoError(LOGGER, ex); - } - } - - /** - * Retrieves a skillset definition. - * - *

Code Sample

- * - *

Get search indexer skillset "searchIndexerSkillset".

- * - * - *
-     * SEARCH_INDEXER_ASYNC_CLIENT.getSkillset("searchIndexerSkillset")
-     *     .subscribe(indexerSkillset ->
-     *         System.out.printf("The indexer skillset name is %s. The ETag of indexer skillset is %s.%n",
-     *         indexerSkillset.getName(), indexerSkillset.getETag()));
-     * 
- * - * - * @param skillsetName the name of the skillset to retrieve - * @return the Skillset. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono getSkillset(String skillsetName) { - return getSkillsetWithResponse(skillsetName).map(Response::getValue); - } - - /** - * Retrieves a skillset definition. - * - *

Code Sample

- * - *

Get search indexer skillset "searchIndexerSkillset".

- * - * - *
-     * SEARCH_INDEXER_ASYNC_CLIENT.getSkillsetWithResponse("searchIndexerSkillset")
-     *     .subscribe(skillsetWithResponse ->
-     *         System.out.printf("The status code of the response is %s. The indexer skillset name is %s.%n",
-     *         skillsetWithResponse.getStatusCode(), skillsetWithResponse.getValue().getName()));
-     * 
- * - * - * @param skillsetName the name of the skillset to retrieve - * @return a response containing the Skillset. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> getSkillsetWithResponse(String skillsetName) { - return withContext(context -> getSkillsetWithResponse(skillsetName, context)); - } - - Mono> getSkillsetWithResponse(String skillsetName, Context context) { - try { - return this.restClient.getSkillsets() - .getWithResponseAsync(skillsetName, null, context) - .onErrorMap(MappingUtils::exceptionMapper); - } catch (RuntimeException ex) { - return monoError(LOGGER, ex); - } - } - - /** - * Lists all skillsets available for an Azure AI Search service. - * - *

Code Sample

- * - *

List all search indexer skillsets.

- * - * - *
-     * SEARCH_INDEXER_ASYNC_CLIENT.listSkillsets()
-     *     .subscribe(skillset ->
-     *         System.out.printf("The skillset name is %s. The ETag of skillset is %s.%n", skillset.getName(),
-     *         skillset.getETag()));
-     * 
- * - * - * @return a reactive response emitting the list of skillsets. - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - public PagedFlux listSkillsets() { - try { - return new PagedFlux<>(() -> withContext(context -> listSkillsetsWithResponse(null, context)) - .map(MappingUtils::mappingPagingSkillset)); - } catch (RuntimeException ex) { - return pagedFluxError(LOGGER, ex); - } - } - - /** - * Lists all skillset names for an Azure AI Search service. - * - *

Code Sample

- * - *

List all search indexer skillset names.

- * - * - *
-     * SEARCH_INDEXER_ASYNC_CLIENT.listSkillsetNames()
-     *     .subscribe(skillsetName -> System.out.printf("The indexer skillset name is %s.%n", skillsetName));
-     * 
- * - * - * @return a reactive response emitting the list of skillset names. - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - public PagedFlux listSkillsetNames() { - try { - return new PagedFlux<>(() -> withContext(context -> listSkillsetsWithResponse("name", context)) - .map(MappingUtils::mappingPagingSkillsetNames)); - } catch (RuntimeException ex) { - return pagedFluxError(LOGGER, ex); - } - } - - private Mono> listSkillsetsWithResponse(String select, Context context) { - return this.restClient.getSkillsets() - .listWithResponseAsync(select, null, context) - .onErrorMap(MappingUtils::exceptionMapper); - } - - /** - * Creates a new Azure AI Search skillset or updates a skillset if it already exists. - * - *

Code Sample

- * - *

Create or update search indexer skillset "searchIndexerSkillset".

- * - * - *
-     * SEARCH_INDEXER_ASYNC_CLIENT.getSkillset("searchIndexerSkillset")
-     *     .flatMap(indexerSkillset -> {
-     *         indexerSkillset.setDescription("This is new description!");
-     *         return SEARCH_INDEXER_ASYNC_CLIENT.createOrUpdateSkillset(indexerSkillset);
-     *     }).subscribe(updateSkillset ->
-     *         System.out.printf("The indexer skillset name is %s. The description of indexer skillset is %s.%n",
-     *         updateSkillset.getName(), updateSkillset.getDescription()));
-     * 
- * - * - * @param skillset the definition of the skillset to create or update - * @return the skillset that was created or updated. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono createOrUpdateSkillset(SearchIndexerSkillset skillset) { - return createOrUpdateSkillsetWithResponse(skillset, false).map(Response::getValue); - } - - /** - * Creates a new Azure AI Search skillset or updates a skillset if it already exists. - * - *

Code Sample

- * - *

Create or update search indexer skillset "searchIndexerSkillset".

- * - * - *
-     * SEARCH_INDEXER_ASYNC_CLIENT.getSkillset("searchIndexerSkillset")
-     *     .flatMap(indexerSkillset -> {
-     *         indexerSkillset.setDescription("This is new description!");
-     *         return SEARCH_INDEXER_ASYNC_CLIENT.createOrUpdateSkillsetWithResponse(indexerSkillset, true);
-     *     })
-     *     .subscribe(updateSkillsetResponse ->
-     *         System.out.printf("The status code of the response is %s.%nThe indexer skillset name is %s. "
-     *             + "The description of indexer skillset is %s.%n", updateSkillsetResponse.getStatusCode(),
-     *         updateSkillsetResponse.getValue().getName(),
-     *         updateSkillsetResponse.getValue().getDescription()));
-     * 
- * - * - * @param skillset the definition of the skillset to create or update - * @param onlyIfUnchanged {@code true} to update if the {@code skillset} is the same as the current service value. - * {@code false} to always update existing value. - * @return a response containing the skillset that was created or updated. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> createOrUpdateSkillsetWithResponse(SearchIndexerSkillset skillset, - boolean onlyIfUnchanged) { - return withContext( - context -> createOrUpdateSkillsetWithResponse(skillset, onlyIfUnchanged, null, null, context)); - } - - Mono> createOrUpdateSkillsetWithResponse(SearchIndexerSkillset skillset, - boolean onlyIfUnchanged, Boolean disableCacheReprocessingChangeDetection, Boolean ignoreResetRequirements, - Context context) { - if (skillset == null) { - return monoError(LOGGER, new NullPointerException("'skillset' cannot be null.")); - } - String ifMatch = onlyIfUnchanged ? skillset.getETag() : null; - try { - return restClient.getSkillsets() - .createOrUpdateWithResponseAsync(skillset.getName(), skillset, ifMatch, null, ignoreResetRequirements, - disableCacheReprocessingChangeDetection, null, context) - .onErrorMap(MappingUtils::exceptionMapper); - } catch (RuntimeException ex) { - return monoError(LOGGER, ex); - } - } - - /** - * Deletes a cognitive skillset in an Azure AI Search service. - * - *

Code Sample

- * - *

Delete search indexer skillset "searchIndexerSkillset".

- * - * - *
-     * SEARCH_INDEXER_ASYNC_CLIENT.deleteSkillset("searchIndexerSkillset")
-     *     .subscribe();
-     * 
- * - * - * @param skillsetName the name of the skillset to delete - * @return a response signalling completion. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono deleteSkillset(String skillsetName) { - return withContext( - context -> deleteSkillsetWithResponse(skillsetName, null, context).flatMap(FluxUtil::toMono)); - } - - /** - * Deletes a cognitive skillset in an Azure AI Search service. - * - *

Code Sample

- * - *

Delete search indexer skillset "searchIndexerSkillset".

- * - * - *
-     * SEARCH_INDEXER_ASYNC_CLIENT.getSkillset("searchIndexerSkillset")
-     *     .flatMap(searchIndexerSkillset ->
-     *         SEARCH_INDEXER_ASYNC_CLIENT.deleteSkillsetWithResponse(searchIndexerSkillset, true))
-     *     .subscribe(deleteResponse ->
-     *         System.out.printf("The status code of the response is %d.%n", deleteResponse.getStatusCode()));
-     * 
- * - * - * @param skillset the {@link SearchIndexerSkillset} to delete. - * @param onlyIfUnchanged {@code true} to delete if the {@code skillset} is the same as the current service value. - * {@code false} to always delete existing value. - * @return a response signalling completion. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> deleteSkillsetWithResponse(SearchIndexerSkillset skillset, boolean onlyIfUnchanged) { - if (skillset == null) { - return monoError(LOGGER, new NullPointerException("'skillset' cannot be null.")); - } - String eTag = onlyIfUnchanged ? skillset.getETag() : null; - return withContext(context -> deleteSkillsetWithResponse(skillset.getName(), eTag, context)); - } - - Mono> deleteSkillsetWithResponse(String skillsetName, String eTag, Context context) { - try { - return restClient.getSkillsets() - .deleteWithResponseAsync(skillsetName, eTag, null, null, context) - .onErrorMap(MappingUtils::exceptionMapper) - .map(Function.identity()); - } catch (RuntimeException ex) { - return monoError(LOGGER, ex); - } - } -} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/SearchIndexerClient.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/SearchIndexerClient.java deleted file mode 100644 index abc4de3a661a..000000000000 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/SearchIndexerClient.java +++ /dev/null @@ -1,1616 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.search.documents.indexes; - -import com.azure.core.annotation.ReturnType; -import com.azure.core.annotation.ServiceClient; -import com.azure.core.annotation.ServiceMethod; -import com.azure.core.http.HttpPipeline; -import com.azure.core.http.rest.PagedIterable; -import com.azure.core.http.rest.Response; -import com.azure.core.util.Context; -import com.azure.core.util.logging.ClientLogger; -import com.azure.search.documents.SearchServiceVersion; -import com.azure.search.documents.implementation.util.MappingUtils; -import com.azure.search.documents.implementation.util.Utility; -import com.azure.search.documents.indexes.implementation.SearchServiceClientImpl; -import com.azure.search.documents.indexes.implementation.models.ListDataSourcesResult; -import com.azure.search.documents.indexes.implementation.models.ListIndexersResult; -import com.azure.search.documents.indexes.implementation.models.ListSkillsetsResult; -import com.azure.search.documents.indexes.models.SearchIndexer; -import com.azure.search.documents.indexes.models.SearchIndexerDataSourceConnection; -import com.azure.search.documents.indexes.models.SearchIndexerSkillset; -import com.azure.search.documents.indexes.models.SearchIndexerStatus; - -/** - * This class provides a client that contains the operations for creating, getting, listing, updating, or deleting data - * source connections, indexers, or skillsets and running or resetting indexers in an Azure AI Search service. - * - *

- * Overview - *

- * - *

- * Indexers provide indexing automation. An indexer connects to a data source, reads in the data, and passes it to a - * skillset pipeline for indexing into a target search index. Indexers read from an external source using connection - * information in a data source, and serialize the incoming data into JSON search documents. In addition to a data - * source, an indexer also requires an index. The index specifies the fields and attributes of the search documents. - *

- * - *

- * A skillset adds external processing steps to indexer execution, and is usually used to add AI or deep learning - * models to analyze or transform content to make it searchable in an index. The contents of a skillset are one or - * more skills, which can be built-in skills - * created by Microsoft, custom skills, or a combination of both. Built-in skills exist for image analysis, - * including OCR, and natural language processing. Other examples of built-in skills include entity recognition, - * key phrase extraction, chunking text into logical pages, among others. A skillset is high-level standalone object - * that exists on a level equivalent to indexes, indexers, and data sources, but it's operational only within indexer - * processing. As a high-level object, you can design a skillset once, and then reference it in multiple indexers. - *

- * - *

- * This client provides a synchronous API for accessing indexers and skillsets. This client allows you to create, - * update, list, or delete indexers and skillsets. It can also be used to run or reset indexers. - *

- * - *

- * Getting Started - *

- * - *

- * Authenticating and building instances of this client are handled by {@link SearchIndexerClientBuilder}. This - * sample shows you how to authenticate and build this client: - *

- * - * - *
- * SearchIndexerClient searchIndexerClient = new SearchIndexerClientBuilder()
- *     .endpoint("{endpoint}")
- *     .credential(new AzureKeyCredential("{admin-key}"))
- *     .buildClient();
- * 
- * - * - *

- * For more information on authentication and building, see the {@link SearchIndexerClientBuilder} documentation. - *

- * - *

- * Examples - *

- * - *

- * The following examples all use a simple Hotel - * data set that you can - * import into your own index from the Azure portal. - * These are just a few of the basics - please check out our Samples for much more. - *

- * - *

- * Create an Indexer - *

- * - *

- * The following sample creates an indexer. - *

- * - * - *
- * SearchIndexer indexer = new SearchIndexer("example-indexer", "example-datasource", "example-index");
- * SearchIndexer createdIndexer = searchIndexerClient.createIndexer(indexer);
- * System.out.printf("Created indexer name: %s%n", createdIndexer.getName());
- * 
- * - * - * - * For an asynchronous sample, see {@link SearchIndexerAsyncClient#createIndexer(SearchIndexer)}. - * - * - *

- * List all Indexers - *

- * - *

- * The following sample lists all indexers. - *

- * - * - *
- * searchIndexerClient.listIndexers().forEach(indexer ->
- *     System.out.printf("Retrieved indexer name: %s%n", indexer.getName())
- * );
- * 
- * - * - * For an asynchronous sample, see {@link SearchIndexerAsyncClient#listIndexers()}. - * - * - *

- * Get an Indexer - *

- * - *

- * The following sample gets an indexer. - *

- * - * - *
- * SearchIndexer indexer = searchIndexerClient.getIndexer("example-indexer");
- * System.out.printf("Retrieved indexer name: %s%n", indexer.getName());
- * 
- * - * - * - * For an asynchronous sample, see {@link SearchIndexerAsyncClient#getIndexer(String)}. - * - * - *

- * Update an Indexer - *

- * - *

- * The following sample updates an indexer. - *

- * - * - *
- * SearchIndexer indexer = searchIndexerClient.getIndexer("example-indexer");
- * indexer.setDescription("This is a new description for this indexer");
- * SearchIndexer updatedIndexer = searchIndexerClient.createOrUpdateIndexer(indexer);
- * System.out.printf("Updated indexer name: %s, description: %s%n", updatedIndexer.getName(),
- *     updatedIndexer.getDescription());
- * 
- * - * - * - * For an asynchronous sample, see {@link SearchIndexerAsyncClient#createOrUpdateIndexer(SearchIndexer)}. - * - * - *

- * Delete an Indexer - *

- * - *

- * The following sample deletes an indexer. - *

- * - * - *
- * searchIndexerClient.deleteIndexer("example-indexer");
- * 
- * - * - * - * For an asynchronous sample, see {@link SearchIndexerAsyncClient#deleteIndexer(String)}. - * - * - *

- * Run an Indexer - *

- * - *

- * The following sample runs an indexer. - *

- * - * - *
- * searchIndexerClient.runIndexer("example-indexer");
- * 
- * - * - * - * For an asynchronous sample, see {@link SearchIndexerAsyncClient#runIndexer(String)}. - * - * - *

- * Reset an Indexer - *

- * - *

- * The following sample resets an indexer. - *

- * - * - *
- * searchIndexerClient.resetIndexer("example-indexer");
- * 
- * - * - * - * For an asynchronous sample, see {@link SearchIndexerAsyncClient#resetIndexer(String)}. - * - * - *

- * Create a Skillset - *

- * - *

- * The following sample creates a skillset. - *

- * - * - *
- *
- * List<InputFieldMappingEntry> inputs = Collections.singletonList(
- *     new InputFieldMappingEntry("image")
- *         .setSource("/document/normalized_images/*")
- * );
- *
- * List<OutputFieldMappingEntry> outputs = Arrays.asList(
- *     new OutputFieldMappingEntry("text")
- *         .setTargetName("mytext"),
- *     new OutputFieldMappingEntry("layoutText")
- *         .setTargetName("myLayoutText")
- * );
- *
- * List<SearchIndexerSkill> skills = Collections.singletonList(
- *     new OcrSkill(inputs, outputs)
- *         .setShouldDetectOrientation(true)
- *         .setDefaultLanguageCode(null)
- *         .setName("myocr")
- *         .setDescription("Extracts text (plain and structured) from image.")
- *         .setContext("/document/normalized_images/*")
- * );
- *
- * SearchIndexerSkillset skillset = new SearchIndexerSkillset("skillsetName", skills)
- *     .setDescription("Extracts text (plain and structured) from image.");
- *
- * System.out.println(String.format("Creating OCR skillset '%s'", skillset.getName()));
- *
- * SearchIndexerSkillset createdSkillset = searchIndexerClient.createSkillset(skillset);
- *
- * System.out.println("Created OCR skillset");
- * System.out.println(String.format("Name: %s", createdSkillset.getName()));
- * System.out.println(String.format("ETag: %s", createdSkillset.getETag()));
- *
- * 
- * - * - * - * For an asynchronous sample, see {@link SearchIndexerAsyncClient#createSkillset(SearchIndexerSkillset)}. - * - * - *

- * List all Skillsets - *

- * - *

- * The following sample lists all skillsets. - *

- * - * - *
- * searchIndexerClient.listSkillsets().forEach(skillset ->
- *     System.out.printf("Retrieved skillset name: %s%n", skillset.getName())
- * );
- * 
- * - * - * - * For an asynchronous sample, see {@link SearchIndexerAsyncClient#listSkillsets()}. - * - * - *

- * Get a Skillset - *

- * - *

- * The following sample gets a skillset. - *

- * - * - *
- * SearchIndexerSkillset skillset = searchIndexerClient.getSkillset("example-skillset");
- * System.out.printf("Retrieved skillset name: %s%n", skillset.getName());
- * 
- * - * - * - * For an asynchronous sample, see {@link SearchIndexerAsyncClient#getSkillset(String)}. - * - * - *

- * Update a Skillset - *

- * - *

- * The following sample updates a skillset. - *

- * - * - *
- * SearchIndexerSkillset skillset = searchIndexerClient.getSkillset("example-skillset");
- * skillset.setDescription("This is a new description for this skillset");
- * SearchIndexerSkillset updatedSkillset = searchIndexerClient.createOrUpdateSkillset(skillset);
- * System.out.printf("Updated skillset name: %s, description: %s%n", updatedSkillset.getName(),
- *     updatedSkillset.getDescription());
- * 
- * - * - * - * For an asynchronous sample, see {@link SearchIndexerAsyncClient#createOrUpdateSkillset(SearchIndexerSkillset)}. - * - * - *

- * Delete a Skillset - *

- * - *

- * The following sample deletes a skillset. - *

- * - * - *
- * searchIndexerClient.deleteSkillset("example-skillset");
- * 
- * - * - * - * For an asynchronous sample, see {@link SearchIndexerAsyncClient#deleteSkillset(String)}. - * - * - * @see SearchIndexerAsyncClient - * @see SearchIndexerClientBuilder - * @see com.azure.search.documents.indexes - */ -@ServiceClient(builder = SearchIndexerClientBuilder.class) -public class SearchIndexerClient { - private static final ClientLogger LOGGER = new ClientLogger(SearchIndexerClient.class); - - /** - * Search REST API Version - */ - private final SearchServiceVersion serviceVersion; - - /** - * The endpoint for the Azure AI Search service. - */ - private final String endpoint; - - /** - * The underlying AutoRest client used to interact with the Search service - */ - private final SearchServiceClientImpl restClient; - - /** - * The pipeline that powers this client. - */ - private final HttpPipeline httpPipeline; - - SearchIndexerClient(String endpoint, SearchServiceVersion serviceVersion, HttpPipeline httpPipeline) { - this.endpoint = endpoint; - this.serviceVersion = serviceVersion; - this.httpPipeline = httpPipeline; - this.restClient = new SearchServiceClientImpl(httpPipeline, endpoint, serviceVersion.getVersion()); - } - - /** - * Gets the {@link HttpPipeline} powering this client. - * - * @return the pipeline. - */ - HttpPipeline getHttpPipeline() { - return this.httpPipeline; - } - - /** - * Gets the endpoint for the Azure AI Search service. - * - * @return the endpoint value. - */ - public String getEndpoint() { - return this.endpoint; - } - - /** - * Creates a new Azure AI Search data source or updates a data source if it already exists - * - *

Code Sample

- * - *

Create or update search indexer data source connection named "dataSource".

- * - * - *
-     * SearchIndexerDataSourceConnection dataSource = SEARCH_INDEXER_CLIENT.getDataSourceConnection("dataSource");
-     * dataSource.setContainer(new SearchIndexerDataContainer("updatecontainer"));
-     *
-     * SearchIndexerDataSourceConnection updateDataSource = SEARCH_INDEXER_CLIENT
-     *     .createOrUpdateDataSourceConnection(dataSource);
-     * System.out.printf("The dataSource name is %s. The container name of dataSource is %s.%n",
-     *     updateDataSource.getName(), updateDataSource.getContainer().getName());
-     * 
- * - * - * @param dataSourceConnection The definition of the data source to create or update. - * @return the data source that was created or updated. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public SearchIndexerDataSourceConnection - createOrUpdateDataSourceConnection(SearchIndexerDataSourceConnection dataSourceConnection) { - return createOrUpdateDataSourceConnectionWithResponse(dataSourceConnection, false, Context.NONE).getValue(); - } - - /** - * Creates a new Azure AI Search data source or updates a data source if it already exists. - * - *

Code Sample

- * - *

Create or update search indexer data source connection named "dataSource".

- * - * - *
-     * SearchIndexerDataSourceConnection dataSource = SEARCH_INDEXER_CLIENT.getDataSourceConnection("dataSource");
-     * dataSource.setContainer(new SearchIndexerDataContainer("updatecontainer"));
-     *
-     * Response<SearchIndexerDataSourceConnection> updateDataSource = SEARCH_INDEXER_CLIENT
-     *     .createOrUpdateDataSourceConnectionWithResponse(dataSource, true, new Context(KEY_1, VALUE_1));
-     * System.out.printf("The status code of the response is %s.%nThe dataSource name is %s. "
-     *     + "The container name of dataSource is %s.%n", updateDataSource.getStatusCode(),
-     *     updateDataSource.getValue().getName(), updateDataSource.getValue().getContainer().getName());
-     * 
- * - * - * @param dataSourceConnection the {@link SearchIndexerDataSourceConnection} to create or update - * @param onlyIfUnchanged {@code true} to update if the {@code dataSourceConnection} is the same as the current - * service value. {@code false} to always update existing value. - * @param context additional context that is passed through the HTTP pipeline during the service call - * @return a response containing data source that was created or updated. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Response createOrUpdateDataSourceConnectionWithResponse( - SearchIndexerDataSourceConnection dataSourceConnection, boolean onlyIfUnchanged, Context context) { - return createOrUpdateDataSourceConnectionWithResponse(dataSourceConnection, onlyIfUnchanged, null, context); - } - - Response createOrUpdateDataSourceConnectionWithResponse( - SearchIndexerDataSourceConnection dataSource, boolean onlyIfUnchanged, Boolean ignoreResetRequirements, - Context context) { - if (dataSource == null) { - throw LOGGER.logExceptionAsError(new NullPointerException("'dataSource' cannot be null.")); - } - String ifMatch = onlyIfUnchanged ? dataSource.getETag() : null; - if (dataSource.getConnectionString() == null) { - dataSource.setConnectionString(""); - } - return Utility.executeRestCallWithExceptionHandling(() -> restClient.getDataSources() - .createOrUpdateWithResponse(dataSource.getName(), dataSource, ifMatch, null, ignoreResetRequirements, null, - context), - LOGGER); - } - - /** - * Creates a new Azure AI Search data source - * - *

Code Sample

- * - *

Create search indexer data source connection named "dataSource".

- * - * - *
-     * SearchIndexerDataSourceConnection dataSource = new SearchIndexerDataSourceConnection("dataSource",
-     *     com.azure.search.documents.indexes.models.SearchIndexerDataSourceType.AZURE_BLOB, "{connectionString}",
-     *     new com.azure.search.documents.indexes.models.SearchIndexerDataContainer("container"));
-     * SearchIndexerDataSourceConnection dataSourceFromService =
-     *     SEARCH_INDEXER_CLIENT.createDataSourceConnection(dataSource);
-     * System.out.printf("The data source name is %s. The ETag of data source is %s.%n",
-     *     dataSourceFromService.getName(), dataSourceFromService.getETag());
-     * 
- * - * - * @param dataSourceConnection The definition of the data source to create - * @return the data source that was created. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public SearchIndexerDataSourceConnection - createDataSourceConnection(SearchIndexerDataSourceConnection dataSourceConnection) { - return createDataSourceConnectionWithResponse(dataSourceConnection, Context.NONE).getValue(); - } - - /** - * Creates a new Azure AI Search data source - * - *

Code Sample

- * - *

Create search indexer data source connection named "dataSource".

- * - * - *
-     * SearchIndexerDataSourceConnection dataSource = new SearchIndexerDataSourceConnection("dataSource",
-     *     SearchIndexerDataSourceType.AZURE_BLOB, "{connectionString}",
-     *     new SearchIndexerDataContainer("container"));
-     * Response<SearchIndexerDataSourceConnection> dataSourceFromService =
-     *     SEARCH_INDEXER_CLIENT.createDataSourceConnectionWithResponse(dataSource, new Context(KEY_1, VALUE_1));
-     *
-     * System.out.printf("The status code of the response is %s. The data source name is %s.%n",
-     *     dataSourceFromService.getStatusCode(), dataSourceFromService.getValue().getName());
-     * 
- * - * - * @param dataSourceConnection the definition of the data source to create doesn't match specified values - * @param context additional context that is passed through the HTTP pipeline during the service call - * @return a response containing data source that was created. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Response createDataSourceConnectionWithResponse( - SearchIndexerDataSourceConnection dataSourceConnection, Context context) { - return Utility.executeRestCallWithExceptionHandling( - () -> restClient.getDataSources().createWithResponse(dataSourceConnection, null, context), LOGGER); - } - - /** - * Retrieves a DataSource from an Azure AI Search service. - * - *

Code Sample

- * - *

Get search indexer data source connection named "dataSource".

- * - * - *
-     * SearchIndexerDataSourceConnection dataSource =
-     *     SEARCH_INDEXER_CLIENT.getDataSourceConnection("dataSource");
-     * System.out.printf("The dataSource name is %s. The ETag of dataSource is %s.%n", dataSource.getName(),
-     *     dataSource.getETag());
-     * 
- * - * - * @param dataSourceConnectionName the name of the data source to retrieve - * @return the DataSource. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public SearchIndexerDataSourceConnection getDataSourceConnection(String dataSourceConnectionName) { - return getDataSourceConnectionWithResponse(dataSourceConnectionName, Context.NONE).getValue(); - } - - /** - * Retrieves a DataSource from an Azure AI Search service. - * - *

Code Sample

- * - *

Get search indexer data source connection named "dataSource".

- * - * - *
-     * Response<SearchIndexerDataSourceConnection> dataSource =
-     *     SEARCH_INDEXER_CLIENT.getDataSourceConnectionWithResponse(
-     *         "dataSource", new Context(KEY_1, VALUE_1));
-     *
-     * System.out.printf("The status code of the response is %s. The data source name is %s.%n",
-     *     dataSource.getStatusCode(), dataSource.getValue().getName());
-     * 
- * - * - * @param dataSourceConnectionName the name of the data source to retrieve - * @param context additional context that is passed through the HTTP pipeline during the service call - * @return a response containing the DataSource. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Response - getDataSourceConnectionWithResponse(String dataSourceConnectionName, Context context) { - return Utility.executeRestCallWithExceptionHandling( - () -> restClient.getDataSources().getWithResponse(dataSourceConnectionName, null, context), LOGGER); - } - - /** - * List all DataSources from an Azure AI Search service. - * - *

Code Sample

- * - *

List all search indexer data source connections.

- * - * - *
-     * PagedIterable<SearchIndexerDataSourceConnection> dataSources = SEARCH_INDEXER_CLIENT.listDataSourceConnections();
-     * for (SearchIndexerDataSourceConnection dataSource: dataSources) {
-     *     System.out.printf("The dataSource name is %s. The ETag of dataSource is %s.%n", dataSource.getName(),
-     *         dataSource.getETag());
-     * }
-     * 
- * - * - * @return a list of DataSources - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - public PagedIterable listDataSourceConnections() { - return listDataSourceConnections(Context.NONE); - } - - /** - * List all DataSources from an Azure AI Search service. - * - *

Code Sample

- * - *

List all search indexer data source connections.

- * - * - *
-     * PagedIterable<SearchIndexerDataSourceConnection> dataSources =
-     *     SEARCH_INDEXER_CLIENT.listDataSourceConnections(new Context(KEY_1, VALUE_1));
-     *
-     * System.out.println("The status code of the response is"
-     *     + dataSources.iterableByPage().iterator().next().getStatusCode());
-     * for (SearchIndexerDataSourceConnection dataSource: dataSources) {
-     *     System.out.printf("The dataSource name is %s. The ETag of dataSource is %s.%n",
-     *         dataSource.getName(), dataSource.getETag());
-     * }
-     * 
- * - * - * @param context Additional context that is passed through the HTTP pipeline during the service call. - * @return a response containing the list of DataSources. - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - public PagedIterable listDataSourceConnections(Context context) { - try { - return new PagedIterable<>( - () -> MappingUtils.mappingPagingDataSource(listDataSourceConnectionsWithResponse(null, context))); - } catch (RuntimeException ex) { - throw LOGGER.logExceptionAsError(ex); - } - } - - private Response listDataSourceConnectionsWithResponse(String select, Context context) { - return Utility.executeRestCallWithExceptionHandling( - () -> restClient.getDataSources().listWithResponse(select, null, context), LOGGER); - } - - /** - * List all DataSource names from an Azure AI Search service. - * - *

Code Sample

- * - *

List all search indexer data source connection names.

- * - * - *
-     * PagedIterable<String> dataSources = SEARCH_INDEXER_CLIENT.listDataSourceConnectionNames();
-     * for (String dataSourceName: dataSources) {
-     *     System.out.printf("The dataSource name is %s.%n", dataSourceName);
-     * }
-     * 
- * - * - * @return a list of DataSources names - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - public PagedIterable listDataSourceConnectionNames() { - return listDataSourceConnectionNames(Context.NONE); - } - - /** - * List all DataSources names from an Azure AI Search service. - * - *

Code Sample

- * - *

List all search indexer data source connection names.

- * - * - *
-     * PagedIterable<String> dataSources = SEARCH_INDEXER_CLIENT.listDataSourceConnectionNames(new Context(KEY_1, VALUE_1));
-     * System.out.println("The status code of the response is"
-     *     + dataSources.iterableByPage().iterator().next().getStatusCode());
-     * for (String dataSourceName: dataSources) {
-     *     System.out.printf("The dataSource name is %s.%n", dataSourceName);
-     * }
-     * 
- * - * - * @param context Additional context that is passed through the HTTP pipeline during the service call. - * @return a response containing the list of DataSource names. - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - public PagedIterable listDataSourceConnectionNames(Context context) { - try { - return new PagedIterable<>(() -> MappingUtils - .mappingPagingDataSourceNames(this.listDataSourceConnectionsWithResponse("name", context))); - } catch (RuntimeException ex) { - throw LOGGER.logExceptionAsError(ex); - } - } - - /** - * Delete a DataSource - * - *

Code Sample

- * - *

Delete all search indexer data source connection named "dataSource".

- * - * - *
-     * SEARCH_INDEXER_CLIENT.deleteDataSourceConnection("dataSource");
-     * 
- * - * - * @param dataSourceConnectionName the name of the data source to be deleted - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public void deleteDataSourceConnection(String dataSourceConnectionName) { - deleteDataSourceConnectionWithResponse(new SearchIndexerDataSourceConnection(dataSourceConnectionName), false, - Context.NONE); - } - - /** - * Delete a DataSource with Response - * - *

Code Sample

- * - *

Delete all search indexer data source connection named "dataSource".

- * - * - *
-     * SearchIndexerDataSourceConnection dataSource =
-     *     SEARCH_INDEXER_CLIENT.getDataSourceConnection("dataSource");
-     * Response<Void> deleteResponse = SEARCH_INDEXER_CLIENT.deleteDataSourceConnectionWithResponse(dataSource, true,
-     *     new Context(KEY_1, VALUE_1));
-     * System.out.printf("The status code of the response is %d.%n", deleteResponse.getStatusCode());
-     * 
- * - * - * @param dataSourceConnection the {@link SearchIndexerDataSourceConnection} to be deleted. - * @param onlyIfUnchanged {@code true} to delete if the {@code dataSourceConnection} is the same as the current - * service value. {@code false} to always delete existing value. - * @param context additional context that is passed through the HTTP pipeline during the service call - * @return an empty response - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Response deleteDataSourceConnectionWithResponse(SearchIndexerDataSourceConnection dataSourceConnection, - boolean onlyIfUnchanged, Context context) { - String eTag = onlyIfUnchanged ? dataSourceConnection.getETag() : null; - return Utility.executeRestCallWithExceptionHandling(() -> restClient.getDataSources() - .deleteWithResponse(dataSourceConnection.getName(), eTag, null, null, context), LOGGER); - } - - /** - * Creates a new Azure AI Search indexer. - * - *

Code Sample

- * - *

Create search indexer named "searchIndexer".

- * - * - *
-     * SearchIndexer searchIndexer = new SearchIndexer("searchIndexer", "dataSource",
-     *     "searchIndex");
-     * SearchIndexer indexerFromService = SEARCH_INDEXER_CLIENT.createIndexer(searchIndexer);
-     * System.out.printf("The indexer name is %s. The ETag of indexer is %s.%n", indexerFromService.getName(),
-     *     indexerFromService.getETag());
-     * 
- * - * - * @param indexer definition of the indexer to create. - * @return the created Indexer. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public SearchIndexer createIndexer(SearchIndexer indexer) { - return createIndexerWithResponse(indexer, Context.NONE).getValue(); - } - - /** - * Creates a new Azure AI Search indexer. - * - *

Code Sample

- * - *

Create search indexer named "searchIndexer".

- * - * - *
-     * SearchIndexer searchIndexer = new SearchIndexer("searchIndexer", "dataSource",
-     *     "searchIndex");
-     * Response<SearchIndexer> indexerFromServiceResponse = SEARCH_INDEXER_CLIENT.createIndexerWithResponse(
-     *     searchIndexer, new Context(KEY_1, VALUE_1));
-     *
-     * System.out.printf("The status code of the response is %s. The indexer name is %s.%n",
-     *     indexerFromServiceResponse.getStatusCode(), indexerFromServiceResponse.getValue().getName());
-     * 
- * - * - * @param indexer definition of the indexer to create - * @param context additional context that is passed through the HTTP pipeline during the service call - * @return a response containing the created Indexer. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Response createIndexerWithResponse(SearchIndexer indexer, Context context) { - return Utility.executeRestCallWithExceptionHandling( - () -> restClient.getIndexers().createWithResponse(indexer, null, context), LOGGER); - } - - /** - * Creates a new Azure AI Search indexer or updates an indexer if it already exists. - * - *

Code Sample

- * - *

Create or update search indexer named "searchIndexer".

- * - * - *
-     * SearchIndexer searchIndexerFromService = SEARCH_INDEXER_CLIENT.getIndexer("searchIndexer");
-     * searchIndexerFromService.setFieldMappings(Collections.singletonList(
-     *     new FieldMapping("hotelName").setTargetFieldName("HotelName")));
-     * SearchIndexer updateIndexer = SEARCH_INDEXER_CLIENT.createOrUpdateIndexer(searchIndexerFromService);
-     * System.out.printf("The indexer name is %s. The target field name of indexer is %s.%n",
-     *     updateIndexer.getName(), updateIndexer.getFieldMappings().get(0).getTargetFieldName());
-     * 
- * - * - * @param indexer The definition of the indexer to create or update. - * @return a response containing the created Indexer. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public SearchIndexer createOrUpdateIndexer(SearchIndexer indexer) { - return createOrUpdateIndexerWithResponse(indexer, false, Context.NONE).getValue(); - } - - /** - * Creates a new Azure AI Search indexer or updates an indexer if it already exists. - * - *

Code Sample

- * - *

Create or update search indexer named "searchIndexer".

- * - * - *
-     * SearchIndexer searchIndexerFromService = SEARCH_INDEXER_CLIENT.getIndexer("searchIndexer");
-     * searchIndexerFromService.setFieldMappings(Collections.singletonList(
-     *     new FieldMapping("hotelName").setTargetFieldName("HotelName")));
-     * Response<SearchIndexer> indexerFromService = SEARCH_INDEXER_CLIENT.createOrUpdateIndexerWithResponse(
-     *     searchIndexerFromService, true, new Context(KEY_1, VALUE_1));
-     * System.out.printf("The status code of the response is %s.%nThe indexer name is %s. "
-     *     + "The target field name of indexer is %s.%n", indexerFromService.getStatusCode(),
-     *     indexerFromService.getValue().getName(),
-     *     indexerFromService.getValue().getFieldMappings().get(0).getTargetFieldName());
-     * 
- * - * - * @param indexer The {@link SearchIndexer} to create or update. - * @param onlyIfUnchanged {@code true} to update if the {@code indexer} is the same as the current service value. - * {@code false} to always update existing value. - * @param context additional context that is passed through the HTTP pipeline during the service call - * @return A response object containing the Indexer. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Response createOrUpdateIndexerWithResponse(SearchIndexer indexer, boolean onlyIfUnchanged, - Context context) { - return createOrUpdateIndexerWithResponse(indexer, onlyIfUnchanged, null, null, context); - } - - Response createOrUpdateIndexerWithResponse(SearchIndexer indexer, boolean onlyIfUnchanged, - Boolean disableCacheReprocessingChangeDetection, Boolean ignoreResetRequirements, Context context) { - if (indexer == null) { - throw LOGGER.logExceptionAsError(new NullPointerException("'indexer' cannot be null.")); - } - String ifMatch = onlyIfUnchanged ? indexer.getETag() : null; - return Utility.executeRestCallWithExceptionHandling(() -> restClient.getIndexers() - .createOrUpdateWithResponse(indexer.getName(), indexer, ifMatch, null, ignoreResetRequirements, - disableCacheReprocessingChangeDetection, null, context), - LOGGER); - - } - - /** - * Lists all indexers available for an Azure AI Search service. - * - *

Code Sample

- * - *

List all search indexers.

- * - * - *
-     * PagedIterable<SearchIndexer> indexers = SEARCH_INDEXER_CLIENT.listIndexers();
-     * for (SearchIndexer indexer: indexers) {
-     *     System.out.printf("The indexer name is %s. The ETag of indexer is %s.%n", indexer.getName(),
-     *         indexer.getETag());
-     * }
-     * 
- * - * - * @return all Indexers from the Search service. - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - public PagedIterable listIndexers() { - return listIndexers(Context.NONE); - } - - /** - * Lists all indexers available for an Azure AI Search service. - * - *

Code Sample

- * - *

List all search indexers.

- * - * - *
-     * PagedIterable<SearchIndexer> indexers = SEARCH_INDEXER_CLIENT.listIndexers(new Context(KEY_1, VALUE_1));
-     * System.out.println("The status code of the response is"
-     *     + indexers.iterableByPage().iterator().next().getStatusCode());
-     * for (SearchIndexer indexer: indexers) {
-     *     System.out.printf("The indexer name is %s. The ETag of index is %s.%n",
-     *         indexer.getName(), indexer.getETag());
-     * }
-     * 
- * - * - * @param context additional context that is passed through the HTTP pipeline during the service call - * @return all Indexers from the Search service. - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - public PagedIterable listIndexers(Context context) { - try { - return new PagedIterable<>( - () -> MappingUtils.mappingPagingSearchIndexer(listIndexersWithResponse(null, context))); - } catch (RuntimeException ex) { - throw LOGGER.logExceptionAsError(ex); - } - } - - private Response listIndexersWithResponse(String select, Context context) { - return Utility.executeRestCallWithExceptionHandling( - () -> restClient.getIndexers().listWithResponse(select, null, context), LOGGER); - } - - /** - * Lists all indexers names for an Azure AI Search service. - * - *

Code Sample

- * - *

List all search indexer names.

- * - * - *
-     * PagedIterable<String> indexers = SEARCH_INDEXER_CLIENT.listIndexerNames();
-     * for (String indexerName: indexers) {
-     *     System.out.printf("The indexer name is %s.%n", indexerName);
-     * }
-     * 
- * - * - * @return all Indexer names from the Search service . - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - public PagedIterable listIndexerNames() { - return listIndexerNames(Context.NONE); - } - - /** - * Lists all indexers names for an Azure AI Search service. - * - *

Code Sample

- * - *

List all search indexer names.

- * - * - *
-     * PagedIterable<String> indexers = SEARCH_INDEXER_CLIENT.listIndexerNames(new Context(KEY_1, VALUE_1));
-     * System.out.println("The status code of the response is"
-     *     + indexers.iterableByPage().iterator().next().getStatusCode());
-     * for (String indexerName: indexers) {
-     *     System.out.printf("The indexer name is %s.%n", indexerName);
-     * }
-     * 
- * - * - * @param context additional context that is passed through the HTTP pipeline during the service call - * @return all Indexer names from the Search service. - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - public PagedIterable listIndexerNames(Context context) { - try { - return new PagedIterable<>( - () -> MappingUtils.mappingPagingSearchIndexerNames(this.listIndexersWithResponse("name", context))); - } catch (RuntimeException ex) { - throw LOGGER.logExceptionAsError(ex); - } - } - - /** - * Retrieves an indexer definition. - * - *

Code Sample

- * - *

Get search indexer with name "searchIndexer".

- * - * - *
-     * SearchIndexer indexerFromService =
-     *     SEARCH_INDEXER_CLIENT.getIndexer("searchIndexer");
-     * System.out.printf("The indexer name is %s. The ETag of indexer is %s.%n", indexerFromService.getName(),
-     *     indexerFromService.getETag());
-     * 
- * - * - * @param indexerName the name of the indexer to retrieve - * @return the indexer. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public SearchIndexer getIndexer(String indexerName) { - return getIndexerWithResponse(indexerName, Context.NONE).getValue(); - } - - /** - * Retrieves an indexer definition. - * - *

Code Sample

- * - *

Get search indexer with name "searchIndexer".

- * - * - *
-     * Response<SearchIndexer> indexerFromServiceResponse = SEARCH_INDEXER_CLIENT.getIndexerWithResponse(
-     *     "searchIndexer", new Context(KEY_1, VALUE_1));
-     *
-     * System.out.printf("The status code of the response is %s. The indexer name is %s.%n",
-     *     indexerFromServiceResponse.getStatusCode(), indexerFromServiceResponse.getValue().getName());
-     * 
- * - * - * @param indexerName the name of the indexer to retrieve - * @param context additional context that is passed through the HTTP pipeline during the service call - * @return a response containing the indexer. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Response getIndexerWithResponse(String indexerName, Context context) { - return Utility.executeRestCallWithExceptionHandling( - () -> restClient.getIndexers().getWithResponse(indexerName, null, context), LOGGER); - } - - /** - * Deletes an Azure AI Search indexer. - * - *

Code Sample

- * - *

Delete search indexer named "searchIndexer".

- * - * - *
-     * SEARCH_INDEXER_CLIENT.deleteIndexer("searchIndexer");
-     * 
- * - * - * @param indexerName the name of the indexer to delete - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public void deleteIndexer(String indexerName) { - deleteIndexerWithResponse(new SearchIndexer(indexerName), false, Context.NONE); - } - - /** - * Deletes an Azure AI Search indexer. - * - *

Code Sample

- * - *

Delete search index named "searchIndexer".

- * - * - *
-     * SearchIndexer searchIndexer = SEARCH_INDEXER_CLIENT.getIndexer("searchIndexer");
-     * Response<Void> deleteResponse = SEARCH_INDEXER_CLIENT.deleteIndexerWithResponse(searchIndexer, true,
-     *     new Context(KEY_1, VALUE_1));
-     * System.out.printf("The status code of the response is %d.%n", deleteResponse.getStatusCode());
-     * 
- * - * - * @param indexer the search {@link SearchIndexer} - * @param onlyIfUnchanged {@code true} to delete if the {@code indexer} is the same as the current service value. - * {@code false} to always delete existing value. - * @param context the context - * @return a response signalling completion. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Response deleteIndexerWithResponse(SearchIndexer indexer, boolean onlyIfUnchanged, Context context) { - String eTag = onlyIfUnchanged ? indexer.getETag() : null; - return Utility.executeRestCallWithExceptionHandling( - () -> restClient.getIndexers().deleteWithResponse(indexer.getName(), eTag, null, null, context), LOGGER); - } - - /** - * Resets the change tracking state associated with an indexer. - * - *

Code Sample

- * - *

Reset search indexer named "searchIndexer".

- * - * - *
-     * SEARCH_INDEXER_CLIENT.resetIndexer("searchIndexer");
-     * 
- * - * - * @param indexerName the name of the indexer to reset - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public void resetIndexer(String indexerName) { - resetIndexerWithResponse(indexerName, Context.NONE); - } - - /** - * Resets the change tracking state associated with an indexer. - * - *

Code Sample

- * - *

Reset search indexer named "searchIndexer".

- * - * - *
-     * Response<Void> response = SEARCH_INDEXER_CLIENT.resetIndexerWithResponse("searchIndexer",
-     *     new Context(KEY_1, VALUE_1));
-     * System.out.println("The status code of the response is " + response.getStatusCode());
-     * 
- * - * - * @param indexerName the name of the indexer to reset - * @param context additional context that is passed through the HTTP pipeline during the service call - * @return a response signalling completion. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Response resetIndexerWithResponse(String indexerName, Context context) { - return Utility.executeRestCallWithExceptionHandling( - () -> restClient.getIndexers().resetWithResponse(indexerName, null, context), LOGGER); - } - - /** - * Runs an indexer on-demand. - * - *

Code Sample

- * - *

Run search indexer named "searchIndexer".

- * - * - *
-     * SEARCH_INDEXER_CLIENT.runIndexer("searchIndexer");
-     * 
- * - * - * @param indexerName the name of the indexer to run - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public void runIndexer(String indexerName) { - runIndexerWithResponse(indexerName, Context.NONE); - } - - /** - * Runs an indexer on-demand. - * - *

Code Sample

- * - *

Run search indexer named "searchIndexer".

- * - * - *
-     * Response<Void> response = SEARCH_INDEXER_CLIENT.runIndexerWithResponse("searchIndexer",
-     *     new Context(KEY_1, VALUE_1));
-     * System.out.println("The status code of the response is " + response.getStatusCode());
-     * 
- * - * - * @param indexerName the name of the indexer to run - * @param context additional context that is passed through the HTTP pipeline during the service call - * @return a response signalling completion. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Response runIndexerWithResponse(String indexerName, Context context) { - return Utility.executeRestCallWithExceptionHandling( - () -> restClient.getIndexers().runWithResponse(indexerName, null, context), LOGGER); - } - - /** - * Returns the current status and execution history of an indexer. - * - *

Code Sample

- * - *

Get search indexer status.

- * - * - *
-     * SearchIndexerStatus indexerStatus = SEARCH_INDEXER_CLIENT.getIndexerStatus("searchIndexer");
-     * System.out.printf("The indexer status is %s.%n", indexerStatus.getStatus());
-     * 
- * - * - * @param indexerName the name of the indexer for which to retrieve status - * @return a response with the indexer execution info. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public SearchIndexerStatus getIndexerStatus(String indexerName) { - return getIndexerStatusWithResponse(indexerName, Context.NONE).getValue(); - } - - /** - * Returns the current status and execution history of an indexer. - * - *

Code Sample

- * - *

Get search indexer status.

- * - * - *
-     * Response<SearchIndexerStatus> response = SEARCH_INDEXER_CLIENT.getIndexerStatusWithResponse("searchIndexer",
-     *     new Context(KEY_1, VALUE_1));
-     * System.out.printf("The status code of the response is %s.%nThe indexer status is %s.%n",
-     *     response.getStatusCode(), response.getValue().getStatus());
-     * 
- * - * - * @param indexerName the name of the indexer for which to retrieve status - * @param context additional context that is passed through the HTTP pipeline during the service call - * @return a response with the indexer execution info. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Response getIndexerStatusWithResponse(String indexerName, Context context) { - return Utility.executeRestCallWithExceptionHandling( - () -> restClient.getIndexers().getStatusWithResponse(indexerName, null, context), LOGGER); - } - - /** - * Creates a new skillset in an Azure AI Search service. - * - *

Code Sample

- * - *

Create search indexer skillset "searchIndexerSkillset".

- * - * - *
-     * List<InputFieldMappingEntry> inputs = Collections.singletonList(
-     *     new InputFieldMappingEntry("image")
-     *         .setSource("/document/normalized_images/*")
-     * );
-     *
-     * List<OutputFieldMappingEntry> outputs = Arrays.asList(
-     *     new OutputFieldMappingEntry("text")
-     *         .setTargetName("mytext"),
-     *     new OutputFieldMappingEntry("layoutText")
-     *         .setTargetName("myLayoutText")
-     * );
-     * SearchIndexerSkillset searchIndexerSkillset = new SearchIndexerSkillset("searchIndexerSkillset",
-     *     Collections.singletonList(new OcrSkill(inputs, outputs)
-     *         .setShouldDetectOrientation(true)
-     *         .setDefaultLanguageCode(null)
-     *         .setName("myocr")
-     *         .setDescription("Extracts text (plain and structured) from image.")
-     *         .setContext("/document/normalized_images/*")));
-     * SearchIndexerSkillset skillset = SEARCH_INDEXER_CLIENT.createSkillset(searchIndexerSkillset);
-     * System.out.printf("The indexer skillset name is %s. The ETag of indexer skillset is %s.%n",
-     *     skillset.getName(), skillset.getETag());
-     * 
- * - * - * @param skillset definition of the skillset containing one or more cognitive skills - * @return the created SearchIndexerSkillset. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public SearchIndexerSkillset createSkillset(SearchIndexerSkillset skillset) { - return createSkillsetWithResponse(skillset, Context.NONE).getValue(); - } - - /** - * Creates a new skillset in an Azure AI Search service. - * - *

Code Sample

- * - *

Create search indexer skillset "searchIndexerSkillset".

- * - * - *
-     * List<InputFieldMappingEntry> inputs = Collections.singletonList(
-     *     new InputFieldMappingEntry("image")
-     *         .setSource("/document/normalized_images/*")
-     * );
-     *
-     * List<OutputFieldMappingEntry> outputs = Arrays.asList(
-     *     new OutputFieldMappingEntry("text")
-     *         .setTargetName("mytext"),
-     *     new OutputFieldMappingEntry("layoutText")
-     *         .setTargetName("myLayoutText")
-     * );
-     * SearchIndexerSkillset searchIndexerSkillset = new SearchIndexerSkillset("searchIndexerSkillset",
-     *     Collections.singletonList(new OcrSkill(inputs, outputs)
-     *         .setShouldDetectOrientation(true)
-     *         .setDefaultLanguageCode(null)
-     *         .setName("myocr")
-     *         .setDescription("Extracts text (plain and structured) from image.")
-     *         .setContext("/document/normalized_images/*")));
-     * Response<SearchIndexerSkillset> skillsetWithResponse =
-     *     SEARCH_INDEXER_CLIENT.createSkillsetWithResponse(searchIndexerSkillset, new Context(KEY_1, VALUE_1));
-     * System.out.printf("The status code of the response is %s. The indexer skillset name is %s.%n",
-     *     skillsetWithResponse.getStatusCode(), skillsetWithResponse.getValue().getName());
-     * 
- * - * - * @param skillset definition of the skillset containing one or more cognitive skills - * @param context additional context that is passed through the HTTP pipeline during the service call - * @return a response containing the created SearchIndexerSkillset. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Response createSkillsetWithResponse(SearchIndexerSkillset skillset, Context context) { - if (skillset == null) { - throw LOGGER.logExceptionAsError(new NullPointerException("'skillset' cannot be null.")); - } - return Utility.executeRestCallWithExceptionHandling( - () -> restClient.getSkillsets().createWithResponse(skillset, null, context), LOGGER); - } - - /** - * Retrieves a skillset definition. - * - *

Code Sample

- * - *

Get search indexer skillset "searchIndexerSkillset".

- * - * - *
-     * SearchIndexerSkillset indexerSkillset =
-     *     SEARCH_INDEXER_CLIENT.getSkillset("searchIndexerSkillset");
-     * System.out.printf("The indexer skillset name is %s. The ETag of indexer skillset is %s.%n",
-     *     indexerSkillset.getName(), indexerSkillset.getETag());
-     * 
- * - * - * @param skillsetName the name of the skillset to retrieve - * @return the SearchIndexerSkillset. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public SearchIndexerSkillset getSkillset(String skillsetName) { - return getSkillsetWithResponse(skillsetName, Context.NONE).getValue(); - } - - /** - * Retrieves a skillset definition. - * - *

Code Sample

- * - *

Get search indexer skillset "searchIndexerSkillset".

- * - * - *
-     * Response<SearchIndexerSkillset> skillsetWithResponse = SEARCH_INDEXER_CLIENT.getSkillsetWithResponse(
-     *     "searchIndexerSkillset", new Context(KEY_1, VALUE_1));
-     *
-     * System.out.printf("The status code of the response is %s. The indexer skillset name is %s.%n",
-     *     skillsetWithResponse.getStatusCode(), skillsetWithResponse.getValue().getName());
-     * 
- * - * - * @param skillsetName the name of the skillset to retrieve - * @param context additional context that is passed through the HTTP pipeline during the service call - * @return a response containing the SearchIndexerSkillset. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Response getSkillsetWithResponse(String skillsetName, Context context) { - return Utility.executeRestCallWithExceptionHandling( - () -> restClient.getSkillsets().getWithResponse(skillsetName, null, context), LOGGER); - } - - /** - * Lists all skillsets available for an Azure AI Search service. - * - *

Code Sample

- * - *

List all search indexer skillsets.

- * - * - *
-     * PagedIterable<SearchIndexerSkillset> indexerSkillsets = SEARCH_INDEXER_CLIENT.listSkillsets();
-     * for (SearchIndexerSkillset skillset: indexerSkillsets) {
-     *     System.out.printf("The skillset name is %s. The ETag of skillset is %s.%n", skillset.getName(),
-     *         skillset.getETag());
-     * }
-     * 
- * - * - * @return the list of skillsets. - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - public PagedIterable listSkillsets() { - return listSkillsets(Context.NONE); - } - - /** - * Lists all skillsets available for an Azure AI Search service. - * - *

Code Sample

- * - *

List all search indexer skillsets.

- * - * - *
-     * PagedIterable<SearchIndexerSkillset> indexerSkillsets = SEARCH_INDEXER_CLIENT
-     *     .listSkillsets(new Context(KEY_1, VALUE_1));
-     * System.out.println("The status code of the response is"
-     *     + indexerSkillsets.iterableByPage().iterator().next().getStatusCode());
-     * for (SearchIndexerSkillset skillset: indexerSkillsets) {
-     *     System.out.printf("The skillset name is %s. The ETag of skillset is %s.%n",
-     *         skillset.getName(), skillset.getETag());
-     * }
-     * 
- * - * - * @param context additional context that is passed through the HTTP pipeline during the service call - * @return the list of skillsets. - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - public PagedIterable listSkillsets(Context context) { - try { - return new PagedIterable<>( - () -> MappingUtils.mappingPagingSkillset(listSkillsetsWithResponse(null, context))); - } catch (RuntimeException ex) { - throw LOGGER.logExceptionAsError(ex); - } - } - - private Response listSkillsetsWithResponse(String select, Context context) { - return Utility.executeRestCallWithExceptionHandling( - () -> this.restClient.getSkillsets().listWithResponse(select, null, context), LOGGER); - } - - /** - * Lists all skillset names for an Azure AI Search service. - * - *

Code Sample

- * - *

List all search indexer skillset names.

- * - * - *
-     * PagedIterable<String> skillsetNames = SEARCH_INDEXER_CLIENT.listSkillsetNames();
-     * for (String skillsetName: skillsetNames) {
-     *     System.out.printf("The indexer skillset name is %s.%n", skillsetName);
-     * }
-     * 
- * - * - * @return the list of skillset names. - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - public PagedIterable listSkillsetNames() { - return listSkillsetNames(Context.NONE); - } - - /** - * Lists all skillset names for an Azure AI Search service. - * - *

Code Sample

- * - *

List all search indexer skillset names with response.

- * - * - *
-     * PagedIterable<String> skillsetNames = SEARCH_INDEXER_CLIENT.listSkillsetNames(new Context(KEY_1, VALUE_1));
-     * System.out.println("The status code of the response is"
-     *     + skillsetNames.iterableByPage().iterator().next().getStatusCode());
-     * for (String skillsetName: skillsetNames) {
-     *     System.out.printf("The indexer skillset name is %s.%n", skillsetName);
-     * }
-     * 
- * - * - * @param context additional context that is passed through the HTTP pipeline during the service call - * @return the list of skillset names. - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - public PagedIterable listSkillsetNames(Context context) { - try { - return new PagedIterable<>( - () -> MappingUtils.mappingPagingSkillsetNames(listSkillsetsWithResponse("name", context))); - } catch (RuntimeException ex) { - throw LOGGER.logExceptionAsError(ex); - } - } - - /** - * Creates a new Azure AI Search skillset or updates a skillset if it already exists. - * - *

Code Sample

- * - *

Create or update search indexer skillset "searchIndexerSkillset".

- * - * - *
-     * SearchIndexerSkillset indexerSkillset = SEARCH_INDEXER_CLIENT.getSkillset("searchIndexerSkillset");
-     * indexerSkillset.setDescription("This is new description!");
-     * SearchIndexerSkillset updateSkillset = SEARCH_INDEXER_CLIENT.createOrUpdateSkillset(indexerSkillset);
-     * System.out.printf("The indexer skillset name is %s. The description of indexer skillset is %s.%n",
-     *     updateSkillset.getName(), updateSkillset.getDescription());
-     * 
- * - * - * @param skillset the {@link SearchIndexerSkillset} to create or update. - * @return the skillset that was created or updated. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public SearchIndexerSkillset createOrUpdateSkillset(SearchIndexerSkillset skillset) { - return createOrUpdateSkillsetWithResponse(skillset, false, Context.NONE).getValue(); - } - - /** - * Creates a new Azure AI Search skillset or updates a skillset if it already exists. - * - *

Code Sample

- * - *

Create or update search indexer skillset "searchIndexerSkillset".

- * - * - *
-     * SearchIndexerSkillset indexerSkillset = SEARCH_INDEXER_CLIENT.getSkillset("searchIndexerSkillset");
-     * indexerSkillset.setDescription("This is new description!");
-     * Response<SearchIndexerSkillset> updateSkillsetResponse = SEARCH_INDEXER_CLIENT.createOrUpdateSkillsetWithResponse(
-     *     indexerSkillset, true, new Context(KEY_1, VALUE_1));
-     * System.out.printf("The status code of the response is %s.%nThe indexer skillset name is %s. "
-     *         + "The description of indexer skillset is %s.%n", updateSkillsetResponse.getStatusCode(),
-     *     updateSkillsetResponse.getValue().getName(),
-     *     updateSkillsetResponse.getValue().getDescription());
-     * 
- * - * - * @param skillset the {@link SearchIndexerSkillset} to create or update. - * @param onlyIfUnchanged {@code true} to update if the {@code skillset} is the same as the current service value. - * {@code false} to always update existing value. - * @param context additional context that is passed through the HTTP pipeline during the service call - * @return a response containing the skillset that was created or updated. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Response createOrUpdateSkillsetWithResponse(SearchIndexerSkillset skillset, - boolean onlyIfUnchanged, Context context) { - return createOrUpdateSkillsetWithResponse(skillset, onlyIfUnchanged, null, null, context); - } - - Response createOrUpdateSkillsetWithResponse(SearchIndexerSkillset skillset, - boolean onlyIfUnchanged, Boolean disableCacheReprocessingChangeDetection, Boolean ignoreResetRequirements, - Context context) { - if (skillset == null) { - throw LOGGER.logExceptionAsError(new NullPointerException("'skillset' cannot be null.")); - } - String ifMatch = onlyIfUnchanged ? skillset.getETag() : null; - return Utility.executeRestCallWithExceptionHandling(() -> restClient.getSkillsets() - .createOrUpdateWithResponse(skillset.getName(), skillset, ifMatch, null, ignoreResetRequirements, - disableCacheReprocessingChangeDetection, null, context), - LOGGER); - } - - /** - * Deletes a cognitive skillset in an Azure AI Search service. - * - *

Code Sample

- * - *

Delete search indexer skillset "searchIndexerSkillset".

- * - * - *
-     * SEARCH_INDEXER_CLIENT.deleteSkillset("searchIndexerSkillset");
-     * 
- * - * - * @param skillsetName the name of the skillset to delete - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public void deleteSkillset(String skillsetName) { - deleteSkillsetWithResponse(new SearchIndexerSkillset(skillsetName), false, Context.NONE); - } - - /** - * Deletes a cognitive skillset in an Azure AI Search service. - * - *

Code Sample

- * - *

Delete search indexer skillset "searchIndexerSkillset".

- * - * - *
-     * SearchIndexerSkillset searchIndexerSkillset = SEARCH_INDEXER_CLIENT.getSkillset("searchIndexerSkillset");
-     * Response<Void> deleteResponse = SEARCH_INDEXER_CLIENT.deleteSkillsetWithResponse(searchIndexerSkillset, true,
-     *     new Context(KEY_1, VALUE_1));
-     * System.out.printf("The status code of the response is %d.%n", deleteResponse.getStatusCode());
-     * 
- * - * - * @param skillset the {@link SearchIndexerSkillset} to delete. - * @param onlyIfUnchanged {@code true} to delete if the {@code skillset} is the same as the current service value. - * {@code false} to always delete existing value. - * @param context additional context that is passed through the HTTP pipeline during the service call - * @return a response signalling completion. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Response deleteSkillsetWithResponse(SearchIndexerSkillset skillset, boolean onlyIfUnchanged, - Context context) { - String eTag = onlyIfUnchanged ? skillset.getETag() : null; - return Utility.executeRestCallWithExceptionHandling( - () -> restClient.getSkillsets().deleteWithResponse(skillset.getName(), eTag, null, null, context), LOGGER); - } -} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/SearchIndexerClientBuilder.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/SearchIndexerClientBuilder.java deleted file mode 100644 index de6cfec11a34..000000000000 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/SearchIndexerClientBuilder.java +++ /dev/null @@ -1,517 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.search.documents.indexes; - -import com.azure.core.annotation.ServiceClientBuilder; -import com.azure.core.client.traits.AzureKeyCredentialTrait; -import com.azure.core.client.traits.ConfigurationTrait; -import com.azure.core.client.traits.EndpointTrait; -import com.azure.core.client.traits.HttpTrait; -import com.azure.core.client.traits.TokenCredentialTrait; -import com.azure.core.credential.AzureKeyCredential; -import com.azure.core.credential.TokenCredential; -import com.azure.core.http.HttpClient; -import com.azure.core.http.HttpPipeline; -import com.azure.core.http.HttpPipelinePosition; -import com.azure.core.http.policy.HttpLogDetailLevel; -import com.azure.core.http.policy.HttpLogOptions; -import com.azure.core.http.policy.HttpPipelinePolicy; -import com.azure.core.http.policy.RetryOptions; -import com.azure.core.http.policy.RetryPolicy; -import com.azure.core.util.ClientOptions; -import com.azure.core.util.Configuration; -import com.azure.core.util.HttpClientOptions; -import com.azure.core.util.logging.ClientLogger; -import com.azure.search.documents.models.SearchAudience; -import com.azure.search.documents.SearchServiceVersion; -import com.azure.search.documents.implementation.util.Constants; -import com.azure.search.documents.implementation.util.Utility; - -import java.net.MalformedURLException; -import java.net.URL; -import java.util.ArrayList; -import java.util.List; -import java.util.Objects; - -/** - * This class provides a fluent builder API to help aid the configuration and instantiation of {@link - * SearchIndexerClient SearchIndexerClients} and {@link SearchIndexerAsyncClient SearchIndexerAsyncClients}. - * - *

- * Overview - *

- * - *

- * This client allows you to create instances of {@link SearchIndexerClient} and {@link SearchIndexerAsyncClient} to - * utilize synchronous and asynchronous APIs respectively to interact with Azure AI Search. - *

- * - *

- * Getting Started - *

- * - *

- * Authentication - *

- * - *

- * Azure AI Search supports - * Microsoft Entra ID (role-based) authentication and API keys for authentication. - *

- * - *

- * For more information about the scopes of authorization, see the Azure AI Search Security Overview documentation. - *

- * - *

- * Building and Authenticating a {@link SearchIndexerClient} or {@link SearchIndexerAsyncClient} using API keys - *

- * - *

- * To build an instance of {@link SearchIndexerClient} or {@link SearchIndexerAsyncClient} using API keys, call - * {@link #buildClient() buildClient} and {@link #buildAsyncClient() buildAsyncClient} respectively from the - * {@link SearchIndexerClientBuilder}. - *

- * - *

- * The following must be provided to construct a client instance: - *

- * - *
    - *
  • The Azure AI Search service URL.
  • - *
  • An {@link AzureKeyCredential API Key} that grants access to the Azure AI Search service.
  • - *
- * - *

Instantiating a synchronous Search Indexer Client

- * - * - *
- * SearchIndexerClient searchIndexerClient = new SearchIndexerClientBuilder()
- *     .credential(new AzureKeyCredential("{key}"))
- *     .endpoint("{endpoint}")
- *     .buildClient();
- * 
- * - * - *

Instantiating an asynchronous Search Indexer Client

- * - * - *
- * SearchIndexerAsyncClient searchIndexerAsyncClient = new SearchIndexerClientBuilder()
- *     .credential(new AzureKeyCredential("{key}"))
- *     .endpoint("{endpoint}")
- *     .buildAsyncClient();
- * 
- * - * - *

- * Building and Authenticating a {@link SearchIndexerClient} or {@link SearchIndexerAsyncClient} using Microsoft Entra ID - *

- * - *

- * You can also create a {@link SearchIndexerClient} or {@link SearchIndexerAsyncClient} using Microsoft Entra ID - * authentication. Your user or service principal must be assigned the "Search Index Data Reader" role. Using the - * DefaultAzureCredential you can authenticate a service using Managed Identity or a service principal, authenticate - * as a developer working on an application, and more all without changing code. Please refer the documentation for - * instructions on how to connect to Azure AI Search using Azure role-based access control (Azure RBAC). - *

- * - *

- * Before you can use the `DefaultAzureCredential`, or any credential type from Azure.Identity, you'll first need to install the Azure.Identity package. - *

- * - *

- * To use DefaultAzureCredential with a client ID and secret, you'll need to set the `AZURE_TENANT_ID`, `AZURE_CLIENT_ID`, - * and `AZURE_CLIENT_SECRET` environment variables; alternatively, you can pass those values to the - * `ClientSecretCredential` also in azure-identity. - *

- * - *

- * Make sure you use the right namespace for DefaultAzureCredential at the top of your source file: - *

- * - * - *
- * import com.azure.identity.DefaultAzureCredential;
- * import com.azure.identity.DefaultAzureCredentialBuilder;
- * 
- * - * - *

- * Then you can create an instance of DefaultAzureCredential and pass it to a new instance of your client: - *

- * - *

Instantiating a synchronous Search Indexer Client

- * - * - *
- * DefaultAzureCredential credential = new DefaultAzureCredentialBuilder().build();
- *
- * SearchIndexerClient searchIndexerClient = new SearchIndexerClientBuilder()
- *     .endpoint("{endpoint}")
- *     .credential(credential)
- *     .buildClient();
- * 
- * - * - *

Instantiating an asynchronous Search Indexer Client

- * - * - *
- * DefaultAzureCredential credential = new DefaultAzureCredentialBuilder().build();
- *
- * SearchIndexerAsyncClient searchIndexerAsyncClient = new SearchIndexerClientBuilder()
- *     .endpoint("{endpoint}")
- *     .credential(credential)
- *     .buildAsyncClient();
- * 
- * - * - * @see SearchIndexerClient - * @see SearchIndexerAsyncClient - * @see com.azure.search.documents.indexes - */ -@ServiceClientBuilder(serviceClients = { SearchIndexerClient.class, SearchIndexerAsyncClient.class }) -public class SearchIndexerClientBuilder implements AzureKeyCredentialTrait, - ConfigurationTrait, EndpointTrait, - HttpTrait, TokenCredentialTrait { - private static final ClientLogger LOGGER = new ClientLogger(SearchIndexerClientBuilder.class); - - private final List perCallPolicies = new ArrayList<>(); - private final List perRetryPolicies = new ArrayList<>(); - - private AzureKeyCredential azureKeyCredential; - private TokenCredential tokenCredential; - private SearchAudience audience; - - private SearchServiceVersion serviceVersion; - private String endpoint; - private HttpClient httpClient; - private HttpPipeline httpPipeline; - private ClientOptions clientOptions; - private HttpLogOptions httpLogOptions; - private Configuration configuration; - private RetryPolicy retryPolicy; - private RetryOptions retryOptions; - - /** - * Creates a builder instance that is able to configure and construct {@link SearchIndexerClient - * SearchIndexerClients} and {@link SearchIndexerAsyncClient SearchIndexerAsyncClients}. - */ - public SearchIndexerClientBuilder() { - } - - /** - * Creates a {@link SearchIndexerClient} based on options set in the Builder. Every time {@code buildClient()} is - * called a new instance of {@link SearchIndexerClient} is created. - *

- * If {@link #pipeline(HttpPipeline) pipeline} is set, then only the {@code pipeline} and {@link #endpoint(String) - * endpoint} are used to create the {@link SearchIndexerClient client}. All other builder settings are ignored. - * - * @return A SearchIndexerClient with the options set from the builder. - * @throws NullPointerException If {@code endpoint} are {@code null}. - * @throws IllegalStateException If both {@link #retryOptions(RetryOptions)} - * and {@link #retryPolicy(RetryPolicy)} have been set. - */ - public SearchIndexerClient buildClient() { - Objects.requireNonNull(endpoint, "'endpoint' cannot be null."); - - SearchServiceVersion buildVersion - = (serviceVersion == null) ? SearchServiceVersion.getLatest() : serviceVersion; - - if (httpPipeline != null) { - return new SearchIndexerClient(endpoint, buildVersion, httpPipeline); - } - - HttpPipeline pipeline - = Utility.buildHttpPipeline(clientOptions, httpLogOptions, configuration, retryPolicy, retryOptions, - azureKeyCredential, tokenCredential, audience, perCallPolicies, perRetryPolicies, httpClient, LOGGER); - - return new SearchIndexerClient(endpoint, buildVersion, pipeline); - } - - /** - * Creates a {@link SearchIndexerAsyncClient} based on options set in the Builder. Every time {@code - * buildAsyncClient()} is called a new instance of {@link SearchIndexerAsyncClient} is created. - *

- * If {@link #pipeline(HttpPipeline) pipeline} is set, then only the {@code pipeline} and {@link #endpoint(String) - * endpoint} are used to create the {@link SearchIndexerAsyncClient client}. All other builder settings are - * ignored. - * - * @return A SearchIndexerAsyncClient with the options set from the builder. - * @throws NullPointerException If {@code endpoint} are {@code null}. - * @throws IllegalStateException If both {@link #retryOptions(RetryOptions)} - * and {@link #retryPolicy(RetryPolicy)} have been set. - */ - public SearchIndexerAsyncClient buildAsyncClient() { - Objects.requireNonNull(endpoint, "'endpoint' cannot be null."); - - SearchServiceVersion buildVersion - = (serviceVersion == null) ? SearchServiceVersion.getLatest() : serviceVersion; - - if (httpPipeline != null) { - return new SearchIndexerAsyncClient(endpoint, buildVersion, httpPipeline); - } - - HttpPipeline pipeline - = Utility.buildHttpPipeline(clientOptions, httpLogOptions, configuration, retryPolicy, retryOptions, - azureKeyCredential, tokenCredential, audience, perCallPolicies, perRetryPolicies, httpClient, LOGGER); - - return new SearchIndexerAsyncClient(endpoint, buildVersion, pipeline); - } - - /** - * Sets the service endpoint for the Azure AI Search instance. - * - * @param endpoint The URL of the Azure AI Search instance. - * @return The updated SearchIndexerClientBuilder object. - * @throws IllegalArgumentException If {@code endpoint} is null or it cannot be parsed into a valid URL. - */ - @Override - public SearchIndexerClientBuilder endpoint(String endpoint) { - try { - new URL(endpoint); - } catch (MalformedURLException ex) { - throw LOGGER.logExceptionAsWarning(new IllegalArgumentException("'endpoint' must be a valid URL", ex)); - } - this.endpoint = endpoint; - return this; - } - - /** - * Sets the {@link AzureKeyCredential} used to authenticate HTTP requests. - * - * @param credential The {@link AzureKeyCredential} used to authenticate HTTP requests. - * @return The updated SearchIndexerClientBuilder object. - */ - @Override - public SearchIndexerClientBuilder credential(AzureKeyCredential credential) { - this.azureKeyCredential = credential; - return this; - } - - /** - * Sets the {@link TokenCredential} used to authorize requests sent to the service. Refer to the Azure SDK for Java - * identity and authentication - * documentation for more details on proper usage of the {@link TokenCredential} type. - * - * @param credential {@link TokenCredential} used to authorize requests sent to the service. - * @return The updated SearchIndexerClientBuilder object. - */ - @Override - public SearchIndexerClientBuilder credential(TokenCredential credential) { - this.tokenCredential = credential; - return this; - } - - /** - * Sets the Audience to use for authentication with Microsoft Entra ID. - *

- * The audience is not considered when using a {@link #credential(AzureKeyCredential) shared key}. - *

- * If {@code audience} is null the public cloud audience will be assumed. - * - * @param audience The Audience to use for authentication with Microsoft Entra ID. - * @return The updated SearchClientBuilder object. - */ - public SearchIndexerClientBuilder audience(SearchAudience audience) { - this.audience = audience; - return this; - } - - /** - * Sets the {@link HttpLogOptions logging configuration} to use when sending and receiving requests to and from - * the service. If a {@code logLevel} is not provided, default value of {@link HttpLogDetailLevel#NONE} is set. - * - *

Note: It is important to understand the precedence order of the HttpTrait APIs. In - * particular, if a {@link HttpPipeline} is specified, this takes precedence over all other APIs in the trait, and - * they will be ignored. If no {@link HttpPipeline} is specified, a HTTP pipeline will be constructed internally - * based on the settings provided to this trait. Additionally, there may be other APIs in types that implement this - * trait that are also ignored if an {@link HttpPipeline} is specified, so please be sure to refer to the - * documentation of types that implement this trait to understand the full set of implications.

- * - * @param logOptions The {@link HttpLogOptions logging configuration} to use when sending and receiving requests to - * and from the service. - * @return The updated SearchIndexerClientBuilder object. - */ - @Override - public SearchIndexerClientBuilder httpLogOptions(HttpLogOptions logOptions) { - httpLogOptions = logOptions; - return this; - } - - /** - * Gets the default Azure Search headers and query parameters allow list. - * - * @return The default {@link HttpLogOptions} allow list. - */ - public static HttpLogOptions getDefaultLogOptions() { - return Constants.DEFAULT_LOG_OPTIONS_SUPPLIER.get(); - } - - /** - * Allows for setting common properties such as application ID, headers, proxy configuration, etc. Note that it is - * recommended that this method be called with an instance of the {@link HttpClientOptions} - * class (a subclass of the {@link ClientOptions} base class). The HttpClientOptions subclass provides more - * configuration options suitable for HTTP clients, which is applicable for any class that implements this HttpTrait - * interface. - * - *

Note: It is important to understand the precedence order of the HttpTrait APIs. In - * particular, if a {@link HttpPipeline} is specified, this takes precedence over all other APIs in the trait, and - * they will be ignored. If no {@link HttpPipeline} is specified, a HTTP pipeline will be constructed internally - * based on the settings provided to this trait. Additionally, there may be other APIs in types that implement this - * trait that are also ignored if an {@link HttpPipeline} is specified, so please be sure to refer to the - * documentation of types that implement this trait to understand the full set of implications.

- * - * @param clientOptions A configured instance of {@link HttpClientOptions}. - * @return The updated SearchIndexerClientBuilder object. - * @see HttpClientOptions - */ - @Override - public SearchIndexerClientBuilder clientOptions(ClientOptions clientOptions) { - this.clientOptions = clientOptions; - return this; - } - - /** - * Adds a {@link HttpPipelinePolicy pipeline policy} to apply on each request sent. - * - *

Note: It is important to understand the precedence order of the HttpTrait APIs. In - * particular, if a {@link HttpPipeline} is specified, this takes precedence over all other APIs in the trait, and - * they will be ignored. If no {@link HttpPipeline} is specified, a HTTP pipeline will be constructed internally - * based on the settings provided to this trait. Additionally, there may be other APIs in types that implement this - * trait that are also ignored if an {@link HttpPipeline} is specified, so please be sure to refer to the - * documentation of types that implement this trait to understand the full set of implications.

- * - * @param policy A {@link HttpPipelinePolicy pipeline policy}. - * @return The updated SearchIndexerClientBuilder object. - * @throws NullPointerException If {@code policy} is {@code null}. - */ - @Override - public SearchIndexerClientBuilder addPolicy(HttpPipelinePolicy policy) { - Objects.requireNonNull(policy, "'policy' cannot be null."); - - if (policy.getPipelinePosition() == HttpPipelinePosition.PER_CALL) { - perCallPolicies.add(policy); - } else { - perRetryPolicies.add(policy); - } - - return this; - } - - /** - * Sets the {@link HttpClient} to use for sending and receiving requests to and from the service. - * - *

Note: It is important to understand the precedence order of the HttpTrait APIs. In - * particular, if a {@link HttpPipeline} is specified, this takes precedence over all other APIs in the trait, and - * they will be ignored. If no {@link HttpPipeline} is specified, a HTTP pipeline will be constructed internally - * based on the settings provided to this trait. Additionally, there may be other APIs in types that implement this - * trait that are also ignored if an {@link HttpPipeline} is specified, so please be sure to refer to the - * documentation of types that implement this trait to understand the full set of implications.

- * - * @param client The {@link HttpClient} to use for requests. - * @return The updated SearchIndexerClientBuilder object. - */ - @Override - public SearchIndexerClientBuilder httpClient(HttpClient client) { - if (this.httpClient != null && client == null) { - LOGGER.info("HttpClient is being set to 'null' when it was previously configured."); - } - - this.httpClient = client; - return this; - } - - /** - * Sets the {@link HttpPipeline} to use for the service client. - * - *

Note: It is important to understand the precedence order of the HttpTrait APIs. In - * particular, if a {@link HttpPipeline} is specified, this takes precedence over all other APIs in the trait, and - * they will be ignored. If no {@link HttpPipeline} is specified, a HTTP pipeline will be constructed internally - * based on the settings provided to this trait. Additionally, there may be other APIs in types that implement this - * trait that are also ignored if an {@link HttpPipeline} is specified, so please be sure to refer to the - * documentation of types that implement this trait to understand the full set of implications.

- *

- * If {@code pipeline} is set, all other settings are ignored, aside from {@link #endpoint(String) endpoint} when - * building a {@link SearchIndexerClient} or {@link SearchIndexerAsyncClient}. - * - * @param httpPipeline {@link HttpPipeline} to use for sending service requests and receiving responses. - * @return The updated SearchIndexerClientBuilder object. - */ - @Override - public SearchIndexerClientBuilder pipeline(HttpPipeline httpPipeline) { - if (this.httpPipeline != null && httpPipeline == null) { - LOGGER.info("HttpPipeline is being set to 'null' when it was previously configured."); - } - - this.httpPipeline = httpPipeline; - return this; - } - - /** - * Sets the configuration store that is used during construction of the service client. - *

- * The default configuration store is a clone of the {@link Configuration#getGlobalConfiguration() global - * configuration store}, use {@link Configuration#NONE} to bypass using configuration settings during construction. - * - * @param configuration The configuration store that will be used. - * @return The updated SearchIndexerClientBuilder object. - */ - @Override - public SearchIndexerClientBuilder configuration(Configuration configuration) { - this.configuration = configuration; - return this; - } - - /** - * Sets the {@link HttpPipelinePolicy} that will attempt to retry requests when needed. - *

- * A default retry policy will be supplied if one isn't provided. - *

- * Setting this is mutually exclusive with using {@link #retryOptions(RetryOptions)}. - * - * @param retryPolicy The {@link RetryPolicy} that will attempt to retry requests when needed. - * @return The updated SearchIndexerClientBuilder object. - */ - public SearchIndexerClientBuilder retryPolicy(RetryPolicy retryPolicy) { - this.retryPolicy = retryPolicy; - return this; - } - - /** - * Sets the {@link RetryOptions} for all the requests made through the client. - * - *

Note: It is important to understand the precedence order of the HttpTrait APIs. In - * particular, if a {@link HttpPipeline} is specified, this takes precedence over all other APIs in the trait, and - * they will be ignored. If no {@link HttpPipeline} is specified, a HTTP pipeline will be constructed internally - * based on the settings provided to this trait. Additionally, there may be other APIs in types that implement this - * trait that are also ignored if an {@link HttpPipeline} is specified, so please be sure to refer to the - * documentation of types that implement this trait to understand the full set of implications.

- *

- * Setting this is mutually exclusive with using {@link #retryPolicy(RetryPolicy)}. - * - * @param retryOptions The {@link RetryOptions} to use for all the requests made through the client. - * @return The updated SearchIndexerClientBuilder object. - */ - @Override - public SearchIndexerClientBuilder retryOptions(RetryOptions retryOptions) { - this.retryOptions = retryOptions; - return this; - } - - /** - * Sets the {@link SearchServiceVersion} that is used when making API requests. - *

- * If a service version is not provided, {@link SearchServiceVersion#getLatest()} will be used as a default. When - * this default is used updating to a newer client library may result in a newer version of the service being used. - * - * @param serviceVersion The version of the service to be used when making requests. - * @return The updated SearchIndexerClientBuilder object. - */ - public SearchIndexerClientBuilder serviceVersion(SearchServiceVersion serviceVersion) { - this.serviceVersion = serviceVersion; - return this; - } -} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/SearchIndexerDataSources.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/SearchIndexerDataSources.java deleted file mode 100644 index 94e496e2edc4..000000000000 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/SearchIndexerDataSources.java +++ /dev/null @@ -1,268 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.search.documents.indexes; - -import com.azure.core.util.CoreUtils; -import com.azure.search.documents.indexes.models.DataChangeDetectionPolicy; -import com.azure.search.documents.indexes.models.DataDeletionDetectionPolicy; -import com.azure.search.documents.indexes.models.HighWaterMarkChangeDetectionPolicy; -import com.azure.search.documents.indexes.models.SearchIndexerDataContainer; -import com.azure.search.documents.indexes.models.SearchIndexerDataSourceConnection; -import com.azure.search.documents.indexes.models.SearchIndexerDataSourceType; - -/** - * Utility class that aids in the creation of {@link SearchIndexerDataSourceConnection - * SearchIndexerDataSourceConnections}. - */ -public final class SearchIndexerDataSources { - - /** - * Creates a new {@link SearchIndexerDataSourceConnection} to connect to an Azure SQL database. - * - * @param dataSourceName The name of the data source. - * @param sqlConnectionString The connection string for the Azure SQL database. - * @param tableOrViewName The name of the table or view from which to read rows. - * @param description Optional. Description of the data source. - * @param changeDetectionPolicy The change detection policy for the data source. Note that only high watermark - * change detection is allowed for Azure SQL when deletion detection is enabled. - * @param deletionDetectionPolicy Optional. The data deletion detection policy for the data source. - * @return A new Azure SQL {@link SearchIndexerDataSourceConnection} instance. - * @throws IllegalArgumentException If {@code dataSourceName}, {@code sqlConnectionString}, or {@code - * tableOrViewName} is null or empty. - */ - public static SearchIndexerDataSourceConnection createFromAzureSql(String dataSourceName, - String sqlConnectionString, String tableOrViewName, String description, - DataChangeDetectionPolicy changeDetectionPolicy, DataDeletionDetectionPolicy deletionDetectionPolicy) { - if (CoreUtils.isNullOrEmpty(dataSourceName)) { - throw new IllegalArgumentException("'dataSourceName' cannot be null or empty."); - } - if (CoreUtils.isNullOrEmpty(sqlConnectionString)) { - throw new IllegalArgumentException("'sqlConnectionString' cannot be null or empty."); - } - if (CoreUtils.isNullOrEmpty(tableOrViewName)) { - throw new IllegalArgumentException("'tableOrViewName' cannot be null or empty."); - } - - return createSearchIndexerDataSource(dataSourceName, SearchIndexerDataSourceType.AZURE_SQL, sqlConnectionString, - tableOrViewName, null, description, changeDetectionPolicy, deletionDetectionPolicy); - } - - /** - * Creates a new {@link SearchIndexerDataSourceConnection} to connect to an Azure SQL database. - * - * @param dataSourceName The name of the data source. - * @param sqlConnectionString The connection string for the Azure SQL database. - * @param tableOrViewName The name of the table or view from which to read rows. - * @return A new Azure SQL {@link SearchIndexerDataSourceConnection} instance. - * @throws IllegalArgumentException If {@code dataSourceName}, {@code sqlConnectionString}, or {@code - * tableOrViewName} is null or empty. - */ - public static SearchIndexerDataSourceConnection createFromAzureSql(String dataSourceName, - String sqlConnectionString, String tableOrViewName) { - return createFromAzureSql(dataSourceName, sqlConnectionString, tableOrViewName, null, null, null); - } - - /** - * Creates a new {@link SearchIndexerDataSourceConnection} to connect to an Azure Blob container. - * - * @param dataSourceName The name of the data source. - * @param storageConnectionString The connection string for the Azure Storage account. The Storage connection string - * must use this format: - *

- * {@code "DefaultEndpointsProtocol=https;AccountName=[your storage account];AccountKey=[your account key]:} - *

- * Note: The connection string must use HTTPS. - * @param containerName The name of the container from which to read blobs. - * @param pathPrefix Optional. Limits the data source to only include blobs starting with the specified prefix, this - * is useful when blobs are organized into "virtual folders". - * @param description Optional. Description of the data source - * @param deletionDetectionPolicy Optional. The data deletion detection policy for the data source - * @return A new Azure Blob {@link SearchIndexerDataSourceConnection} instance. - * @throws IllegalArgumentException If {@code dataSourceName}, {@code containerName} or {@code - * storageConnectionString} is null or empty. - */ - public static SearchIndexerDataSourceConnection createFromAzureBlobStorage(String dataSourceName, - String storageConnectionString, String containerName, String pathPrefix, String description, - DataDeletionDetectionPolicy deletionDetectionPolicy) { - if (CoreUtils.isNullOrEmpty(dataSourceName)) { - throw new IllegalArgumentException("'dataSourceName' cannot be null or empty."); - } - if (CoreUtils.isNullOrEmpty(storageConnectionString)) { - throw new IllegalArgumentException("'storageConnectionString' cannot be null or empty."); - } - if (CoreUtils.isNullOrEmpty(containerName)) { - throw new IllegalArgumentException("'containerName' cannot be null or empty."); - } - - return createSearchIndexerDataSource(dataSourceName, SearchIndexerDataSourceType.AZURE_BLOB, - storageConnectionString, containerName, pathPrefix, description, null, deletionDetectionPolicy); - } - - /** - * Creates a new {@link SearchIndexerDataSourceConnection} to connect to an Azure Blob container. - * - * @param dataSourceName The name of the data source. - * @param storageConnectionString The connection string for the Azure Storage account. The Storage connection string - * must use this format: - *

- * {@code "DefaultEndpointsProtocol=https;AccountName=[your storage account];AccountKey=[your account key]:} - *

- * Note: The connection string must use HTTPS. - * @param containerName The name of the container from which to read blobs. - * @return A new Azure Blob {@link SearchIndexerDataSourceConnection} instance. - * @throws IllegalArgumentException If {@code dataSourceName}, {@code containerName} or {@code - * storageConnectionString} is null or empty. - */ - public static SearchIndexerDataSourceConnection createFromAzureBlobStorage(String dataSourceName, - String storageConnectionString, String containerName) { - return createFromAzureBlobStorage(dataSourceName, storageConnectionString, containerName, null, null, null); - } - - /** - * Creates a new {@link SearchIndexerDataSourceConnection} to connect to an Azure Table. - * - * @param dataSourceName The name of the data source. - * @param storageConnectionString The connection string for the Azure Storage account. The Storage connection string - * must use this format: - *

- * {@code "DefaultEndpointsProtocol=https;AccountName=[your storage account];AccountKey=[your account key]:} - *

- * Note: The connection string must use HTTPS. - * @param tableName The name of the Azure table from which to read rows. - * @param query Optional. A query that is applied to the table when reading rows. - * @param description Optional. Description of the data source - * @param deletionDetectionPolicy Optional. The data deletion detection policy for the data source. - * @return A new Azure Table {@link SearchIndexerDataSourceConnection} instance. - * @throws IllegalArgumentException If {@code dataSourceName}, {@code tableName}, or {@code storageConnectionString} - * is null or empty. - */ - public static SearchIndexerDataSourceConnection createFromAzureTableStorage(String dataSourceName, - String storageConnectionString, String tableName, String query, String description, - DataDeletionDetectionPolicy deletionDetectionPolicy) { - if (CoreUtils.isNullOrEmpty(dataSourceName)) { - throw new IllegalArgumentException("'dataSourceName' cannot be null or empty."); - } - if (CoreUtils.isNullOrEmpty(tableName)) { - throw new IllegalArgumentException("'tableName' cannot be null or empty."); - } - if (CoreUtils.isNullOrEmpty(storageConnectionString)) { - throw new IllegalArgumentException("'storageConnectionString' cannot be null or empty."); - } - - return createSearchIndexerDataSource(dataSourceName, SearchIndexerDataSourceType.AZURE_TABLE, - storageConnectionString, tableName, query, description, null, deletionDetectionPolicy); - } - - /** - * Creates a new {@link SearchIndexerDataSourceConnection} to connect to an Azure Table. - * - * @param dataSourceName The name of the data source. - * @param storageConnectionString The connection string for the Azure Storage account. The Storage connection string - * must use this format: - *

- * {@code "DefaultEndpointsProtocol=https;AccountName=[your storage account];AccountKey=[your account key]:} - *

- * Note: The connection string must use HTTPS. - * @param tableName The name of the Azure table from which to read rows. - * @return A new Azure Table {@link SearchIndexerDataSourceConnection} instance. - * @throws IllegalArgumentException If {@code dataSourceName}, {@code tableName}, or {@code storageConnectionString} - * is null or empty. - */ - public static SearchIndexerDataSourceConnection createFromAzureTableStorage(String dataSourceName, - String storageConnectionString, String tableName) { - return createFromAzureTableStorage(dataSourceName, storageConnectionString, tableName, null, null, null); - } - - /** - * Creates a new {@link SearchIndexerDataSourceConnection} to connect to a Cosmos database. - * - * @param dataSourceName The name of the data source. - * @param cosmosConnectionString The connection string for the Cosmos database. It must follow this format: - *

- * {@code AccountName|AccountEndpoint=[your account name or endpoint]; AccountKey=[your account key];Database=[your - * database name]"} - * @param collectionName The name of the collection from which to read documents. - * @param query Optional. A query that is applied to the collection when reading documents. - * @param useChangeDetection Optional. Indicates whether to use change detection when indexing. Default is true. - * @param description Optional. Description of the data source - * @param deletionDetectionPolicy Optional. The data deletion detection policy for the data source. - * @return A new Cosmos {@link SearchIndexerDataSourceConnection} instance. - * @throws IllegalArgumentException If {@code dataSourceName}, {@code collectionName}, or {@code - * cosmosConnectionString} is null or empty. - */ - public static SearchIndexerDataSourceConnection createFromCosmos(String dataSourceName, - String cosmosConnectionString, String collectionName, String query, Boolean useChangeDetection, - String description, DataDeletionDetectionPolicy deletionDetectionPolicy) { - if (CoreUtils.isNullOrEmpty(dataSourceName)) { - throw new IllegalArgumentException("'dataSourceName' cannot be null or empty."); - } - if (CoreUtils.isNullOrEmpty(collectionName)) { - throw new IllegalArgumentException("'collectionName' cannot be null or empty."); - } - if (CoreUtils.isNullOrEmpty(cosmosConnectionString)) { - throw new IllegalArgumentException("'cosmosConnectionString' cannot be null or empty."); - } - - DataChangeDetectionPolicy changeDetectionPolicy - = useChangeDetection ? new HighWaterMarkChangeDetectionPolicy("_ts") : null; - - return createSearchIndexerDataSource(dataSourceName, SearchIndexerDataSourceType.COSMOS_DB, - cosmosConnectionString, collectionName, query, description, changeDetectionPolicy, deletionDetectionPolicy); - } - - /** - * Creates a new {@link SearchIndexerDataSourceConnection} to connect to a Cosmos database. - * - * @param dataSourceName The name of the data source. - * @param cosmosConnectionString The connection string for the Cosmos database. It must follow this format: - *

- * {@code AccountName|AccountEndpoint=[your account name or endpoint]; AccountKey=[your account key];Database=[your - * database name]"} - * @param collectionName The name of the collection from which to read documents - * @param useChangeDetection Optional. Indicates whether to use change detection when indexing. Default is true. - * @return A new Cosmos {@link SearchIndexerDataSourceConnection} instance. - * @throws IllegalArgumentException If {@code dataSourceName}, {@code collectionName}, or {@code - * cosmosConnectionString} is null or empty. - */ - public static SearchIndexerDataSourceConnection createFromCosmos(String dataSourceName, - String cosmosConnectionString, String collectionName, Boolean useChangeDetection) { - return createFromCosmos(dataSourceName, cosmosConnectionString, collectionName, null, useChangeDetection, null, - null); - } - - /** - * Creates a new {@link SearchIndexerDataSourceConnection} to connect to a Cosmos database with change detection - * set to true. - * - * @param dataSourceName The name of the data source. - * @param cosmosConnectionString The connection string for the Cosmos database. It must follow this format: - *

- * {@code AccountName|AccountEndpoint=[your account name or endpoint]; AccountKey=[your account key];Database=[your - * database name]"} - * @param collectionName The name of the collection from which to read documents - * @return A new Cosmos {@link SearchIndexerDataSourceConnection} instance. - * @throws IllegalArgumentException If {@code dataSourceName}, {@code collectionName}, or {@code - * cosmosConnectionString} is null or empty. - */ - public static SearchIndexerDataSourceConnection createFromCosmos(String dataSourceName, - String cosmosConnectionString, String collectionName) { - return createFromCosmos(dataSourceName, cosmosConnectionString, collectionName, null, true, null, null); - } - - /* - * Helper method that creates a generic SearchIndexerDataSource. - */ - private static SearchIndexerDataSourceConnection createSearchIndexerDataSource(String name, - SearchIndexerDataSourceType type, String connectionString, String dataSourceName, String dataSourceQuery, - String description, DataChangeDetectionPolicy dataChangeDetectionPolicy, - DataDeletionDetectionPolicy dataDeletionDetectionPolicy) { - return new SearchIndexerDataSourceConnection(name, type, connectionString, - new SearchIndexerDataContainer(dataSourceName).setQuery(dataSourceQuery)).setDescription(description) - .setDataChangeDetectionPolicy(dataChangeDetectionPolicy) - .setDataDeletionDetectionPolicy(dataDeletionDetectionPolicy); - } - - private SearchIndexerDataSources() { - } -} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/SearchableField.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/SearchableField.java deleted file mode 100644 index 6579d4de3e24..000000000000 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/SearchableField.java +++ /dev/null @@ -1,129 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.search.documents.indexes; - -import com.azure.search.documents.indexes.models.FieldBuilderOptions; -import com.azure.search.documents.indexes.models.LexicalAnalyzerName; -import com.azure.search.documents.indexes.models.SearchField; -import com.azure.search.documents.indexes.models.SynonymMap; -import com.azure.search.documents.indexes.models.VectorEncodingFormat; - -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -/** - * An annotation that directs {@link SearchIndexAsyncClient#buildSearchFields(Class, FieldBuilderOptions)} to turn the - * field or method into a searchable {@link SearchField field}. - */ -@Target({ ElementType.FIELD, ElementType.METHOD }) -@Retention(RetentionPolicy.RUNTIME) -public @interface SearchableField { - /** - * Indicates if the field or method should generate as a key {@link SearchField field}. - * - * @return A flag indicating if the field or method should generate as a key {@link SearchField field}. - */ - boolean isKey() default false; - - /** - * Indicates if the field or method should generate as a hidden {@link SearchField field}. - * - * @return A flag indicating if the field or method should generate as a hidden {@link SearchField field}. - */ - boolean isHidden() default false; - - /** - * Indicates if the field or method should generate as a facetable {@link SearchField field}. - * - * @return A flag indicating if the field or method should generate as a facetable {@link SearchField field}. - */ - boolean isFacetable() default false; - - /** - * Indicates if the field or method should generate as a sortable {@link SearchField field}. - * - * @return A flag indicating if the field or method should generate as a sortable {@link SearchField field}. - */ - boolean isSortable() default false; - - /** - * Indicates if whether the field will be persisted separately on disk to be returned in a search result. - * - * @return A flag indicating if the field or method should generate as a stored {@link SearchField field}. - */ - boolean isStored() default true; - - /** - * Indicates if the field or method should generate as a filterable {@link SearchField field}. - * - * @return A flag indicating if the field or method should generate as a filterable {@link SearchField field}. - */ - boolean isFilterable() default false; - - /** - * A {@link LexicalAnalyzerName} to associate as the search and index analyzer for the {@link SearchField field}. - * - * @return The {@link LexicalAnalyzerName} that will be associated as the search and index analyzer for the - * {@link SearchField field}. - */ - String analyzerName() default ""; - - /** - * A {@link LexicalAnalyzerName} to associate as the search analyzer for the {@link SearchField field}. - * - * @return The {@link LexicalAnalyzerName} that will be associated as the search analyzer for the - * {@link SearchField field}. - */ - String searchAnalyzerName() default ""; - - /** - * A {@link LexicalAnalyzerName} to associate as the index analyzer for the {@link SearchField field}. - * - * @return The {@link LexicalAnalyzerName} that will be associated as the index analyzer for the - * {@link SearchField field}. - */ - String indexAnalyzerName() default ""; - - /** - * A list of {@link SynonymMap} names to be associated with the {@link SearchField field}. - *

- * 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. The synonym map attribute may be changed on existing fields. - *

- * Currently, only one synonym map per field is supported. - * - * @return The {@link SynonymMap} names that will be associated with the {@link SearchField field}. - */ - String[] synonymMapNames() default { }; - - /** - * The dimensionality of the vector field. - *

- * If the value is negative or 0, the field won't have a {@link SearchField#getVectorSearchDimensions()} value. - * - * @return The dimensionality of the vector {@link SearchField field}. - */ - int vectorSearchDimensions() default -1; - - /** - * The name of the vector search profile that specifies the parameters for searching the vector field. - *

- * If the value is empty, the field won't have a {@link SearchField#getVectorSearchProfileName()} ()} value. - * - * @return The name of the vector search profile that specifies the parameters for searching the vector - * {@link SearchField field}. - */ - String vectorSearchProfileName() default ""; - - /** - * A {@link VectorEncodingFormat} to be associated with the {@link SearchField field}. - *

- * If the value is empty, the field won't have a {@link SearchField#getVectorEncodingFormat()} value. - * - * @return The {@link VectorEncodingFormat} that will be associated with the {@link SearchField field}. - */ - String vectorEncodingFormat() default ""; -} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/SimpleField.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/SimpleField.java deleted file mode 100644 index a0d651d9888d..000000000000 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/SimpleField.java +++ /dev/null @@ -1,55 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.search.documents.indexes; - -import com.azure.search.documents.indexes.models.FieldBuilderOptions; -import com.azure.search.documents.indexes.models.SearchField; - -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -/** - * An annotation that directs {@link SearchIndexAsyncClient#buildSearchFields(Class, FieldBuilderOptions)} to turn the - * field or method into a non-searchable {@link SearchField field}. - */ -@Target({ ElementType.FIELD, ElementType.METHOD }) -@Retention(RetentionPolicy.RUNTIME) -public @interface SimpleField { - /** - * Indicates if the field or method should generate as a key {@link SearchField field}. - * - * @return A flag indicating if the field or method should generate as a key {@link SearchField field}. - */ - boolean isKey() default false; - - /** - * Indicates if the field or method should generate as a hidden {@link SearchField field}. - * - * @return A flag indicating if the field or method should generate as a hidden {@link SearchField field}. - */ - boolean isHidden() default false; - - /** - * Indicates if the field or method should generate as a facetable {@link SearchField field}. - * - * @return A flag indicating if the field or method should generate as a facetable {@link SearchField field}. - */ - boolean isFacetable() default false; - - /** - * Indicates if the field or method should generate as a sortable {@link SearchField field}. - * - * @return A flag indicating if the field or method should generate as a sortable {@link SearchField field}. - */ - boolean isSortable() default false; - - /** - * Indicates if the field or method should generate as a filterable {@link SearchField field}. - * - * @return A flag indicating if the field or method should generate as a filterable {@link SearchField field}. - */ - boolean isFilterable() default false; -} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/implementation/AliasesImpl.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/implementation/AliasesImpl.java deleted file mode 100644 index f973595390f3..000000000000 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/implementation/AliasesImpl.java +++ /dev/null @@ -1,826 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -package com.azure.search.documents.indexes.implementation; - -import com.azure.core.annotation.BodyParam; -import com.azure.core.annotation.Delete; -import com.azure.core.annotation.ExpectedResponses; -import com.azure.core.annotation.Get; -import com.azure.core.annotation.HeaderParam; -import com.azure.core.annotation.Host; -import com.azure.core.annotation.HostParam; -import com.azure.core.annotation.PathParam; -import com.azure.core.annotation.Post; -import com.azure.core.annotation.Put; -import com.azure.core.annotation.QueryParam; -import com.azure.core.annotation.ReturnType; -import com.azure.core.annotation.ServiceInterface; -import com.azure.core.annotation.ServiceMethod; -import com.azure.core.annotation.UnexpectedResponseExceptionType; -import com.azure.core.http.rest.PagedFlux; -import com.azure.core.http.rest.PagedIterable; -import com.azure.core.http.rest.PagedResponse; -import com.azure.core.http.rest.PagedResponseBase; -import com.azure.core.http.rest.Response; -import com.azure.core.http.rest.RestProxy; -import com.azure.core.util.Context; -import com.azure.core.util.FluxUtil; -import com.azure.search.documents.indexes.implementation.models.ErrorResponseException; -import com.azure.search.documents.indexes.implementation.models.ListAliasesResult; -import com.azure.search.documents.indexes.implementation.models.RequestOptions; -import com.azure.search.documents.indexes.models.SearchAlias; -import java.util.UUID; -import reactor.core.publisher.Mono; - -/** - * An instance of this class provides access to all the operations defined in Aliases. - */ -public final class AliasesImpl { - /** - * The proxy service used to perform REST calls. - */ - private final AliasesService service; - - /** - * The service client containing this operation class. - */ - private final SearchServiceClientImpl client; - - /** - * Initializes an instance of AliasesImpl. - * - * @param client the instance of the service client containing this operation class. - */ - AliasesImpl(SearchServiceClientImpl client) { - this.service = RestProxy.create(AliasesService.class, client.getHttpPipeline(), client.getSerializerAdapter()); - this.client = client; - } - - /** - * The interface defining all the services for SearchServiceClientAliases to be used by the proxy service to perform - * REST calls. - */ - @Host("{endpoint}") - @ServiceInterface(name = "SearchServiceClientA") - public interface AliasesService { - @Post("/aliases") - @ExpectedResponses({ 201 }) - @UnexpectedResponseExceptionType(ErrorResponseException.class) - Mono> create(@HostParam("endpoint") String endpoint, - @HeaderParam("x-ms-client-request-id") UUID xMsClientRequestId, - @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, - @BodyParam("application/json") SearchAlias alias, Context context); - - @Post("/aliases") - @ExpectedResponses({ 201 }) - @UnexpectedResponseExceptionType(ErrorResponseException.class) - Response createSync(@HostParam("endpoint") String endpoint, - @HeaderParam("x-ms-client-request-id") UUID xMsClientRequestId, - @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, - @BodyParam("application/json") SearchAlias alias, Context context); - - @Get("/aliases") - @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(ErrorResponseException.class) - Mono> list(@HostParam("endpoint") String endpoint, - @HeaderParam("x-ms-client-request-id") UUID xMsClientRequestId, - @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, Context context); - - @Get("/aliases") - @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(ErrorResponseException.class) - Response listSync(@HostParam("endpoint") String endpoint, - @HeaderParam("x-ms-client-request-id") UUID xMsClientRequestId, - @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, Context context); - - @Put("/aliases('{aliasName}')") - @ExpectedResponses({ 200, 201 }) - @UnexpectedResponseExceptionType(ErrorResponseException.class) - Mono> createOrUpdate(@HostParam("endpoint") String endpoint, - @PathParam("aliasName") String aliasName, @HeaderParam("x-ms-client-request-id") UUID xMsClientRequestId, - @HeaderParam("If-Match") String ifMatch, @HeaderParam("If-None-Match") String ifNoneMatch, - @HeaderParam("Prefer") String prefer, @QueryParam("api-version") String apiVersion, - @HeaderParam("Accept") String accept, @BodyParam("application/json") SearchAlias alias, Context context); - - @Put("/aliases('{aliasName}')") - @ExpectedResponses({ 200, 201 }) - @UnexpectedResponseExceptionType(ErrorResponseException.class) - Response createOrUpdateSync(@HostParam("endpoint") String endpoint, - @PathParam("aliasName") String aliasName, @HeaderParam("x-ms-client-request-id") UUID xMsClientRequestId, - @HeaderParam("If-Match") String ifMatch, @HeaderParam("If-None-Match") String ifNoneMatch, - @HeaderParam("Prefer") String prefer, @QueryParam("api-version") String apiVersion, - @HeaderParam("Accept") String accept, @BodyParam("application/json") SearchAlias alias, Context context); - - @Delete("/aliases('{aliasName}')") - @ExpectedResponses({ 204, 404 }) - @UnexpectedResponseExceptionType(ErrorResponseException.class) - Mono> delete(@HostParam("endpoint") String endpoint, @PathParam("aliasName") String aliasName, - @HeaderParam("x-ms-client-request-id") UUID xMsClientRequestId, @HeaderParam("If-Match") String ifMatch, - @HeaderParam("If-None-Match") String ifNoneMatch, @QueryParam("api-version") String apiVersion, - @HeaderParam("Accept") String accept, Context context); - - @Delete("/aliases('{aliasName}')") - @ExpectedResponses({ 204, 404 }) - @UnexpectedResponseExceptionType(ErrorResponseException.class) - Response deleteSync(@HostParam("endpoint") String endpoint, @PathParam("aliasName") String aliasName, - @HeaderParam("x-ms-client-request-id") UUID xMsClientRequestId, @HeaderParam("If-Match") String ifMatch, - @HeaderParam("If-None-Match") String ifNoneMatch, @QueryParam("api-version") String apiVersion, - @HeaderParam("Accept") String accept, Context context); - - @Get("/aliases('{aliasName}')") - @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(ErrorResponseException.class) - Mono> get(@HostParam("endpoint") String endpoint, - @PathParam("aliasName") String aliasName, @HeaderParam("x-ms-client-request-id") UUID xMsClientRequestId, - @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, Context context); - - @Get("/aliases('{aliasName}')") - @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(ErrorResponseException.class) - Response getSync(@HostParam("endpoint") String endpoint, @PathParam("aliasName") String aliasName, - @HeaderParam("x-ms-client-request-id") UUID xMsClientRequestId, - @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, Context context); - } - - /** - * Creates a new search alias. - * - * @param alias The definition of the alias to create. - * @param requestOptions Parameter group. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return represents an index alias, which describes a mapping from the alias name to an index along with - * {@link Response} on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> createWithResponseAsync(SearchAlias alias, RequestOptions requestOptions) { - return FluxUtil.withContext(context -> createWithResponseAsync(alias, requestOptions, context)); - } - - /** - * Creates a new search alias. - * - * @param alias The definition of the alias to create. - * @param requestOptions Parameter group. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return represents an index alias, which describes a mapping from the alias name to an index along with - * {@link Response} on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> createWithResponseAsync(SearchAlias alias, RequestOptions requestOptions, - Context context) { - final String accept = "application/json; odata.metadata=minimal"; - UUID xMsClientRequestIdInternal = null; - if (requestOptions != null) { - xMsClientRequestIdInternal = requestOptions.getXMsClientRequestId(); - } - UUID xMsClientRequestId = xMsClientRequestIdInternal; - return service.create(this.client.getEndpoint(), xMsClientRequestId, this.client.getApiVersion(), accept, alias, - context); - } - - /** - * Creates a new search alias. - * - * @param alias The definition of the alias to create. - * @param requestOptions Parameter group. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return represents an index alias, which describes a mapping from the alias name to an index on successful - * completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono createAsync(SearchAlias alias, RequestOptions requestOptions) { - return createWithResponseAsync(alias, requestOptions).flatMap(res -> Mono.justOrEmpty(res.getValue())); - } - - /** - * Creates a new search alias. - * - * @param alias The definition of the alias to create. - * @param requestOptions Parameter group. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return represents an index alias, which describes a mapping from the alias name to an index on successful - * completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono createAsync(SearchAlias alias, RequestOptions requestOptions, Context context) { - return createWithResponseAsync(alias, requestOptions, context).flatMap(res -> Mono.justOrEmpty(res.getValue())); - } - - /** - * Creates a new search alias. - * - * @param alias The definition of the alias to create. - * @param requestOptions Parameter group. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return represents an index alias, which describes a mapping from the alias name to an index along with - * {@link Response}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Response createWithResponse(SearchAlias alias, RequestOptions requestOptions, Context context) { - final String accept = "application/json; odata.metadata=minimal"; - UUID xMsClientRequestIdInternal = null; - if (requestOptions != null) { - xMsClientRequestIdInternal = requestOptions.getXMsClientRequestId(); - } - UUID xMsClientRequestId = xMsClientRequestIdInternal; - return service.createSync(this.client.getEndpoint(), xMsClientRequestId, this.client.getApiVersion(), accept, - alias, context); - } - - /** - * Creates a new search alias. - * - * @param alias The definition of the alias to create. - * @param requestOptions Parameter group. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return represents an index alias, which describes a mapping from the alias name to an index. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public SearchAlias create(SearchAlias alias, RequestOptions requestOptions) { - return createWithResponse(alias, requestOptions, Context.NONE).getValue(); - } - - /** - * Lists all aliases available for a search service. - * - * @param requestOptions Parameter group. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return response from a List Aliases request along with {@link PagedResponse} on successful completion of - * {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> listSinglePageAsync(RequestOptions requestOptions) { - final String accept = "application/json; odata.metadata=minimal"; - UUID xMsClientRequestIdInternal = null; - if (requestOptions != null) { - xMsClientRequestIdInternal = requestOptions.getXMsClientRequestId(); - } - UUID xMsClientRequestId = xMsClientRequestIdInternal; - return FluxUtil - .withContext(context -> service.list(this.client.getEndpoint(), xMsClientRequestId, - this.client.getApiVersion(), accept, context)) - .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), - res.getValue().getAliases(), null, null)); - } - - /** - * Lists all aliases available for a search service. - * - * @param requestOptions Parameter group. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return response from a List Aliases request along with {@link PagedResponse} on successful completion of - * {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> listSinglePageAsync(RequestOptions requestOptions, Context context) { - final String accept = "application/json; odata.metadata=minimal"; - UUID xMsClientRequestIdInternal = null; - if (requestOptions != null) { - xMsClientRequestIdInternal = requestOptions.getXMsClientRequestId(); - } - UUID xMsClientRequestId = xMsClientRequestIdInternal; - return service.list(this.client.getEndpoint(), xMsClientRequestId, this.client.getApiVersion(), accept, context) - .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), - res.getValue().getAliases(), null, null)); - } - - /** - * Lists all aliases available for a search service. - * - * @param requestOptions Parameter group. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return response from a List Aliases request as paginated response with {@link PagedFlux}. - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - public PagedFlux listAsync(RequestOptions requestOptions) { - return new PagedFlux<>(() -> listSinglePageAsync(requestOptions)); - } - - /** - * Lists all aliases available for a search service. - * - * @param requestOptions Parameter group. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return response from a List Aliases request as paginated response with {@link PagedFlux}. - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - public PagedFlux listAsync(RequestOptions requestOptions, Context context) { - return new PagedFlux<>(() -> listSinglePageAsync(requestOptions, context)); - } - - /** - * Lists all aliases available for a search service. - * - * @param requestOptions Parameter group. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return response from a List Aliases request along with {@link PagedResponse}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public PagedResponse listSinglePage(RequestOptions requestOptions) { - final String accept = "application/json; odata.metadata=minimal"; - UUID xMsClientRequestIdInternal = null; - if (requestOptions != null) { - xMsClientRequestIdInternal = requestOptions.getXMsClientRequestId(); - } - UUID xMsClientRequestId = xMsClientRequestIdInternal; - Response res = service.listSync(this.client.getEndpoint(), xMsClientRequestId, - this.client.getApiVersion(), accept, Context.NONE); - return new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), - res.getValue().getAliases(), null, null); - } - - /** - * Lists all aliases available for a search service. - * - * @param requestOptions Parameter group. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return response from a List Aliases request along with {@link PagedResponse}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public PagedResponse listSinglePage(RequestOptions requestOptions, Context context) { - final String accept = "application/json; odata.metadata=minimal"; - UUID xMsClientRequestIdInternal = null; - if (requestOptions != null) { - xMsClientRequestIdInternal = requestOptions.getXMsClientRequestId(); - } - UUID xMsClientRequestId = xMsClientRequestIdInternal; - Response res = service.listSync(this.client.getEndpoint(), xMsClientRequestId, - this.client.getApiVersion(), accept, context); - return new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), - res.getValue().getAliases(), null, null); - } - - /** - * Lists all aliases available for a search service. - * - * @param requestOptions Parameter group. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return response from a List Aliases request as paginated response with {@link PagedIterable}. - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - public PagedIterable list(RequestOptions requestOptions) { - return new PagedIterable<>(() -> listSinglePage(requestOptions, Context.NONE)); - } - - /** - * Lists all aliases available for a search service. - * - * @param requestOptions Parameter group. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return response from a List Aliases request as paginated response with {@link PagedIterable}. - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - public PagedIterable list(RequestOptions requestOptions, Context context) { - return new PagedIterable<>(() -> listSinglePage(requestOptions, context)); - } - - /** - * Creates a new search alias or updates an alias if it already exists. - * - * @param aliasName The definition of the alias to create or update. - * @param alias The definition of the alias to create or update. - * @param ifMatch Defines the If-Match condition. The operation will be performed only if the ETag on the server - * matches this value. - * @param ifNoneMatch Defines the If-None-Match condition. The operation will be performed only if the ETag on the - * server does not match this value. - * @param requestOptions Parameter group. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return represents an index alias, which describes a mapping from the alias name to an index along with - * {@link Response} on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> createOrUpdateWithResponseAsync(String aliasName, SearchAlias alias, - String ifMatch, String ifNoneMatch, RequestOptions requestOptions) { - return FluxUtil.withContext(context -> createOrUpdateWithResponseAsync(aliasName, alias, ifMatch, ifNoneMatch, - requestOptions, context)); - } - - /** - * Creates a new search alias or updates an alias if it already exists. - * - * @param aliasName The definition of the alias to create or update. - * @param alias The definition of the alias to create or update. - * @param ifMatch Defines the If-Match condition. The operation will be performed only if the ETag on the server - * matches this value. - * @param ifNoneMatch Defines the If-None-Match condition. The operation will be performed only if the ETag on the - * server does not match this value. - * @param requestOptions Parameter group. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return represents an index alias, which describes a mapping from the alias name to an index along with - * {@link Response} on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> createOrUpdateWithResponseAsync(String aliasName, SearchAlias alias, - String ifMatch, String ifNoneMatch, RequestOptions requestOptions, Context context) { - final String prefer = "return=representation"; - final String accept = "application/json; odata.metadata=minimal"; - UUID xMsClientRequestIdInternal = null; - if (requestOptions != null) { - xMsClientRequestIdInternal = requestOptions.getXMsClientRequestId(); - } - UUID xMsClientRequestId = xMsClientRequestIdInternal; - return service.createOrUpdate(this.client.getEndpoint(), aliasName, xMsClientRequestId, ifMatch, ifNoneMatch, - prefer, this.client.getApiVersion(), accept, alias, context); - } - - /** - * Creates a new search alias or updates an alias if it already exists. - * - * @param aliasName The definition of the alias to create or update. - * @param alias The definition of the alias to create or update. - * @param ifMatch Defines the If-Match condition. The operation will be performed only if the ETag on the server - * matches this value. - * @param ifNoneMatch Defines the If-None-Match condition. The operation will be performed only if the ETag on the - * server does not match this value. - * @param requestOptions Parameter group. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return represents an index alias, which describes a mapping from the alias name to an index on successful - * completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono createOrUpdateAsync(String aliasName, SearchAlias alias, String ifMatch, - String ifNoneMatch, RequestOptions requestOptions) { - return createOrUpdateWithResponseAsync(aliasName, alias, ifMatch, ifNoneMatch, requestOptions) - .flatMap(res -> Mono.justOrEmpty(res.getValue())); - } - - /** - * Creates a new search alias or updates an alias if it already exists. - * - * @param aliasName The definition of the alias to create or update. - * @param alias The definition of the alias to create or update. - * @param ifMatch Defines the If-Match condition. The operation will be performed only if the ETag on the server - * matches this value. - * @param ifNoneMatch Defines the If-None-Match condition. The operation will be performed only if the ETag on the - * server does not match this value. - * @param requestOptions Parameter group. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return represents an index alias, which describes a mapping from the alias name to an index on successful - * completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono createOrUpdateAsync(String aliasName, SearchAlias alias, String ifMatch, - String ifNoneMatch, RequestOptions requestOptions, Context context) { - return createOrUpdateWithResponseAsync(aliasName, alias, ifMatch, ifNoneMatch, requestOptions, context) - .flatMap(res -> Mono.justOrEmpty(res.getValue())); - } - - /** - * Creates a new search alias or updates an alias if it already exists. - * - * @param aliasName The definition of the alias to create or update. - * @param alias The definition of the alias to create or update. - * @param ifMatch Defines the If-Match condition. The operation will be performed only if the ETag on the server - * matches this value. - * @param ifNoneMatch Defines the If-None-Match condition. The operation will be performed only if the ETag on the - * server does not match this value. - * @param requestOptions Parameter group. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return represents an index alias, which describes a mapping from the alias name to an index along with - * {@link Response}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Response createOrUpdateWithResponse(String aliasName, SearchAlias alias, String ifMatch, - String ifNoneMatch, RequestOptions requestOptions, Context context) { - final String prefer = "return=representation"; - final String accept = "application/json; odata.metadata=minimal"; - UUID xMsClientRequestIdInternal = null; - if (requestOptions != null) { - xMsClientRequestIdInternal = requestOptions.getXMsClientRequestId(); - } - UUID xMsClientRequestId = xMsClientRequestIdInternal; - return service.createOrUpdateSync(this.client.getEndpoint(), aliasName, xMsClientRequestId, ifMatch, - ifNoneMatch, prefer, this.client.getApiVersion(), accept, alias, context); - } - - /** - * Creates a new search alias or updates an alias if it already exists. - * - * @param aliasName The definition of the alias to create or update. - * @param alias The definition of the alias to create or update. - * @param ifMatch Defines the If-Match condition. The operation will be performed only if the ETag on the server - * matches this value. - * @param ifNoneMatch Defines the If-None-Match condition. The operation will be performed only if the ETag on the - * server does not match this value. - * @param requestOptions Parameter group. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return represents an index alias, which describes a mapping from the alias name to an index. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public SearchAlias createOrUpdate(String aliasName, SearchAlias alias, String ifMatch, String ifNoneMatch, - RequestOptions requestOptions) { - return createOrUpdateWithResponse(aliasName, alias, ifMatch, ifNoneMatch, requestOptions, Context.NONE) - .getValue(); - } - - /** - * 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 aliasName The name of the alias to delete. - * @param ifMatch Defines the If-Match condition. The operation will be performed only if the ETag on the server - * matches this value. - * @param ifNoneMatch Defines the If-None-Match condition. The operation will be performed only if the ETag on the - * server does not match this value. - * @param requestOptions Parameter group. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the {@link Response} on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> deleteWithResponseAsync(String aliasName, String ifMatch, String ifNoneMatch, - RequestOptions requestOptions) { - return FluxUtil - .withContext(context -> deleteWithResponseAsync(aliasName, ifMatch, ifNoneMatch, requestOptions, context)); - } - - /** - * 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 aliasName The name of the alias to delete. - * @param ifMatch Defines the If-Match condition. The operation will be performed only if the ETag on the server - * matches this value. - * @param ifNoneMatch Defines the If-None-Match condition. The operation will be performed only if the ETag on the - * server does not match this value. - * @param requestOptions Parameter group. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the {@link Response} on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> deleteWithResponseAsync(String aliasName, String ifMatch, String ifNoneMatch, - RequestOptions requestOptions, Context context) { - final String accept = "application/json; odata.metadata=minimal"; - UUID xMsClientRequestIdInternal = null; - if (requestOptions != null) { - xMsClientRequestIdInternal = requestOptions.getXMsClientRequestId(); - } - UUID xMsClientRequestId = xMsClientRequestIdInternal; - return service.delete(this.client.getEndpoint(), aliasName, xMsClientRequestId, ifMatch, ifNoneMatch, - this.client.getApiVersion(), accept, context); - } - - /** - * 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 aliasName The name of the alias to delete. - * @param ifMatch Defines the If-Match condition. The operation will be performed only if the ETag on the server - * matches this value. - * @param ifNoneMatch Defines the If-None-Match condition. The operation will be performed only if the ETag on the - * server does not match this value. - * @param requestOptions Parameter group. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return A {@link Mono} that completes when a successful response is received. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono deleteAsync(String aliasName, String ifMatch, String ifNoneMatch, RequestOptions requestOptions) { - return deleteWithResponseAsync(aliasName, ifMatch, ifNoneMatch, requestOptions) - .flatMap(ignored -> Mono.empty()); - } - - /** - * 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 aliasName The name of the alias to delete. - * @param ifMatch Defines the If-Match condition. The operation will be performed only if the ETag on the server - * matches this value. - * @param ifNoneMatch Defines the If-None-Match condition. The operation will be performed only if the ETag on the - * server does not match this value. - * @param requestOptions Parameter group. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return A {@link Mono} that completes when a successful response is received. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono deleteAsync(String aliasName, String ifMatch, String ifNoneMatch, RequestOptions requestOptions, - Context context) { - return deleteWithResponseAsync(aliasName, ifMatch, ifNoneMatch, requestOptions, context) - .flatMap(ignored -> Mono.empty()); - } - - /** - * 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 aliasName The name of the alias to delete. - * @param ifMatch Defines the If-Match condition. The operation will be performed only if the ETag on the server - * matches this value. - * @param ifNoneMatch Defines the If-None-Match condition. The operation will be performed only if the ETag on the - * server does not match this value. - * @param requestOptions Parameter group. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the {@link Response}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Response deleteWithResponse(String aliasName, String ifMatch, String ifNoneMatch, - RequestOptions requestOptions, Context context) { - final String accept = "application/json; odata.metadata=minimal"; - UUID xMsClientRequestIdInternal = null; - if (requestOptions != null) { - xMsClientRequestIdInternal = requestOptions.getXMsClientRequestId(); - } - UUID xMsClientRequestId = xMsClientRequestIdInternal; - return service.deleteSync(this.client.getEndpoint(), aliasName, xMsClientRequestId, ifMatch, ifNoneMatch, - this.client.getApiVersion(), accept, context); - } - - /** - * 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 aliasName The name of the alias to delete. - * @param ifMatch Defines the If-Match condition. The operation will be performed only if the ETag on the server - * matches this value. - * @param ifNoneMatch Defines the If-None-Match condition. The operation will be performed only if the ETag on the - * server does not match this value. - * @param requestOptions Parameter group. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public void delete(String aliasName, String ifMatch, String ifNoneMatch, RequestOptions requestOptions) { - deleteWithResponse(aliasName, ifMatch, ifNoneMatch, requestOptions, Context.NONE); - } - - /** - * Retrieves an alias definition. - * - * @param aliasName The name of the alias to retrieve. - * @param requestOptions Parameter group. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return represents an index alias, which describes a mapping from the alias name to an index along with - * {@link Response} on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> getWithResponseAsync(String aliasName, RequestOptions requestOptions) { - return FluxUtil.withContext(context -> getWithResponseAsync(aliasName, requestOptions, context)); - } - - /** - * Retrieves an alias definition. - * - * @param aliasName The name of the alias to retrieve. - * @param requestOptions Parameter group. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return represents an index alias, which describes a mapping from the alias name to an index along with - * {@link Response} on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> getWithResponseAsync(String aliasName, RequestOptions requestOptions, - Context context) { - final String accept = "application/json; odata.metadata=minimal"; - UUID xMsClientRequestIdInternal = null; - if (requestOptions != null) { - xMsClientRequestIdInternal = requestOptions.getXMsClientRequestId(); - } - UUID xMsClientRequestId = xMsClientRequestIdInternal; - return service.get(this.client.getEndpoint(), aliasName, xMsClientRequestId, this.client.getApiVersion(), - accept, context); - } - - /** - * Retrieves an alias definition. - * - * @param aliasName The name of the alias to retrieve. - * @param requestOptions Parameter group. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return represents an index alias, which describes a mapping from the alias name to an index on successful - * completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono getAsync(String aliasName, RequestOptions requestOptions) { - return getWithResponseAsync(aliasName, requestOptions).flatMap(res -> Mono.justOrEmpty(res.getValue())); - } - - /** - * Retrieves an alias definition. - * - * @param aliasName The name of the alias to retrieve. - * @param requestOptions Parameter group. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return represents an index alias, which describes a mapping from the alias name to an index on successful - * completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono getAsync(String aliasName, RequestOptions requestOptions, Context context) { - return getWithResponseAsync(aliasName, requestOptions, context) - .flatMap(res -> Mono.justOrEmpty(res.getValue())); - } - - /** - * Retrieves an alias definition. - * - * @param aliasName The name of the alias to retrieve. - * @param requestOptions Parameter group. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return represents an index alias, which describes a mapping from the alias name to an index along with - * {@link Response}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Response getWithResponse(String aliasName, RequestOptions requestOptions, Context context) { - final String accept = "application/json; odata.metadata=minimal"; - UUID xMsClientRequestIdInternal = null; - if (requestOptions != null) { - xMsClientRequestIdInternal = requestOptions.getXMsClientRequestId(); - } - UUID xMsClientRequestId = xMsClientRequestIdInternal; - return service.getSync(this.client.getEndpoint(), aliasName, xMsClientRequestId, this.client.getApiVersion(), - accept, context); - } - - /** - * Retrieves an alias definition. - * - * @param aliasName The name of the alias to retrieve. - * @param requestOptions Parameter group. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return represents an index alias, which describes a mapping from the alias name to an index. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public SearchAlias get(String aliasName, RequestOptions requestOptions) { - return getWithResponse(aliasName, requestOptions, Context.NONE).getValue(); - } -} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/implementation/CoreToCodegenBridgeUtils.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/implementation/CoreToCodegenBridgeUtils.java deleted file mode 100644 index de981e670711..000000000000 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/implementation/CoreToCodegenBridgeUtils.java +++ /dev/null @@ -1,196 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -package com.azure.search.documents.indexes.implementation; - -import com.azure.core.models.ResponseError; -import com.azure.json.JsonReader; -import com.azure.json.JsonToken; -import com.azure.json.JsonWriter; -import java.io.IOException; -import java.time.Duration; - -/** - * Utility class that handles functionality not yet available in azure-core that generated code requires. - */ -public final class CoreToCodegenBridgeUtils { - /** - * Writes the object to the passed {@link ResponseError}. - * - * @param jsonWriter Where the {@link ResponseError} JSON will be written. - * @return The {@link JsonWriter} where the JSON was written. - * @throws IOException If the {@link ResponseError} fails to be written to the {@code jsonWriter}. - */ - public static JsonWriter responseErrorToJson(JsonWriter jsonWriter, ResponseError responseError) - throws IOException { - return jsonWriter.writeStartObject() - .writeStringField("code", responseError.getCode()) - .writeStringField("message", responseError.getMessage()) - .writeEndObject(); - } - - /** - * Reads a JSON stream into a {@link ResponseError}. - * - * @param jsonReader The {@link JsonReader} being read. - * @return The {@link ResponseError} that the JSON stream represented, or null if it pointed to JSON null. - * @throws IllegalStateException If the deserialized JSON object was missing any required properties. - * @throws IOException If a {@link ResponseError} fails to be read from the {@code jsonReader}. - */ - public static ResponseError responseErrorFromJson(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - // Buffer the next JSON object as ResponseError can take two forms: - // - // - A ResponseError object - // - A ResponseError object wrapped in an "error" node. - JsonReader bufferedReader = reader.bufferObject(); - bufferedReader.nextToken(); // Get to the START_OBJECT token. - while (bufferedReader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = bufferedReader.getFieldName(); - bufferedReader.nextToken(); - - if ("error".equals(fieldName)) { - // If the ResponseError was wrapped in the "error" node begin reading it now. - return readResponseError(bufferedReader); - } else { - bufferedReader.skipChildren(); - } - } - - // Otherwise reset the JsonReader and read the whole JSON object. - return readResponseError(bufferedReader.reset()); - }); - } - - private static ResponseError readResponseError(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - String code = null; - boolean codeFound = false; - String message = null; - boolean messageFound = false; - - while (reader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = reader.getFieldName(); - reader.nextToken(); - - if ("code".equals(fieldName)) { - code = reader.getString(); - codeFound = true; - } else if ("message".equals(fieldName)) { - message = reader.getString(); - messageFound = true; - } else { - reader.skipChildren(); - } - } - - if (!codeFound && !messageFound) { - throw new IllegalStateException("Missing required properties: code, message"); - } else if (!codeFound) { - throw new IllegalStateException("Missing required property: code"); - } else if (!messageFound) { - throw new IllegalStateException("Missing required property: message"); - } - - return new ResponseError(code, message); - }); - } - - /** - * Converts a {@link Duration} to a string in ISO-8601 format with support for a day component. - * - * @param duration The {@link Duration} to convert. - * @return The {@link Duration} as a string in ISO-8601 format with support for a day component, or null if the - * provided {@link Duration} was null. - */ - public static String durationToStringWithDays(Duration duration) { - if (duration == null) { - return null; - } - - if (duration.isZero()) { - return "PT0S"; - } - - StringBuilder builder = new StringBuilder(); - - if (duration.isNegative()) { - builder.append("-P"); - duration = duration.negated(); - } else { - builder.append('P'); - } - - long days = duration.toDays(); - if (days > 0) { - builder.append(days); - builder.append('D'); - duration = duration.minusDays(days); - } - - long hours = duration.toHours(); - if (hours > 0) { - builder.append('T'); - builder.append(hours); - builder.append('H'); - duration = duration.minusHours(hours); - } - - final long minutes = duration.toMinutes(); - if (minutes > 0) { - if (hours == 0) { - builder.append('T'); - } - - builder.append(minutes); - builder.append('M'); - duration = duration.minusMinutes(minutes); - } - - final long seconds = duration.getSeconds(); - if (seconds > 0) { - if (hours == 0 && minutes == 0) { - builder.append('T'); - } - - builder.append(seconds); - duration = duration.minusSeconds(seconds); - } - - long milliseconds = duration.toMillis(); - if (milliseconds > 0) { - if (hours == 0 && minutes == 0 && seconds == 0) { - builder.append("T"); - } - - if (seconds == 0) { - builder.append("0"); - } - - builder.append('.'); - - if (milliseconds <= 99) { - builder.append('0'); - - if (milliseconds <= 9) { - builder.append('0'); - } - } - - // Remove trailing zeros. - while (milliseconds % 10 == 0) { - milliseconds /= 10; - } - builder.append(milliseconds); - } - - if (seconds > 0 || milliseconds > 0) { - builder.append('S'); - } - - return builder.toString(); - } -} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/implementation/DataSourcesImpl.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/implementation/DataSourcesImpl.java deleted file mode 100644 index 45c3e4f26005..000000000000 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/implementation/DataSourcesImpl.java +++ /dev/null @@ -1,815 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -package com.azure.search.documents.indexes.implementation; - -import com.azure.core.annotation.BodyParam; -import com.azure.core.annotation.Delete; -import com.azure.core.annotation.ExpectedResponses; -import com.azure.core.annotation.Get; -import com.azure.core.annotation.HeaderParam; -import com.azure.core.annotation.Host; -import com.azure.core.annotation.HostParam; -import com.azure.core.annotation.PathParam; -import com.azure.core.annotation.Post; -import com.azure.core.annotation.Put; -import com.azure.core.annotation.QueryParam; -import com.azure.core.annotation.ReturnType; -import com.azure.core.annotation.ServiceInterface; -import com.azure.core.annotation.ServiceMethod; -import com.azure.core.annotation.UnexpectedResponseExceptionType; -import com.azure.core.http.rest.Response; -import com.azure.core.http.rest.RestProxy; -import com.azure.core.util.Context; -import com.azure.core.util.FluxUtil; -import com.azure.search.documents.indexes.implementation.models.ErrorResponseException; -import com.azure.search.documents.indexes.implementation.models.ListDataSourcesResult; -import com.azure.search.documents.indexes.implementation.models.RequestOptions; -import com.azure.search.documents.indexes.models.SearchIndexerDataSourceConnection; -import java.util.UUID; -import reactor.core.publisher.Mono; - -/** - * An instance of this class provides access to all the operations defined in DataSources. - */ -public final class DataSourcesImpl { - /** - * The proxy service used to perform REST calls. - */ - private final DataSourcesService service; - - /** - * The service client containing this operation class. - */ - private final SearchServiceClientImpl client; - - /** - * Initializes an instance of DataSourcesImpl. - * - * @param client the instance of the service client containing this operation class. - */ - DataSourcesImpl(SearchServiceClientImpl client) { - this.service - = RestProxy.create(DataSourcesService.class, client.getHttpPipeline(), client.getSerializerAdapter()); - this.client = client; - } - - /** - * The interface defining all the services for SearchServiceClientDataSources to be used by the proxy service to - * perform REST calls. - */ - @Host("{endpoint}") - @ServiceInterface(name = "SearchServiceClientD") - public interface DataSourcesService { - @Put("/datasources('{dataSourceName}')") - @ExpectedResponses({ 200, 201 }) - @UnexpectedResponseExceptionType(ErrorResponseException.class) - Mono> createOrUpdate(@HostParam("endpoint") String endpoint, - @PathParam("dataSourceName") String dataSourceName, - @HeaderParam("x-ms-client-request-id") UUID xMsClientRequestId, @HeaderParam("If-Match") String ifMatch, - @HeaderParam("If-None-Match") String ifNoneMatch, @HeaderParam("Prefer") String prefer, - @QueryParam("api-version") String apiVersion, - @QueryParam("ignoreResetRequirements") Boolean skipIndexerResetRequirementForCache, - @HeaderParam("Accept") String accept, - @BodyParam("application/json") SearchIndexerDataSourceConnection dataSource, Context context); - - @Put("/datasources('{dataSourceName}')") - @ExpectedResponses({ 200, 201 }) - @UnexpectedResponseExceptionType(ErrorResponseException.class) - Response createOrUpdateSync(@HostParam("endpoint") String endpoint, - @PathParam("dataSourceName") String dataSourceName, - @HeaderParam("x-ms-client-request-id") UUID xMsClientRequestId, @HeaderParam("If-Match") String ifMatch, - @HeaderParam("If-None-Match") String ifNoneMatch, @HeaderParam("Prefer") String prefer, - @QueryParam("api-version") String apiVersion, - @QueryParam("ignoreResetRequirements") Boolean skipIndexerResetRequirementForCache, - @HeaderParam("Accept") String accept, - @BodyParam("application/json") SearchIndexerDataSourceConnection dataSource, Context context); - - @Delete("/datasources('{dataSourceName}')") - @ExpectedResponses({ 204, 404 }) - @UnexpectedResponseExceptionType(ErrorResponseException.class) - Mono> delete(@HostParam("endpoint") String endpoint, - @PathParam("dataSourceName") String dataSourceName, - @HeaderParam("x-ms-client-request-id") UUID xMsClientRequestId, @HeaderParam("If-Match") String ifMatch, - @HeaderParam("If-None-Match") String ifNoneMatch, @QueryParam("api-version") String apiVersion, - @HeaderParam("Accept") String accept, Context context); - - @Delete("/datasources('{dataSourceName}')") - @ExpectedResponses({ 204, 404 }) - @UnexpectedResponseExceptionType(ErrorResponseException.class) - Response deleteSync(@HostParam("endpoint") String endpoint, - @PathParam("dataSourceName") String dataSourceName, - @HeaderParam("x-ms-client-request-id") UUID xMsClientRequestId, @HeaderParam("If-Match") String ifMatch, - @HeaderParam("If-None-Match") String ifNoneMatch, @QueryParam("api-version") String apiVersion, - @HeaderParam("Accept") String accept, Context context); - - @Get("/datasources('{dataSourceName}')") - @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(ErrorResponseException.class) - Mono> get(@HostParam("endpoint") String endpoint, - @PathParam("dataSourceName") String dataSourceName, - @HeaderParam("x-ms-client-request-id") UUID xMsClientRequestId, - @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, Context context); - - @Get("/datasources('{dataSourceName}')") - @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(ErrorResponseException.class) - Response getSync(@HostParam("endpoint") String endpoint, - @PathParam("dataSourceName") String dataSourceName, - @HeaderParam("x-ms-client-request-id") UUID xMsClientRequestId, - @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, Context context); - - @Get("/datasources") - @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(ErrorResponseException.class) - Mono> list(@HostParam("endpoint") String endpoint, - @QueryParam("$select") String select, @HeaderParam("x-ms-client-request-id") UUID xMsClientRequestId, - @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, Context context); - - @Get("/datasources") - @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(ErrorResponseException.class) - Response listSync(@HostParam("endpoint") String endpoint, - @QueryParam("$select") String select, @HeaderParam("x-ms-client-request-id") UUID xMsClientRequestId, - @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, Context context); - - @Post("/datasources") - @ExpectedResponses({ 201 }) - @UnexpectedResponseExceptionType(ErrorResponseException.class) - Mono> create(@HostParam("endpoint") String endpoint, - @HeaderParam("x-ms-client-request-id") UUID xMsClientRequestId, - @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, - @BodyParam("application/json") SearchIndexerDataSourceConnection dataSource, Context context); - - @Post("/datasources") - @ExpectedResponses({ 201 }) - @UnexpectedResponseExceptionType(ErrorResponseException.class) - Response createSync(@HostParam("endpoint") String endpoint, - @HeaderParam("x-ms-client-request-id") UUID xMsClientRequestId, - @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, - @BodyParam("application/json") SearchIndexerDataSourceConnection dataSource, Context context); - } - - /** - * Creates a new datasource or updates a datasource if it already exists. - * - * @param dataSourceName The name of the datasource to create or update. - * @param dataSource The definition of the datasource to create or update. - * @param ifMatch Defines the If-Match condition. The operation will be performed only if the ETag on the server - * matches this value. - * @param ifNoneMatch Defines the If-None-Match condition. The operation will be performed only if the ETag on the - * server does not match this value. - * @param skipIndexerResetRequirementForCache Ignores cache reset requirements. - * @param requestOptions Parameter group. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return represents a datasource definition, which can be used to configure an indexer along with {@link Response} - * on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> createOrUpdateWithResponseAsync(String dataSourceName, - SearchIndexerDataSourceConnection dataSource, String ifMatch, String ifNoneMatch, - Boolean skipIndexerResetRequirementForCache, RequestOptions requestOptions) { - return FluxUtil.withContext(context -> createOrUpdateWithResponseAsync(dataSourceName, dataSource, ifMatch, - ifNoneMatch, skipIndexerResetRequirementForCache, requestOptions, context)); - } - - /** - * Creates a new datasource or updates a datasource if it already exists. - * - * @param dataSourceName The name of the datasource to create or update. - * @param dataSource The definition of the datasource to create or update. - * @param ifMatch Defines the If-Match condition. The operation will be performed only if the ETag on the server - * matches this value. - * @param ifNoneMatch Defines the If-None-Match condition. The operation will be performed only if the ETag on the - * server does not match this value. - * @param skipIndexerResetRequirementForCache Ignores cache reset requirements. - * @param requestOptions Parameter group. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return represents a datasource definition, which can be used to configure an indexer along with {@link Response} - * on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> createOrUpdateWithResponseAsync(String dataSourceName, - SearchIndexerDataSourceConnection dataSource, String ifMatch, String ifNoneMatch, - Boolean skipIndexerResetRequirementForCache, RequestOptions requestOptions, Context context) { - final String prefer = "return=representation"; - final String accept = "application/json; odata.metadata=minimal"; - UUID xMsClientRequestIdInternal = null; - if (requestOptions != null) { - xMsClientRequestIdInternal = requestOptions.getXMsClientRequestId(); - } - UUID xMsClientRequestId = xMsClientRequestIdInternal; - return service.createOrUpdate(this.client.getEndpoint(), dataSourceName, xMsClientRequestId, ifMatch, - ifNoneMatch, prefer, this.client.getApiVersion(), skipIndexerResetRequirementForCache, accept, dataSource, - context); - } - - /** - * Creates a new datasource or updates a datasource if it already exists. - * - * @param dataSourceName The name of the datasource to create or update. - * @param dataSource The definition of the datasource to create or update. - * @param ifMatch Defines the If-Match condition. The operation will be performed only if the ETag on the server - * matches this value. - * @param ifNoneMatch Defines the If-None-Match condition. The operation will be performed only if the ETag on the - * server does not match this value. - * @param skipIndexerResetRequirementForCache Ignores cache reset requirements. - * @param requestOptions Parameter group. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return represents a datasource definition, which can be used to configure an indexer on successful completion of - * {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono createOrUpdateAsync(String dataSourceName, - SearchIndexerDataSourceConnection dataSource, String ifMatch, String ifNoneMatch, - Boolean skipIndexerResetRequirementForCache, RequestOptions requestOptions) { - return createOrUpdateWithResponseAsync(dataSourceName, dataSource, ifMatch, ifNoneMatch, - skipIndexerResetRequirementForCache, requestOptions).flatMap(res -> Mono.justOrEmpty(res.getValue())); - } - - /** - * Creates a new datasource or updates a datasource if it already exists. - * - * @param dataSourceName The name of the datasource to create or update. - * @param dataSource The definition of the datasource to create or update. - * @param ifMatch Defines the If-Match condition. The operation will be performed only if the ETag on the server - * matches this value. - * @param ifNoneMatch Defines the If-None-Match condition. The operation will be performed only if the ETag on the - * server does not match this value. - * @param skipIndexerResetRequirementForCache Ignores cache reset requirements. - * @param requestOptions Parameter group. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return represents a datasource definition, which can be used to configure an indexer on successful completion of - * {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono createOrUpdateAsync(String dataSourceName, - SearchIndexerDataSourceConnection dataSource, String ifMatch, String ifNoneMatch, - Boolean skipIndexerResetRequirementForCache, RequestOptions requestOptions, Context context) { - return createOrUpdateWithResponseAsync(dataSourceName, dataSource, ifMatch, ifNoneMatch, - skipIndexerResetRequirementForCache, requestOptions, context) - .flatMap(res -> Mono.justOrEmpty(res.getValue())); - } - - /** - * Creates a new datasource or updates a datasource if it already exists. - * - * @param dataSourceName The name of the datasource to create or update. - * @param dataSource The definition of the datasource to create or update. - * @param ifMatch Defines the If-Match condition. The operation will be performed only if the ETag on the server - * matches this value. - * @param ifNoneMatch Defines the If-None-Match condition. The operation will be performed only if the ETag on the - * server does not match this value. - * @param skipIndexerResetRequirementForCache Ignores cache reset requirements. - * @param requestOptions Parameter group. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return represents a datasource definition, which can be used to configure an indexer along with - * {@link Response}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Response createOrUpdateWithResponse(String dataSourceName, - SearchIndexerDataSourceConnection dataSource, String ifMatch, String ifNoneMatch, - Boolean skipIndexerResetRequirementForCache, RequestOptions requestOptions, Context context) { - final String prefer = "return=representation"; - final String accept = "application/json; odata.metadata=minimal"; - UUID xMsClientRequestIdInternal = null; - if (requestOptions != null) { - xMsClientRequestIdInternal = requestOptions.getXMsClientRequestId(); - } - UUID xMsClientRequestId = xMsClientRequestIdInternal; - return service.createOrUpdateSync(this.client.getEndpoint(), dataSourceName, xMsClientRequestId, ifMatch, - ifNoneMatch, prefer, this.client.getApiVersion(), skipIndexerResetRequirementForCache, accept, dataSource, - context); - } - - /** - * Creates a new datasource or updates a datasource if it already exists. - * - * @param dataSourceName The name of the datasource to create or update. - * @param dataSource The definition of the datasource to create or update. - * @param ifMatch Defines the If-Match condition. The operation will be performed only if the ETag on the server - * matches this value. - * @param ifNoneMatch Defines the If-None-Match condition. The operation will be performed only if the ETag on the - * server does not match this value. - * @param skipIndexerResetRequirementForCache Ignores cache reset requirements. - * @param requestOptions Parameter group. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return represents a datasource definition, which can be used to configure an indexer. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public SearchIndexerDataSourceConnection createOrUpdate(String dataSourceName, - SearchIndexerDataSourceConnection dataSource, String ifMatch, String ifNoneMatch, - Boolean skipIndexerResetRequirementForCache, RequestOptions requestOptions) { - return createOrUpdateWithResponse(dataSourceName, dataSource, ifMatch, ifNoneMatch, - skipIndexerResetRequirementForCache, requestOptions, Context.NONE).getValue(); - } - - /** - * Deletes a datasource. - * - * @param dataSourceName The name of the datasource to delete. - * @param ifMatch Defines the If-Match condition. The operation will be performed only if the ETag on the server - * matches this value. - * @param ifNoneMatch Defines the If-None-Match condition. The operation will be performed only if the ETag on the - * server does not match this value. - * @param requestOptions Parameter group. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the {@link Response} on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> deleteWithResponseAsync(String dataSourceName, String ifMatch, String ifNoneMatch, - RequestOptions requestOptions) { - return FluxUtil.withContext( - context -> deleteWithResponseAsync(dataSourceName, ifMatch, ifNoneMatch, requestOptions, context)); - } - - /** - * Deletes a datasource. - * - * @param dataSourceName The name of the datasource to delete. - * @param ifMatch Defines the If-Match condition. The operation will be performed only if the ETag on the server - * matches this value. - * @param ifNoneMatch Defines the If-None-Match condition. The operation will be performed only if the ETag on the - * server does not match this value. - * @param requestOptions Parameter group. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the {@link Response} on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> deleteWithResponseAsync(String dataSourceName, String ifMatch, String ifNoneMatch, - RequestOptions requestOptions, Context context) { - final String accept = "application/json; odata.metadata=minimal"; - UUID xMsClientRequestIdInternal = null; - if (requestOptions != null) { - xMsClientRequestIdInternal = requestOptions.getXMsClientRequestId(); - } - UUID xMsClientRequestId = xMsClientRequestIdInternal; - return service.delete(this.client.getEndpoint(), dataSourceName, xMsClientRequestId, ifMatch, ifNoneMatch, - this.client.getApiVersion(), accept, context); - } - - /** - * Deletes a datasource. - * - * @param dataSourceName The name of the datasource to delete. - * @param ifMatch Defines the If-Match condition. The operation will be performed only if the ETag on the server - * matches this value. - * @param ifNoneMatch Defines the If-None-Match condition. The operation will be performed only if the ETag on the - * server does not match this value. - * @param requestOptions Parameter group. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return A {@link Mono} that completes when a successful response is received. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono deleteAsync(String dataSourceName, String ifMatch, String ifNoneMatch, - RequestOptions requestOptions) { - return deleteWithResponseAsync(dataSourceName, ifMatch, ifNoneMatch, requestOptions) - .flatMap(ignored -> Mono.empty()); - } - - /** - * Deletes a datasource. - * - * @param dataSourceName The name of the datasource to delete. - * @param ifMatch Defines the If-Match condition. The operation will be performed only if the ETag on the server - * matches this value. - * @param ifNoneMatch Defines the If-None-Match condition. The operation will be performed only if the ETag on the - * server does not match this value. - * @param requestOptions Parameter group. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return A {@link Mono} that completes when a successful response is received. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono deleteAsync(String dataSourceName, String ifMatch, String ifNoneMatch, - RequestOptions requestOptions, Context context) { - return deleteWithResponseAsync(dataSourceName, ifMatch, ifNoneMatch, requestOptions, context) - .flatMap(ignored -> Mono.empty()); - } - - /** - * Deletes a datasource. - * - * @param dataSourceName The name of the datasource to delete. - * @param ifMatch Defines the If-Match condition. The operation will be performed only if the ETag on the server - * matches this value. - * @param ifNoneMatch Defines the If-None-Match condition. The operation will be performed only if the ETag on the - * server does not match this value. - * @param requestOptions Parameter group. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the {@link Response}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Response deleteWithResponse(String dataSourceName, String ifMatch, String ifNoneMatch, - RequestOptions requestOptions, Context context) { - final String accept = "application/json; odata.metadata=minimal"; - UUID xMsClientRequestIdInternal = null; - if (requestOptions != null) { - xMsClientRequestIdInternal = requestOptions.getXMsClientRequestId(); - } - UUID xMsClientRequestId = xMsClientRequestIdInternal; - return service.deleteSync(this.client.getEndpoint(), dataSourceName, xMsClientRequestId, ifMatch, ifNoneMatch, - this.client.getApiVersion(), accept, context); - } - - /** - * Deletes a datasource. - * - * @param dataSourceName The name of the datasource to delete. - * @param ifMatch Defines the If-Match condition. The operation will be performed only if the ETag on the server - * matches this value. - * @param ifNoneMatch Defines the If-None-Match condition. The operation will be performed only if the ETag on the - * server does not match this value. - * @param requestOptions Parameter group. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public void delete(String dataSourceName, String ifMatch, String ifNoneMatch, RequestOptions requestOptions) { - deleteWithResponse(dataSourceName, ifMatch, ifNoneMatch, requestOptions, Context.NONE); - } - - /** - * Retrieves a datasource definition. - * - * @param dataSourceName The name of the datasource to retrieve. - * @param requestOptions Parameter group. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return represents a datasource definition, which can be used to configure an indexer along with {@link Response} - * on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> getWithResponseAsync(String dataSourceName, - RequestOptions requestOptions) { - return FluxUtil.withContext(context -> getWithResponseAsync(dataSourceName, requestOptions, context)); - } - - /** - * Retrieves a datasource definition. - * - * @param dataSourceName The name of the datasource to retrieve. - * @param requestOptions Parameter group. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return represents a datasource definition, which can be used to configure an indexer along with {@link Response} - * on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> getWithResponseAsync(String dataSourceName, - RequestOptions requestOptions, Context context) { - final String accept = "application/json; odata.metadata=minimal"; - UUID xMsClientRequestIdInternal = null; - if (requestOptions != null) { - xMsClientRequestIdInternal = requestOptions.getXMsClientRequestId(); - } - UUID xMsClientRequestId = xMsClientRequestIdInternal; - return service.get(this.client.getEndpoint(), dataSourceName, xMsClientRequestId, this.client.getApiVersion(), - accept, context); - } - - /** - * Retrieves a datasource definition. - * - * @param dataSourceName The name of the datasource to retrieve. - * @param requestOptions Parameter group. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return represents a datasource definition, which can be used to configure an indexer on successful completion of - * {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono getAsync(String dataSourceName, RequestOptions requestOptions) { - return getWithResponseAsync(dataSourceName, requestOptions).flatMap(res -> Mono.justOrEmpty(res.getValue())); - } - - /** - * Retrieves a datasource definition. - * - * @param dataSourceName The name of the datasource to retrieve. - * @param requestOptions Parameter group. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return represents a datasource definition, which can be used to configure an indexer on successful completion of - * {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono getAsync(String dataSourceName, RequestOptions requestOptions, - Context context) { - return getWithResponseAsync(dataSourceName, requestOptions, context) - .flatMap(res -> Mono.justOrEmpty(res.getValue())); - } - - /** - * Retrieves a datasource definition. - * - * @param dataSourceName The name of the datasource to retrieve. - * @param requestOptions Parameter group. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return represents a datasource definition, which can be used to configure an indexer along with - * {@link Response}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Response getWithResponse(String dataSourceName, - RequestOptions requestOptions, Context context) { - final String accept = "application/json; odata.metadata=minimal"; - UUID xMsClientRequestIdInternal = null; - if (requestOptions != null) { - xMsClientRequestIdInternal = requestOptions.getXMsClientRequestId(); - } - UUID xMsClientRequestId = xMsClientRequestIdInternal; - return service.getSync(this.client.getEndpoint(), dataSourceName, xMsClientRequestId, - this.client.getApiVersion(), accept, context); - } - - /** - * Retrieves a datasource definition. - * - * @param dataSourceName The name of the datasource to retrieve. - * @param requestOptions Parameter group. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return represents a datasource definition, which can be used to configure an indexer. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public SearchIndexerDataSourceConnection get(String dataSourceName, RequestOptions requestOptions) { - return getWithResponse(dataSourceName, requestOptions, Context.NONE).getValue(); - } - - /** - * Lists all datasources available for a search service. - * - * @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. - * @param requestOptions Parameter group. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return response from a List Datasources request along with {@link Response} on successful completion of - * {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> listWithResponseAsync(String select, RequestOptions requestOptions) { - return FluxUtil.withContext(context -> listWithResponseAsync(select, requestOptions, context)); - } - - /** - * Lists all datasources available for a search service. - * - * @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. - * @param requestOptions Parameter group. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return response from a List Datasources request along with {@link Response} on successful completion of - * {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> listWithResponseAsync(String select, RequestOptions requestOptions, - Context context) { - final String accept = "application/json; odata.metadata=minimal"; - UUID xMsClientRequestIdInternal = null; - if (requestOptions != null) { - xMsClientRequestIdInternal = requestOptions.getXMsClientRequestId(); - } - UUID xMsClientRequestId = xMsClientRequestIdInternal; - return service.list(this.client.getEndpoint(), select, xMsClientRequestId, this.client.getApiVersion(), accept, - context); - } - - /** - * Lists all datasources available for a search service. - * - * @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. - * @param requestOptions Parameter group. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return response from a List Datasources request on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono listAsync(String select, RequestOptions requestOptions) { - return listWithResponseAsync(select, requestOptions).flatMap(res -> Mono.justOrEmpty(res.getValue())); - } - - /** - * Lists all datasources available for a search service. - * - * @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. - * @param requestOptions Parameter group. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return response from a List Datasources request on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono listAsync(String select, RequestOptions requestOptions, Context context) { - return listWithResponseAsync(select, requestOptions, context).flatMap(res -> Mono.justOrEmpty(res.getValue())); - } - - /** - * Lists all datasources available for a search service. - * - * @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. - * @param requestOptions Parameter group. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return response from a List Datasources request along with {@link Response}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Response listWithResponse(String select, RequestOptions requestOptions, - Context context) { - final String accept = "application/json; odata.metadata=minimal"; - UUID xMsClientRequestIdInternal = null; - if (requestOptions != null) { - xMsClientRequestIdInternal = requestOptions.getXMsClientRequestId(); - } - UUID xMsClientRequestId = xMsClientRequestIdInternal; - return service.listSync(this.client.getEndpoint(), select, xMsClientRequestId, this.client.getApiVersion(), - accept, context); - } - - /** - * Lists all datasources available for a search service. - * - * @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. - * @param requestOptions Parameter group. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return response from a List Datasources request. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public ListDataSourcesResult list(String select, RequestOptions requestOptions) { - return listWithResponse(select, requestOptions, Context.NONE).getValue(); - } - - /** - * Creates a new datasource. - * - * @param dataSource The definition of the datasource to create. - * @param requestOptions Parameter group. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return represents a datasource definition, which can be used to configure an indexer along with {@link Response} - * on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> - createWithResponseAsync(SearchIndexerDataSourceConnection dataSource, RequestOptions requestOptions) { - return FluxUtil.withContext(context -> createWithResponseAsync(dataSource, requestOptions, context)); - } - - /** - * Creates a new datasource. - * - * @param dataSource The definition of the datasource to create. - * @param requestOptions Parameter group. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return represents a datasource definition, which can be used to configure an indexer along with {@link Response} - * on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> createWithResponseAsync( - SearchIndexerDataSourceConnection dataSource, RequestOptions requestOptions, Context context) { - final String accept = "application/json; odata.metadata=minimal"; - UUID xMsClientRequestIdInternal = null; - if (requestOptions != null) { - xMsClientRequestIdInternal = requestOptions.getXMsClientRequestId(); - } - UUID xMsClientRequestId = xMsClientRequestIdInternal; - return service.create(this.client.getEndpoint(), xMsClientRequestId, this.client.getApiVersion(), accept, - dataSource, context); - } - - /** - * Creates a new datasource. - * - * @param dataSource The definition of the datasource to create. - * @param requestOptions Parameter group. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return represents a datasource definition, which can be used to configure an indexer on successful completion of - * {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono createAsync(SearchIndexerDataSourceConnection dataSource, - RequestOptions requestOptions) { - return createWithResponseAsync(dataSource, requestOptions).flatMap(res -> Mono.justOrEmpty(res.getValue())); - } - - /** - * Creates a new datasource. - * - * @param dataSource The definition of the datasource to create. - * @param requestOptions Parameter group. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return represents a datasource definition, which can be used to configure an indexer on successful completion of - * {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono createAsync(SearchIndexerDataSourceConnection dataSource, - RequestOptions requestOptions, Context context) { - return createWithResponseAsync(dataSource, requestOptions, context) - .flatMap(res -> Mono.justOrEmpty(res.getValue())); - } - - /** - * Creates a new datasource. - * - * @param dataSource The definition of the datasource to create. - * @param requestOptions Parameter group. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return represents a datasource definition, which can be used to configure an indexer along with - * {@link Response}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Response createWithResponse(SearchIndexerDataSourceConnection dataSource, - RequestOptions requestOptions, Context context) { - final String accept = "application/json; odata.metadata=minimal"; - UUID xMsClientRequestIdInternal = null; - if (requestOptions != null) { - xMsClientRequestIdInternal = requestOptions.getXMsClientRequestId(); - } - UUID xMsClientRequestId = xMsClientRequestIdInternal; - return service.createSync(this.client.getEndpoint(), xMsClientRequestId, this.client.getApiVersion(), accept, - dataSource, context); - } - - /** - * Creates a new datasource. - * - * @param dataSource The definition of the datasource to create. - * @param requestOptions Parameter group. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return represents a datasource definition, which can be used to configure an indexer. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public SearchIndexerDataSourceConnection create(SearchIndexerDataSourceConnection dataSource, - RequestOptions requestOptions) { - return createWithResponse(dataSource, requestOptions, Context.NONE).getValue(); - } -} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/implementation/IndexersImpl.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/implementation/IndexersImpl.java deleted file mode 100644 index 966d17df801d..000000000000 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/implementation/IndexersImpl.java +++ /dev/null @@ -1,1329 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -package com.azure.search.documents.indexes.implementation; - -import com.azure.core.annotation.BodyParam; -import com.azure.core.annotation.Delete; -import com.azure.core.annotation.ExpectedResponses; -import com.azure.core.annotation.Get; -import com.azure.core.annotation.HeaderParam; -import com.azure.core.annotation.Host; -import com.azure.core.annotation.HostParam; -import com.azure.core.annotation.PathParam; -import com.azure.core.annotation.Post; -import com.azure.core.annotation.Put; -import com.azure.core.annotation.QueryParam; -import com.azure.core.annotation.ReturnType; -import com.azure.core.annotation.ServiceInterface; -import com.azure.core.annotation.ServiceMethod; -import com.azure.core.annotation.UnexpectedResponseExceptionType; -import com.azure.core.http.rest.Response; -import com.azure.core.http.rest.RestProxy; -import com.azure.core.util.Context; -import com.azure.core.util.FluxUtil; -import com.azure.search.documents.indexes.implementation.models.DocumentKeysOrIds; -import com.azure.search.documents.indexes.implementation.models.ErrorResponseException; -import com.azure.search.documents.indexes.implementation.models.ListIndexersResult; -import com.azure.search.documents.indexes.implementation.models.RequestOptions; -import com.azure.search.documents.indexes.models.SearchIndexer; -import com.azure.search.documents.indexes.models.SearchIndexerStatus; -import java.util.UUID; -import reactor.core.publisher.Mono; - -/** - * An instance of this class provides access to all the operations defined in Indexers. - */ -public final class IndexersImpl { - /** - * The proxy service used to perform REST calls. - */ - private final IndexersService service; - - /** - * The service client containing this operation class. - */ - private final SearchServiceClientImpl client; - - /** - * Initializes an instance of IndexersImpl. - * - * @param client the instance of the service client containing this operation class. - */ - IndexersImpl(SearchServiceClientImpl client) { - this.service = RestProxy.create(IndexersService.class, client.getHttpPipeline(), client.getSerializerAdapter()); - this.client = client; - } - - /** - * The interface defining all the services for SearchServiceClientIndexers to be used by the proxy service to - * perform REST calls. - */ - @Host("{endpoint}") - @ServiceInterface(name = "SearchServiceClientI") - public interface IndexersService { - @Post("/indexers('{indexerName}')/search.reset") - @ExpectedResponses({ 204 }) - @UnexpectedResponseExceptionType(ErrorResponseException.class) - Mono> reset(@HostParam("endpoint") String endpoint, @PathParam("indexerName") String indexerName, - @HeaderParam("x-ms-client-request-id") UUID xMsClientRequestId, - @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, Context context); - - @Post("/indexers('{indexerName}')/search.reset") - @ExpectedResponses({ 204 }) - @UnexpectedResponseExceptionType(ErrorResponseException.class) - Response resetSync(@HostParam("endpoint") String endpoint, @PathParam("indexerName") String indexerName, - @HeaderParam("x-ms-client-request-id") UUID xMsClientRequestId, - @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, Context context); - - @Post("/indexers('{indexerName}')/search.resetdocs") - @ExpectedResponses({ 204 }) - @UnexpectedResponseExceptionType(ErrorResponseException.class) - Mono> resetDocs(@HostParam("endpoint") String endpoint, - @PathParam("indexerName") String indexerName, @QueryParam("overwrite") Boolean overwrite, - @HeaderParam("x-ms-client-request-id") UUID xMsClientRequestId, - @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, - @BodyParam("application/json") DocumentKeysOrIds keysOrIds, Context context); - - @Post("/indexers('{indexerName}')/search.resetdocs") - @ExpectedResponses({ 204 }) - @UnexpectedResponseExceptionType(ErrorResponseException.class) - Response resetDocsSync(@HostParam("endpoint") String endpoint, - @PathParam("indexerName") String indexerName, @QueryParam("overwrite") Boolean overwrite, - @HeaderParam("x-ms-client-request-id") UUID xMsClientRequestId, - @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, - @BodyParam("application/json") DocumentKeysOrIds keysOrIds, Context context); - - @Post("/indexers('{indexerName}')/search.run") - @ExpectedResponses({ 202 }) - @UnexpectedResponseExceptionType(ErrorResponseException.class) - Mono> run(@HostParam("endpoint") String endpoint, @PathParam("indexerName") String indexerName, - @HeaderParam("x-ms-client-request-id") UUID xMsClientRequestId, - @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, Context context); - - @Post("/indexers('{indexerName}')/search.run") - @ExpectedResponses({ 202 }) - @UnexpectedResponseExceptionType(ErrorResponseException.class) - Response runSync(@HostParam("endpoint") String endpoint, @PathParam("indexerName") String indexerName, - @HeaderParam("x-ms-client-request-id") UUID xMsClientRequestId, - @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, Context context); - - @Put("/indexers('{indexerName}')") - @ExpectedResponses({ 200, 201 }) - @UnexpectedResponseExceptionType(ErrorResponseException.class) - Mono> createOrUpdate(@HostParam("endpoint") String endpoint, - @PathParam("indexerName") String indexerName, - @HeaderParam("x-ms-client-request-id") UUID xMsClientRequestId, @HeaderParam("If-Match") String ifMatch, - @HeaderParam("If-None-Match") String ifNoneMatch, @HeaderParam("Prefer") String prefer, - @QueryParam("api-version") String apiVersion, - @QueryParam("ignoreResetRequirements") Boolean skipIndexerResetRequirementForCache, - @QueryParam("disableCacheReprocessingChangeDetection") Boolean disableCacheReprocessingChangeDetection, - @HeaderParam("Accept") String accept, @BodyParam("application/json") SearchIndexer indexer, - Context context); - - @Put("/indexers('{indexerName}')") - @ExpectedResponses({ 200, 201 }) - @UnexpectedResponseExceptionType(ErrorResponseException.class) - Response createOrUpdateSync(@HostParam("endpoint") String endpoint, - @PathParam("indexerName") String indexerName, - @HeaderParam("x-ms-client-request-id") UUID xMsClientRequestId, @HeaderParam("If-Match") String ifMatch, - @HeaderParam("If-None-Match") String ifNoneMatch, @HeaderParam("Prefer") String prefer, - @QueryParam("api-version") String apiVersion, - @QueryParam("ignoreResetRequirements") Boolean skipIndexerResetRequirementForCache, - @QueryParam("disableCacheReprocessingChangeDetection") Boolean disableCacheReprocessingChangeDetection, - @HeaderParam("Accept") String accept, @BodyParam("application/json") SearchIndexer indexer, - Context context); - - @Delete("/indexers('{indexerName}')") - @ExpectedResponses({ 204, 404 }) - @UnexpectedResponseExceptionType(ErrorResponseException.class) - Mono> delete(@HostParam("endpoint") String endpoint, - @PathParam("indexerName") String indexerName, - @HeaderParam("x-ms-client-request-id") UUID xMsClientRequestId, @HeaderParam("If-Match") String ifMatch, - @HeaderParam("If-None-Match") String ifNoneMatch, @QueryParam("api-version") String apiVersion, - @HeaderParam("Accept") String accept, Context context); - - @Delete("/indexers('{indexerName}')") - @ExpectedResponses({ 204, 404 }) - @UnexpectedResponseExceptionType(ErrorResponseException.class) - Response deleteSync(@HostParam("endpoint") String endpoint, @PathParam("indexerName") String indexerName, - @HeaderParam("x-ms-client-request-id") UUID xMsClientRequestId, @HeaderParam("If-Match") String ifMatch, - @HeaderParam("If-None-Match") String ifNoneMatch, @QueryParam("api-version") String apiVersion, - @HeaderParam("Accept") String accept, Context context); - - @Get("/indexers('{indexerName}')") - @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(ErrorResponseException.class) - Mono> get(@HostParam("endpoint") String endpoint, - @PathParam("indexerName") String indexerName, - @HeaderParam("x-ms-client-request-id") UUID xMsClientRequestId, - @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, Context context); - - @Get("/indexers('{indexerName}')") - @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(ErrorResponseException.class) - Response getSync(@HostParam("endpoint") String endpoint, - @PathParam("indexerName") String indexerName, - @HeaderParam("x-ms-client-request-id") UUID xMsClientRequestId, - @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, Context context); - - @Get("/indexers") - @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(ErrorResponseException.class) - Mono> list(@HostParam("endpoint") String endpoint, - @QueryParam("$select") String select, @HeaderParam("x-ms-client-request-id") UUID xMsClientRequestId, - @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, Context context); - - @Get("/indexers") - @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(ErrorResponseException.class) - Response listSync(@HostParam("endpoint") String endpoint, - @QueryParam("$select") String select, @HeaderParam("x-ms-client-request-id") UUID xMsClientRequestId, - @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, Context context); - - @Post("/indexers") - @ExpectedResponses({ 201 }) - @UnexpectedResponseExceptionType(ErrorResponseException.class) - Mono> create(@HostParam("endpoint") String endpoint, - @HeaderParam("x-ms-client-request-id") UUID xMsClientRequestId, - @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, - @BodyParam("application/json") SearchIndexer indexer, Context context); - - @Post("/indexers") - @ExpectedResponses({ 201 }) - @UnexpectedResponseExceptionType(ErrorResponseException.class) - Response createSync(@HostParam("endpoint") String endpoint, - @HeaderParam("x-ms-client-request-id") UUID xMsClientRequestId, - @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, - @BodyParam("application/json") SearchIndexer indexer, Context context); - - @Get("/indexers('{indexerName}')/search.status") - @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(ErrorResponseException.class) - Mono> getStatus(@HostParam("endpoint") String endpoint, - @PathParam("indexerName") String indexerName, - @HeaderParam("x-ms-client-request-id") UUID xMsClientRequestId, - @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, Context context); - - @Get("/indexers('{indexerName}')/search.status") - @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(ErrorResponseException.class) - Response getStatusSync(@HostParam("endpoint") String endpoint, - @PathParam("indexerName") String indexerName, - @HeaderParam("x-ms-client-request-id") UUID xMsClientRequestId, - @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, Context context); - } - - /** - * Resets the change tracking state associated with an indexer. - * - * @param indexerName The name of the indexer to reset. - * @param requestOptions Parameter group. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the {@link Response} on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> resetWithResponseAsync(String indexerName, RequestOptions requestOptions) { - return FluxUtil.withContext(context -> resetWithResponseAsync(indexerName, requestOptions, context)); - } - - /** - * Resets the change tracking state associated with an indexer. - * - * @param indexerName The name of the indexer to reset. - * @param requestOptions Parameter group. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the {@link Response} on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> resetWithResponseAsync(String indexerName, RequestOptions requestOptions, - Context context) { - final String accept = "application/json; odata.metadata=minimal"; - UUID xMsClientRequestIdInternal = null; - if (requestOptions != null) { - xMsClientRequestIdInternal = requestOptions.getXMsClientRequestId(); - } - UUID xMsClientRequestId = xMsClientRequestIdInternal; - return service.reset(this.client.getEndpoint(), indexerName, xMsClientRequestId, this.client.getApiVersion(), - accept, context); - } - - /** - * Resets the change tracking state associated with an indexer. - * - * @param indexerName The name of the indexer to reset. - * @param requestOptions Parameter group. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return A {@link Mono} that completes when a successful response is received. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono resetAsync(String indexerName, RequestOptions requestOptions) { - return resetWithResponseAsync(indexerName, requestOptions).flatMap(ignored -> Mono.empty()); - } - - /** - * Resets the change tracking state associated with an indexer. - * - * @param indexerName The name of the indexer to reset. - * @param requestOptions Parameter group. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return A {@link Mono} that completes when a successful response is received. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono resetAsync(String indexerName, RequestOptions requestOptions, Context context) { - return resetWithResponseAsync(indexerName, requestOptions, context).flatMap(ignored -> Mono.empty()); - } - - /** - * Resets the change tracking state associated with an indexer. - * - * @param indexerName The name of the indexer to reset. - * @param requestOptions Parameter group. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the {@link Response}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Response resetWithResponse(String indexerName, RequestOptions requestOptions, Context context) { - final String accept = "application/json; odata.metadata=minimal"; - UUID xMsClientRequestIdInternal = null; - if (requestOptions != null) { - xMsClientRequestIdInternal = requestOptions.getXMsClientRequestId(); - } - UUID xMsClientRequestId = xMsClientRequestIdInternal; - return service.resetSync(this.client.getEndpoint(), indexerName, xMsClientRequestId, - this.client.getApiVersion(), accept, context); - } - - /** - * Resets the change tracking state associated with an indexer. - * - * @param indexerName The name of the indexer to reset. - * @param requestOptions Parameter group. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public void reset(String indexerName, RequestOptions requestOptions) { - resetWithResponse(indexerName, requestOptions, Context.NONE); - } - - /** - * Resets specific documents in the datasource to be selectively re-ingested by the indexer. - * - * @param indexerName The name of the indexer to reset documents for. - * @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. - * @param keysOrIds The keysOrIds parameter. - * @param requestOptions Parameter group. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the {@link Response} on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> resetDocsWithResponseAsync(String indexerName, Boolean overwrite, - DocumentKeysOrIds keysOrIds, RequestOptions requestOptions) { - return FluxUtil.withContext( - context -> resetDocsWithResponseAsync(indexerName, overwrite, keysOrIds, requestOptions, context)); - } - - /** - * Resets specific documents in the datasource to be selectively re-ingested by the indexer. - * - * @param indexerName The name of the indexer to reset documents for. - * @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. - * @param keysOrIds The keysOrIds parameter. - * @param requestOptions Parameter group. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the {@link Response} on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> resetDocsWithResponseAsync(String indexerName, Boolean overwrite, - DocumentKeysOrIds keysOrIds, RequestOptions requestOptions, Context context) { - final String accept = "application/json; odata.metadata=minimal"; - UUID xMsClientRequestIdInternal = null; - if (requestOptions != null) { - xMsClientRequestIdInternal = requestOptions.getXMsClientRequestId(); - } - UUID xMsClientRequestId = xMsClientRequestIdInternal; - return service.resetDocs(this.client.getEndpoint(), indexerName, overwrite, xMsClientRequestId, - this.client.getApiVersion(), accept, keysOrIds, context); - } - - /** - * Resets specific documents in the datasource to be selectively re-ingested by the indexer. - * - * @param indexerName The name of the indexer to reset documents for. - * @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. - * @param keysOrIds The keysOrIds parameter. - * @param requestOptions Parameter group. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return A {@link Mono} that completes when a successful response is received. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono resetDocsAsync(String indexerName, Boolean overwrite, DocumentKeysOrIds keysOrIds, - RequestOptions requestOptions) { - return resetDocsWithResponseAsync(indexerName, overwrite, keysOrIds, requestOptions) - .flatMap(ignored -> Mono.empty()); - } - - /** - * Resets specific documents in the datasource to be selectively re-ingested by the indexer. - * - * @param indexerName The name of the indexer to reset documents for. - * @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. - * @param keysOrIds The keysOrIds parameter. - * @param requestOptions Parameter group. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return A {@link Mono} that completes when a successful response is received. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono resetDocsAsync(String indexerName, Boolean overwrite, DocumentKeysOrIds keysOrIds, - RequestOptions requestOptions, Context context) { - return resetDocsWithResponseAsync(indexerName, overwrite, keysOrIds, requestOptions, context) - .flatMap(ignored -> Mono.empty()); - } - - /** - * Resets specific documents in the datasource to be selectively re-ingested by the indexer. - * - * @param indexerName The name of the indexer to reset documents for. - * @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. - * @param keysOrIds The keysOrIds parameter. - * @param requestOptions Parameter group. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the {@link Response}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Response resetDocsWithResponse(String indexerName, Boolean overwrite, DocumentKeysOrIds keysOrIds, - RequestOptions requestOptions, Context context) { - final String accept = "application/json; odata.metadata=minimal"; - UUID xMsClientRequestIdInternal = null; - if (requestOptions != null) { - xMsClientRequestIdInternal = requestOptions.getXMsClientRequestId(); - } - UUID xMsClientRequestId = xMsClientRequestIdInternal; - return service.resetDocsSync(this.client.getEndpoint(), indexerName, overwrite, xMsClientRequestId, - this.client.getApiVersion(), accept, keysOrIds, context); - } - - /** - * Resets specific documents in the datasource to be selectively re-ingested by the indexer. - * - * @param indexerName The name of the indexer to reset documents for. - * @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. - * @param keysOrIds The keysOrIds parameter. - * @param requestOptions Parameter group. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public void resetDocs(String indexerName, Boolean overwrite, DocumentKeysOrIds keysOrIds, - RequestOptions requestOptions) { - resetDocsWithResponse(indexerName, overwrite, keysOrIds, requestOptions, Context.NONE); - } - - /** - * Runs an indexer on-demand. - * - * @param indexerName The name of the indexer to run. - * @param requestOptions Parameter group. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the {@link Response} on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> runWithResponseAsync(String indexerName, RequestOptions requestOptions) { - return FluxUtil.withContext(context -> runWithResponseAsync(indexerName, requestOptions, context)); - } - - /** - * Runs an indexer on-demand. - * - * @param indexerName The name of the indexer to run. - * @param requestOptions Parameter group. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the {@link Response} on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> runWithResponseAsync(String indexerName, RequestOptions requestOptions, - Context context) { - final String accept = "application/json; odata.metadata=minimal"; - UUID xMsClientRequestIdInternal = null; - if (requestOptions != null) { - xMsClientRequestIdInternal = requestOptions.getXMsClientRequestId(); - } - UUID xMsClientRequestId = xMsClientRequestIdInternal; - return service.run(this.client.getEndpoint(), indexerName, xMsClientRequestId, this.client.getApiVersion(), - accept, context); - } - - /** - * Runs an indexer on-demand. - * - * @param indexerName The name of the indexer to run. - * @param requestOptions Parameter group. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return A {@link Mono} that completes when a successful response is received. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono runAsync(String indexerName, RequestOptions requestOptions) { - return runWithResponseAsync(indexerName, requestOptions).flatMap(ignored -> Mono.empty()); - } - - /** - * Runs an indexer on-demand. - * - * @param indexerName The name of the indexer to run. - * @param requestOptions Parameter group. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return A {@link Mono} that completes when a successful response is received. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono runAsync(String indexerName, RequestOptions requestOptions, Context context) { - return runWithResponseAsync(indexerName, requestOptions, context).flatMap(ignored -> Mono.empty()); - } - - /** - * Runs an indexer on-demand. - * - * @param indexerName The name of the indexer to run. - * @param requestOptions Parameter group. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the {@link Response}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Response runWithResponse(String indexerName, RequestOptions requestOptions, Context context) { - final String accept = "application/json; odata.metadata=minimal"; - UUID xMsClientRequestIdInternal = null; - if (requestOptions != null) { - xMsClientRequestIdInternal = requestOptions.getXMsClientRequestId(); - } - UUID xMsClientRequestId = xMsClientRequestIdInternal; - return service.runSync(this.client.getEndpoint(), indexerName, xMsClientRequestId, this.client.getApiVersion(), - accept, context); - } - - /** - * Runs an indexer on-demand. - * - * @param indexerName The name of the indexer to run. - * @param requestOptions Parameter group. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public void run(String indexerName, RequestOptions requestOptions) { - runWithResponse(indexerName, requestOptions, Context.NONE); - } - - /** - * Creates a new indexer or updates an indexer if it already exists. - * - * @param indexerName The name of the indexer to create or update. - * @param indexer The definition of the indexer to create or update. - * @param ifMatch Defines the If-Match condition. The operation will be performed only if the ETag on the server - * matches this value. - * @param ifNoneMatch Defines the If-None-Match condition. The operation will be performed only if the ETag on the - * server does not match this value. - * @param skipIndexerResetRequirementForCache Ignores cache reset requirements. - * @param disableCacheReprocessingChangeDetection Disables cache reprocessing change detection. - * @param requestOptions Parameter group. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return represents an indexer along with {@link Response} on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> createOrUpdateWithResponseAsync(String indexerName, SearchIndexer indexer, - String ifMatch, String ifNoneMatch, Boolean skipIndexerResetRequirementForCache, - Boolean disableCacheReprocessingChangeDetection, RequestOptions requestOptions) { - return FluxUtil - .withContext(context -> createOrUpdateWithResponseAsync(indexerName, indexer, ifMatch, ifNoneMatch, - skipIndexerResetRequirementForCache, disableCacheReprocessingChangeDetection, requestOptions, context)); - } - - /** - * Creates a new indexer or updates an indexer if it already exists. - * - * @param indexerName The name of the indexer to create or update. - * @param indexer The definition of the indexer to create or update. - * @param ifMatch Defines the If-Match condition. The operation will be performed only if the ETag on the server - * matches this value. - * @param ifNoneMatch Defines the If-None-Match condition. The operation will be performed only if the ETag on the - * server does not match this value. - * @param skipIndexerResetRequirementForCache Ignores cache reset requirements. - * @param disableCacheReprocessingChangeDetection Disables cache reprocessing change detection. - * @param requestOptions Parameter group. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return represents an indexer along with {@link Response} on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> createOrUpdateWithResponseAsync(String indexerName, SearchIndexer indexer, - String ifMatch, String ifNoneMatch, Boolean skipIndexerResetRequirementForCache, - Boolean disableCacheReprocessingChangeDetection, RequestOptions requestOptions, Context context) { - final String prefer = "return=representation"; - final String accept = "application/json; odata.metadata=minimal"; - UUID xMsClientRequestIdInternal = null; - if (requestOptions != null) { - xMsClientRequestIdInternal = requestOptions.getXMsClientRequestId(); - } - UUID xMsClientRequestId = xMsClientRequestIdInternal; - return service.createOrUpdate(this.client.getEndpoint(), indexerName, xMsClientRequestId, ifMatch, ifNoneMatch, - prefer, this.client.getApiVersion(), skipIndexerResetRequirementForCache, - disableCacheReprocessingChangeDetection, accept, indexer, context); - } - - /** - * Creates a new indexer or updates an indexer if it already exists. - * - * @param indexerName The name of the indexer to create or update. - * @param indexer The definition of the indexer to create or update. - * @param ifMatch Defines the If-Match condition. The operation will be performed only if the ETag on the server - * matches this value. - * @param ifNoneMatch Defines the If-None-Match condition. The operation will be performed only if the ETag on the - * server does not match this value. - * @param skipIndexerResetRequirementForCache Ignores cache reset requirements. - * @param disableCacheReprocessingChangeDetection Disables cache reprocessing change detection. - * @param requestOptions Parameter group. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return represents an indexer on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono createOrUpdateAsync(String indexerName, SearchIndexer indexer, String ifMatch, - String ifNoneMatch, Boolean skipIndexerResetRequirementForCache, - Boolean disableCacheReprocessingChangeDetection, RequestOptions requestOptions) { - return createOrUpdateWithResponseAsync(indexerName, indexer, ifMatch, ifNoneMatch, - skipIndexerResetRequirementForCache, disableCacheReprocessingChangeDetection, requestOptions) - .flatMap(res -> Mono.justOrEmpty(res.getValue())); - } - - /** - * Creates a new indexer or updates an indexer if it already exists. - * - * @param indexerName The name of the indexer to create or update. - * @param indexer The definition of the indexer to create or update. - * @param ifMatch Defines the If-Match condition. The operation will be performed only if the ETag on the server - * matches this value. - * @param ifNoneMatch Defines the If-None-Match condition. The operation will be performed only if the ETag on the - * server does not match this value. - * @param skipIndexerResetRequirementForCache Ignores cache reset requirements. - * @param disableCacheReprocessingChangeDetection Disables cache reprocessing change detection. - * @param requestOptions Parameter group. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return represents an indexer on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono createOrUpdateAsync(String indexerName, SearchIndexer indexer, String ifMatch, - String ifNoneMatch, Boolean skipIndexerResetRequirementForCache, - Boolean disableCacheReprocessingChangeDetection, RequestOptions requestOptions, Context context) { - return createOrUpdateWithResponseAsync(indexerName, indexer, ifMatch, ifNoneMatch, - skipIndexerResetRequirementForCache, disableCacheReprocessingChangeDetection, requestOptions, context) - .flatMap(res -> Mono.justOrEmpty(res.getValue())); - } - - /** - * Creates a new indexer or updates an indexer if it already exists. - * - * @param indexerName The name of the indexer to create or update. - * @param indexer The definition of the indexer to create or update. - * @param ifMatch Defines the If-Match condition. The operation will be performed only if the ETag on the server - * matches this value. - * @param ifNoneMatch Defines the If-None-Match condition. The operation will be performed only if the ETag on the - * server does not match this value. - * @param skipIndexerResetRequirementForCache Ignores cache reset requirements. - * @param disableCacheReprocessingChangeDetection Disables cache reprocessing change detection. - * @param requestOptions Parameter group. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return represents an indexer along with {@link Response}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Response createOrUpdateWithResponse(String indexerName, SearchIndexer indexer, String ifMatch, - String ifNoneMatch, Boolean skipIndexerResetRequirementForCache, - Boolean disableCacheReprocessingChangeDetection, RequestOptions requestOptions, Context context) { - final String prefer = "return=representation"; - final String accept = "application/json; odata.metadata=minimal"; - UUID xMsClientRequestIdInternal = null; - if (requestOptions != null) { - xMsClientRequestIdInternal = requestOptions.getXMsClientRequestId(); - } - UUID xMsClientRequestId = xMsClientRequestIdInternal; - return service.createOrUpdateSync(this.client.getEndpoint(), indexerName, xMsClientRequestId, ifMatch, - ifNoneMatch, prefer, this.client.getApiVersion(), skipIndexerResetRequirementForCache, - disableCacheReprocessingChangeDetection, accept, indexer, context); - } - - /** - * Creates a new indexer or updates an indexer if it already exists. - * - * @param indexerName The name of the indexer to create or update. - * @param indexer The definition of the indexer to create or update. - * @param ifMatch Defines the If-Match condition. The operation will be performed only if the ETag on the server - * matches this value. - * @param ifNoneMatch Defines the If-None-Match condition. The operation will be performed only if the ETag on the - * server does not match this value. - * @param skipIndexerResetRequirementForCache Ignores cache reset requirements. - * @param disableCacheReprocessingChangeDetection Disables cache reprocessing change detection. - * @param requestOptions Parameter group. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return represents an indexer. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public SearchIndexer createOrUpdate(String indexerName, SearchIndexer indexer, String ifMatch, String ifNoneMatch, - Boolean skipIndexerResetRequirementForCache, Boolean disableCacheReprocessingChangeDetection, - RequestOptions requestOptions) { - return createOrUpdateWithResponse(indexerName, indexer, ifMatch, ifNoneMatch, - skipIndexerResetRequirementForCache, disableCacheReprocessingChangeDetection, requestOptions, Context.NONE) - .getValue(); - } - - /** - * Deletes an indexer. - * - * @param indexerName The name of the indexer to delete. - * @param ifMatch Defines the If-Match condition. The operation will be performed only if the ETag on the server - * matches this value. - * @param ifNoneMatch Defines the If-None-Match condition. The operation will be performed only if the ETag on the - * server does not match this value. - * @param requestOptions Parameter group. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the {@link Response} on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> deleteWithResponseAsync(String indexerName, String ifMatch, String ifNoneMatch, - RequestOptions requestOptions) { - return FluxUtil.withContext( - context -> deleteWithResponseAsync(indexerName, ifMatch, ifNoneMatch, requestOptions, context)); - } - - /** - * Deletes an indexer. - * - * @param indexerName The name of the indexer to delete. - * @param ifMatch Defines the If-Match condition. The operation will be performed only if the ETag on the server - * matches this value. - * @param ifNoneMatch Defines the If-None-Match condition. The operation will be performed only if the ETag on the - * server does not match this value. - * @param requestOptions Parameter group. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the {@link Response} on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> deleteWithResponseAsync(String indexerName, String ifMatch, String ifNoneMatch, - RequestOptions requestOptions, Context context) { - final String accept = "application/json; odata.metadata=minimal"; - UUID xMsClientRequestIdInternal = null; - if (requestOptions != null) { - xMsClientRequestIdInternal = requestOptions.getXMsClientRequestId(); - } - UUID xMsClientRequestId = xMsClientRequestIdInternal; - return service.delete(this.client.getEndpoint(), indexerName, xMsClientRequestId, ifMatch, ifNoneMatch, - this.client.getApiVersion(), accept, context); - } - - /** - * Deletes an indexer. - * - * @param indexerName The name of the indexer to delete. - * @param ifMatch Defines the If-Match condition. The operation will be performed only if the ETag on the server - * matches this value. - * @param ifNoneMatch Defines the If-None-Match condition. The operation will be performed only if the ETag on the - * server does not match this value. - * @param requestOptions Parameter group. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return A {@link Mono} that completes when a successful response is received. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono deleteAsync(String indexerName, String ifMatch, String ifNoneMatch, - RequestOptions requestOptions) { - return deleteWithResponseAsync(indexerName, ifMatch, ifNoneMatch, requestOptions) - .flatMap(ignored -> Mono.empty()); - } - - /** - * Deletes an indexer. - * - * @param indexerName The name of the indexer to delete. - * @param ifMatch Defines the If-Match condition. The operation will be performed only if the ETag on the server - * matches this value. - * @param ifNoneMatch Defines the If-None-Match condition. The operation will be performed only if the ETag on the - * server does not match this value. - * @param requestOptions Parameter group. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return A {@link Mono} that completes when a successful response is received. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono deleteAsync(String indexerName, String ifMatch, String ifNoneMatch, RequestOptions requestOptions, - Context context) { - return deleteWithResponseAsync(indexerName, ifMatch, ifNoneMatch, requestOptions, context) - .flatMap(ignored -> Mono.empty()); - } - - /** - * Deletes an indexer. - * - * @param indexerName The name of the indexer to delete. - * @param ifMatch Defines the If-Match condition. The operation will be performed only if the ETag on the server - * matches this value. - * @param ifNoneMatch Defines the If-None-Match condition. The operation will be performed only if the ETag on the - * server does not match this value. - * @param requestOptions Parameter group. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the {@link Response}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Response deleteWithResponse(String indexerName, String ifMatch, String ifNoneMatch, - RequestOptions requestOptions, Context context) { - final String accept = "application/json; odata.metadata=minimal"; - UUID xMsClientRequestIdInternal = null; - if (requestOptions != null) { - xMsClientRequestIdInternal = requestOptions.getXMsClientRequestId(); - } - UUID xMsClientRequestId = xMsClientRequestIdInternal; - return service.deleteSync(this.client.getEndpoint(), indexerName, xMsClientRequestId, ifMatch, ifNoneMatch, - this.client.getApiVersion(), accept, context); - } - - /** - * Deletes an indexer. - * - * @param indexerName The name of the indexer to delete. - * @param ifMatch Defines the If-Match condition. The operation will be performed only if the ETag on the server - * matches this value. - * @param ifNoneMatch Defines the If-None-Match condition. The operation will be performed only if the ETag on the - * server does not match this value. - * @param requestOptions Parameter group. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public void delete(String indexerName, String ifMatch, String ifNoneMatch, RequestOptions requestOptions) { - deleteWithResponse(indexerName, ifMatch, ifNoneMatch, requestOptions, Context.NONE); - } - - /** - * Retrieves an indexer definition. - * - * @param indexerName The name of the indexer to retrieve. - * @param requestOptions Parameter group. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return represents an indexer along with {@link Response} on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> getWithResponseAsync(String indexerName, RequestOptions requestOptions) { - return FluxUtil.withContext(context -> getWithResponseAsync(indexerName, requestOptions, context)); - } - - /** - * Retrieves an indexer definition. - * - * @param indexerName The name of the indexer to retrieve. - * @param requestOptions Parameter group. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return represents an indexer along with {@link Response} on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> getWithResponseAsync(String indexerName, RequestOptions requestOptions, - Context context) { - final String accept = "application/json; odata.metadata=minimal"; - UUID xMsClientRequestIdInternal = null; - if (requestOptions != null) { - xMsClientRequestIdInternal = requestOptions.getXMsClientRequestId(); - } - UUID xMsClientRequestId = xMsClientRequestIdInternal; - return service.get(this.client.getEndpoint(), indexerName, xMsClientRequestId, this.client.getApiVersion(), - accept, context); - } - - /** - * Retrieves an indexer definition. - * - * @param indexerName The name of the indexer to retrieve. - * @param requestOptions Parameter group. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return represents an indexer on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono getAsync(String indexerName, RequestOptions requestOptions) { - return getWithResponseAsync(indexerName, requestOptions).flatMap(res -> Mono.justOrEmpty(res.getValue())); - } - - /** - * Retrieves an indexer definition. - * - * @param indexerName The name of the indexer to retrieve. - * @param requestOptions Parameter group. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return represents an indexer on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono getAsync(String indexerName, RequestOptions requestOptions, Context context) { - return getWithResponseAsync(indexerName, requestOptions, context) - .flatMap(res -> Mono.justOrEmpty(res.getValue())); - } - - /** - * Retrieves an indexer definition. - * - * @param indexerName The name of the indexer to retrieve. - * @param requestOptions Parameter group. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return represents an indexer along with {@link Response}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Response getWithResponse(String indexerName, RequestOptions requestOptions, Context context) { - final String accept = "application/json; odata.metadata=minimal"; - UUID xMsClientRequestIdInternal = null; - if (requestOptions != null) { - xMsClientRequestIdInternal = requestOptions.getXMsClientRequestId(); - } - UUID xMsClientRequestId = xMsClientRequestIdInternal; - return service.getSync(this.client.getEndpoint(), indexerName, xMsClientRequestId, this.client.getApiVersion(), - accept, context); - } - - /** - * Retrieves an indexer definition. - * - * @param indexerName The name of the indexer to retrieve. - * @param requestOptions Parameter group. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return represents an indexer. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public SearchIndexer get(String indexerName, RequestOptions requestOptions) { - return getWithResponse(indexerName, requestOptions, Context.NONE).getValue(); - } - - /** - * Lists all indexers available for a search service. - * - * @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. - * @param requestOptions Parameter group. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return response from a List Indexers request along with {@link Response} on successful completion of - * {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> listWithResponseAsync(String select, RequestOptions requestOptions) { - return FluxUtil.withContext(context -> listWithResponseAsync(select, requestOptions, context)); - } - - /** - * Lists all indexers available for a search service. - * - * @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. - * @param requestOptions Parameter group. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return response from a List Indexers request along with {@link Response} on successful completion of - * {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> listWithResponseAsync(String select, RequestOptions requestOptions, - Context context) { - final String accept = "application/json; odata.metadata=minimal"; - UUID xMsClientRequestIdInternal = null; - if (requestOptions != null) { - xMsClientRequestIdInternal = requestOptions.getXMsClientRequestId(); - } - UUID xMsClientRequestId = xMsClientRequestIdInternal; - return service.list(this.client.getEndpoint(), select, xMsClientRequestId, this.client.getApiVersion(), accept, - context); - } - - /** - * Lists all indexers available for a search service. - * - * @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. - * @param requestOptions Parameter group. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return response from a List Indexers request on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono listAsync(String select, RequestOptions requestOptions) { - return listWithResponseAsync(select, requestOptions).flatMap(res -> Mono.justOrEmpty(res.getValue())); - } - - /** - * Lists all indexers available for a search service. - * - * @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. - * @param requestOptions Parameter group. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return response from a List Indexers request on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono listAsync(String select, RequestOptions requestOptions, Context context) { - return listWithResponseAsync(select, requestOptions, context).flatMap(res -> Mono.justOrEmpty(res.getValue())); - } - - /** - * Lists all indexers available for a search service. - * - * @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. - * @param requestOptions Parameter group. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return response from a List Indexers request along with {@link Response}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Response listWithResponse(String select, RequestOptions requestOptions, - Context context) { - final String accept = "application/json; odata.metadata=minimal"; - UUID xMsClientRequestIdInternal = null; - if (requestOptions != null) { - xMsClientRequestIdInternal = requestOptions.getXMsClientRequestId(); - } - UUID xMsClientRequestId = xMsClientRequestIdInternal; - return service.listSync(this.client.getEndpoint(), select, xMsClientRequestId, this.client.getApiVersion(), - accept, context); - } - - /** - * Lists all indexers available for a search service. - * - * @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. - * @param requestOptions Parameter group. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return response from a List Indexers request. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public ListIndexersResult list(String select, RequestOptions requestOptions) { - return listWithResponse(select, requestOptions, Context.NONE).getValue(); - } - - /** - * Creates a new indexer. - * - * @param indexer The definition of the indexer to create. - * @param requestOptions Parameter group. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return represents an indexer along with {@link Response} on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> createWithResponseAsync(SearchIndexer indexer, RequestOptions requestOptions) { - return FluxUtil.withContext(context -> createWithResponseAsync(indexer, requestOptions, context)); - } - - /** - * Creates a new indexer. - * - * @param indexer The definition of the indexer to create. - * @param requestOptions Parameter group. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return represents an indexer along with {@link Response} on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> createWithResponseAsync(SearchIndexer indexer, RequestOptions requestOptions, - Context context) { - final String accept = "application/json; odata.metadata=minimal"; - UUID xMsClientRequestIdInternal = null; - if (requestOptions != null) { - xMsClientRequestIdInternal = requestOptions.getXMsClientRequestId(); - } - UUID xMsClientRequestId = xMsClientRequestIdInternal; - return service.create(this.client.getEndpoint(), xMsClientRequestId, this.client.getApiVersion(), accept, - indexer, context); - } - - /** - * Creates a new indexer. - * - * @param indexer The definition of the indexer to create. - * @param requestOptions Parameter group. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return represents an indexer on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono createAsync(SearchIndexer indexer, RequestOptions requestOptions) { - return createWithResponseAsync(indexer, requestOptions).flatMap(res -> Mono.justOrEmpty(res.getValue())); - } - - /** - * Creates a new indexer. - * - * @param indexer The definition of the indexer to create. - * @param requestOptions Parameter group. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return represents an indexer on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono createAsync(SearchIndexer indexer, RequestOptions requestOptions, Context context) { - return createWithResponseAsync(indexer, requestOptions, context) - .flatMap(res -> Mono.justOrEmpty(res.getValue())); - } - - /** - * Creates a new indexer. - * - * @param indexer The definition of the indexer to create. - * @param requestOptions Parameter group. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return represents an indexer along with {@link Response}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Response createWithResponse(SearchIndexer indexer, RequestOptions requestOptions, - Context context) { - final String accept = "application/json; odata.metadata=minimal"; - UUID xMsClientRequestIdInternal = null; - if (requestOptions != null) { - xMsClientRequestIdInternal = requestOptions.getXMsClientRequestId(); - } - UUID xMsClientRequestId = xMsClientRequestIdInternal; - return service.createSync(this.client.getEndpoint(), xMsClientRequestId, this.client.getApiVersion(), accept, - indexer, context); - } - - /** - * Creates a new indexer. - * - * @param indexer The definition of the indexer to create. - * @param requestOptions Parameter group. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return represents an indexer. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public SearchIndexer create(SearchIndexer indexer, RequestOptions requestOptions) { - return createWithResponse(indexer, requestOptions, Context.NONE).getValue(); - } - - /** - * Returns the current status and execution history of an indexer. - * - * @param indexerName The name of the indexer for which to retrieve status. - * @param requestOptions Parameter group. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return represents the current status and execution history of an indexer along with {@link Response} on - * successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> getStatusWithResponseAsync(String indexerName, - RequestOptions requestOptions) { - return FluxUtil.withContext(context -> getStatusWithResponseAsync(indexerName, requestOptions, context)); - } - - /** - * Returns the current status and execution history of an indexer. - * - * @param indexerName The name of the indexer for which to retrieve status. - * @param requestOptions Parameter group. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return represents the current status and execution history of an indexer along with {@link Response} on - * successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> getStatusWithResponseAsync(String indexerName, - RequestOptions requestOptions, Context context) { - final String accept = "application/json; odata.metadata=minimal"; - UUID xMsClientRequestIdInternal = null; - if (requestOptions != null) { - xMsClientRequestIdInternal = requestOptions.getXMsClientRequestId(); - } - UUID xMsClientRequestId = xMsClientRequestIdInternal; - return service.getStatus(this.client.getEndpoint(), indexerName, xMsClientRequestId, - this.client.getApiVersion(), accept, context); - } - - /** - * Returns the current status and execution history of an indexer. - * - * @param indexerName The name of the indexer for which to retrieve status. - * @param requestOptions Parameter group. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return represents the current status and execution history of an indexer on successful completion of - * {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono getStatusAsync(String indexerName, RequestOptions requestOptions) { - return getStatusWithResponseAsync(indexerName, requestOptions).flatMap(res -> Mono.justOrEmpty(res.getValue())); - } - - /** - * Returns the current status and execution history of an indexer. - * - * @param indexerName The name of the indexer for which to retrieve status. - * @param requestOptions Parameter group. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return represents the current status and execution history of an indexer on successful completion of - * {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono getStatusAsync(String indexerName, RequestOptions requestOptions, - Context context) { - return getStatusWithResponseAsync(indexerName, requestOptions, context) - .flatMap(res -> Mono.justOrEmpty(res.getValue())); - } - - /** - * Returns the current status and execution history of an indexer. - * - * @param indexerName The name of the indexer for which to retrieve status. - * @param requestOptions Parameter group. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return represents the current status and execution history of an indexer along with {@link Response}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Response getStatusWithResponse(String indexerName, RequestOptions requestOptions, - Context context) { - final String accept = "application/json; odata.metadata=minimal"; - UUID xMsClientRequestIdInternal = null; - if (requestOptions != null) { - xMsClientRequestIdInternal = requestOptions.getXMsClientRequestId(); - } - UUID xMsClientRequestId = xMsClientRequestIdInternal; - return service.getStatusSync(this.client.getEndpoint(), indexerName, xMsClientRequestId, - this.client.getApiVersion(), accept, context); - } - - /** - * Returns the current status and execution history of an indexer. - * - * @param indexerName The name of the indexer for which to retrieve status. - * @param requestOptions Parameter group. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return represents the current status and execution history of an indexer. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public SearchIndexerStatus getStatus(String indexerName, RequestOptions requestOptions) { - return getStatusWithResponse(indexerName, requestOptions, Context.NONE).getValue(); - } -} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/implementation/IndexesImpl.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/implementation/IndexesImpl.java deleted file mode 100644 index ae88eeb26b1d..000000000000 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/implementation/IndexesImpl.java +++ /dev/null @@ -1,1145 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -package com.azure.search.documents.indexes.implementation; - -import com.azure.core.annotation.BodyParam; -import com.azure.core.annotation.Delete; -import com.azure.core.annotation.ExpectedResponses; -import com.azure.core.annotation.Get; -import com.azure.core.annotation.HeaderParam; -import com.azure.core.annotation.Host; -import com.azure.core.annotation.HostParam; -import com.azure.core.annotation.PathParam; -import com.azure.core.annotation.Post; -import com.azure.core.annotation.Put; -import com.azure.core.annotation.QueryParam; -import com.azure.core.annotation.ReturnType; -import com.azure.core.annotation.ServiceInterface; -import com.azure.core.annotation.ServiceMethod; -import com.azure.core.annotation.UnexpectedResponseExceptionType; -import com.azure.core.http.rest.PagedFlux; -import com.azure.core.http.rest.PagedIterable; -import com.azure.core.http.rest.PagedResponse; -import com.azure.core.http.rest.PagedResponseBase; -import com.azure.core.http.rest.Response; -import com.azure.core.http.rest.RestProxy; -import com.azure.core.util.Context; -import com.azure.core.util.FluxUtil; -import com.azure.search.documents.indexes.implementation.models.AnalyzeRequest; -import com.azure.search.documents.indexes.implementation.models.AnalyzeResult; -import com.azure.search.documents.indexes.implementation.models.ErrorResponseException; -import com.azure.search.documents.indexes.implementation.models.ListIndexesResult; -import com.azure.search.documents.indexes.implementation.models.RequestOptions; -import com.azure.search.documents.indexes.models.SearchIndex; -import com.azure.search.documents.indexes.models.SearchIndexStatistics; -import java.util.UUID; -import reactor.core.publisher.Mono; - -/** - * An instance of this class provides access to all the operations defined in Indexes. - */ -public final class IndexesImpl { - /** - * The proxy service used to perform REST calls. - */ - private final IndexesService service; - - /** - * The service client containing this operation class. - */ - private final SearchServiceClientImpl client; - - /** - * Initializes an instance of IndexesImpl. - * - * @param client the instance of the service client containing this operation class. - */ - IndexesImpl(SearchServiceClientImpl client) { - this.service = RestProxy.create(IndexesService.class, client.getHttpPipeline(), client.getSerializerAdapter()); - this.client = client; - } - - /** - * The interface defining all the services for SearchServiceClientIndexes to be used by the proxy service to perform - * REST calls. - */ - @Host("{endpoint}") - @ServiceInterface(name = "SearchServiceClientI") - public interface IndexesService { - @Post("/indexes") - @ExpectedResponses({ 201 }) - @UnexpectedResponseExceptionType(ErrorResponseException.class) - Mono> create(@HostParam("endpoint") String endpoint, - @HeaderParam("x-ms-client-request-id") UUID xMsClientRequestId, - @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, - @BodyParam("application/json") SearchIndex index, Context context); - - @Post("/indexes") - @ExpectedResponses({ 201 }) - @UnexpectedResponseExceptionType(ErrorResponseException.class) - Response createSync(@HostParam("endpoint") String endpoint, - @HeaderParam("x-ms-client-request-id") UUID xMsClientRequestId, - @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, - @BodyParam("application/json") SearchIndex index, Context context); - - @Get("/indexes") - @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(ErrorResponseException.class) - Mono> list(@HostParam("endpoint") String endpoint, - @QueryParam("$select") String select, @HeaderParam("x-ms-client-request-id") UUID xMsClientRequestId, - @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, Context context); - - @Get("/indexes") - @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(ErrorResponseException.class) - Response listSync(@HostParam("endpoint") String endpoint, - @QueryParam("$select") String select, @HeaderParam("x-ms-client-request-id") UUID xMsClientRequestId, - @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, Context context); - - @Put("/indexes('{indexName}')") - @ExpectedResponses({ 200, 201 }) - @UnexpectedResponseExceptionType(ErrorResponseException.class) - Mono> createOrUpdate(@HostParam("endpoint") String endpoint, - @PathParam("indexName") String indexName, @QueryParam("allowIndexDowntime") Boolean allowIndexDowntime, - @HeaderParam("x-ms-client-request-id") UUID xMsClientRequestId, @HeaderParam("If-Match") String ifMatch, - @HeaderParam("If-None-Match") String ifNoneMatch, @HeaderParam("Prefer") String prefer, - @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, - @BodyParam("application/json") SearchIndex index, Context context); - - @Put("/indexes('{indexName}')") - @ExpectedResponses({ 200, 201 }) - @UnexpectedResponseExceptionType(ErrorResponseException.class) - Response createOrUpdateSync(@HostParam("endpoint") String endpoint, - @PathParam("indexName") String indexName, @QueryParam("allowIndexDowntime") Boolean allowIndexDowntime, - @HeaderParam("x-ms-client-request-id") UUID xMsClientRequestId, @HeaderParam("If-Match") String ifMatch, - @HeaderParam("If-None-Match") String ifNoneMatch, @HeaderParam("Prefer") String prefer, - @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, - @BodyParam("application/json") SearchIndex index, Context context); - - @Delete("/indexes('{indexName}')") - @ExpectedResponses({ 204, 404 }) - @UnexpectedResponseExceptionType(ErrorResponseException.class) - Mono> delete(@HostParam("endpoint") String endpoint, @PathParam("indexName") String indexName, - @HeaderParam("x-ms-client-request-id") UUID xMsClientRequestId, @HeaderParam("If-Match") String ifMatch, - @HeaderParam("If-None-Match") String ifNoneMatch, @QueryParam("api-version") String apiVersion, - @HeaderParam("Accept") String accept, Context context); - - @Delete("/indexes('{indexName}')") - @ExpectedResponses({ 204, 404 }) - @UnexpectedResponseExceptionType(ErrorResponseException.class) - Response deleteSync(@HostParam("endpoint") String endpoint, @PathParam("indexName") String indexName, - @HeaderParam("x-ms-client-request-id") UUID xMsClientRequestId, @HeaderParam("If-Match") String ifMatch, - @HeaderParam("If-None-Match") String ifNoneMatch, @QueryParam("api-version") String apiVersion, - @HeaderParam("Accept") String accept, Context context); - - @Get("/indexes('{indexName}')") - @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(ErrorResponseException.class) - Mono> get(@HostParam("endpoint") String endpoint, - @PathParam("indexName") String indexName, @HeaderParam("x-ms-client-request-id") UUID xMsClientRequestId, - @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, Context context); - - @Get("/indexes('{indexName}')") - @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(ErrorResponseException.class) - Response getSync(@HostParam("endpoint") String endpoint, @PathParam("indexName") String indexName, - @HeaderParam("x-ms-client-request-id") UUID xMsClientRequestId, - @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, Context context); - - @Get("/indexes('{indexName}')/search.stats") - @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(ErrorResponseException.class) - Mono> getStatistics(@HostParam("endpoint") String endpoint, - @PathParam("indexName") String indexName, @HeaderParam("x-ms-client-request-id") UUID xMsClientRequestId, - @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, Context context); - - @Get("/indexes('{indexName}')/search.stats") - @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(ErrorResponseException.class) - Response getStatisticsSync(@HostParam("endpoint") String endpoint, - @PathParam("indexName") String indexName, @HeaderParam("x-ms-client-request-id") UUID xMsClientRequestId, - @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, Context context); - - @Post("/indexes('{indexName}')/search.analyze") - @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(ErrorResponseException.class) - Mono> analyze(@HostParam("endpoint") String endpoint, - @PathParam("indexName") String indexName, @HeaderParam("x-ms-client-request-id") UUID xMsClientRequestId, - @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, - @BodyParam("application/json") AnalyzeRequest request, Context context); - - @Post("/indexes('{indexName}')/search.analyze") - @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(ErrorResponseException.class) - Response analyzeSync(@HostParam("endpoint") String endpoint, - @PathParam("indexName") String indexName, @HeaderParam("x-ms-client-request-id") UUID xMsClientRequestId, - @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, - @BodyParam("application/json") AnalyzeRequest request, Context context); - } - - /** - * Creates a new search index. - * - * @param index The definition of the index to create. - * @param requestOptions Parameter group. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return represents a search index definition, which describes the fields and search behavior of an index along - * with {@link Response} on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> createWithResponseAsync(SearchIndex index, RequestOptions requestOptions) { - return FluxUtil.withContext(context -> createWithResponseAsync(index, requestOptions, context)); - } - - /** - * Creates a new search index. - * - * @param index The definition of the index to create. - * @param requestOptions Parameter group. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return represents a search index definition, which describes the fields and search behavior of an index along - * with {@link Response} on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> createWithResponseAsync(SearchIndex index, RequestOptions requestOptions, - Context context) { - final String accept = "application/json; odata.metadata=minimal"; - UUID xMsClientRequestIdInternal = null; - if (requestOptions != null) { - xMsClientRequestIdInternal = requestOptions.getXMsClientRequestId(); - } - UUID xMsClientRequestId = xMsClientRequestIdInternal; - return service.create(this.client.getEndpoint(), xMsClientRequestId, this.client.getApiVersion(), accept, index, - context); - } - - /** - * Creates a new search index. - * - * @param index The definition of the index to create. - * @param requestOptions Parameter group. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return represents a search index definition, which describes the fields and search behavior of an index on - * successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono createAsync(SearchIndex index, RequestOptions requestOptions) { - return createWithResponseAsync(index, requestOptions).flatMap(res -> Mono.justOrEmpty(res.getValue())); - } - - /** - * Creates a new search index. - * - * @param index The definition of the index to create. - * @param requestOptions Parameter group. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return represents a search index definition, which describes the fields and search behavior of an index on - * successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono createAsync(SearchIndex index, RequestOptions requestOptions, Context context) { - return createWithResponseAsync(index, requestOptions, context).flatMap(res -> Mono.justOrEmpty(res.getValue())); - } - - /** - * Creates a new search index. - * - * @param index The definition of the index to create. - * @param requestOptions Parameter group. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return represents a search index definition, which describes the fields and search behavior of an index along - * with {@link Response}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Response createWithResponse(SearchIndex index, RequestOptions requestOptions, Context context) { - final String accept = "application/json; odata.metadata=minimal"; - UUID xMsClientRequestIdInternal = null; - if (requestOptions != null) { - xMsClientRequestIdInternal = requestOptions.getXMsClientRequestId(); - } - UUID xMsClientRequestId = xMsClientRequestIdInternal; - return service.createSync(this.client.getEndpoint(), xMsClientRequestId, this.client.getApiVersion(), accept, - index, context); - } - - /** - * Creates a new search index. - * - * @param index The definition of the index to create. - * @param requestOptions Parameter group. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return represents a search index definition, which describes the fields and search behavior of an index. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public SearchIndex create(SearchIndex index, RequestOptions requestOptions) { - return createWithResponse(index, requestOptions, Context.NONE).getValue(); - } - - /** - * Lists all indexes available for a search service. - * - * @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. - * @param requestOptions Parameter group. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return response from a List Indexes request along with {@link PagedResponse} on successful completion of - * {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> listSinglePageAsync(String select, RequestOptions requestOptions) { - final String accept = "application/json; odata.metadata=minimal"; - UUID xMsClientRequestIdInternal = null; - if (requestOptions != null) { - xMsClientRequestIdInternal = requestOptions.getXMsClientRequestId(); - } - UUID xMsClientRequestId = xMsClientRequestIdInternal; - return FluxUtil - .withContext(context -> service.list(this.client.getEndpoint(), select, xMsClientRequestId, - this.client.getApiVersion(), accept, context)) - .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), - res.getValue().getIndexes(), null, null)); - } - - /** - * Lists all indexes available for a search service. - * - * @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. - * @param requestOptions Parameter group. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return response from a List Indexes request along with {@link PagedResponse} on successful completion of - * {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> listSinglePageAsync(String select, RequestOptions requestOptions, - Context context) { - final String accept = "application/json; odata.metadata=minimal"; - UUID xMsClientRequestIdInternal = null; - if (requestOptions != null) { - xMsClientRequestIdInternal = requestOptions.getXMsClientRequestId(); - } - UUID xMsClientRequestId = xMsClientRequestIdInternal; - return service - .list(this.client.getEndpoint(), select, xMsClientRequestId, this.client.getApiVersion(), accept, context) - .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), - res.getValue().getIndexes(), null, null)); - } - - /** - * Lists all indexes available for a search service. - * - * @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. - * @param requestOptions Parameter group. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return response from a List Indexes request as paginated response with {@link PagedFlux}. - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - public PagedFlux listAsync(String select, RequestOptions requestOptions) { - return new PagedFlux<>(() -> listSinglePageAsync(select, requestOptions)); - } - - /** - * Lists all indexes available for a search service. - * - * @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. - * @param requestOptions Parameter group. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return response from a List Indexes request as paginated response with {@link PagedFlux}. - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - public PagedFlux listAsync(String select, RequestOptions requestOptions, Context context) { - return new PagedFlux<>(() -> listSinglePageAsync(select, requestOptions, context)); - } - - /** - * Lists all indexes available for a search service. - * - * @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. - * @param requestOptions Parameter group. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return response from a List Indexes request along with {@link PagedResponse}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public PagedResponse listSinglePage(String select, RequestOptions requestOptions) { - final String accept = "application/json; odata.metadata=minimal"; - UUID xMsClientRequestIdInternal = null; - if (requestOptions != null) { - xMsClientRequestIdInternal = requestOptions.getXMsClientRequestId(); - } - UUID xMsClientRequestId = xMsClientRequestIdInternal; - Response res = service.listSync(this.client.getEndpoint(), select, xMsClientRequestId, - this.client.getApiVersion(), accept, Context.NONE); - return new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), - res.getValue().getIndexes(), null, null); - } - - /** - * Lists all indexes available for a search service. - * - * @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. - * @param requestOptions Parameter group. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return response from a List Indexes request along with {@link PagedResponse}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public PagedResponse listSinglePage(String select, RequestOptions requestOptions, Context context) { - final String accept = "application/json; odata.metadata=minimal"; - UUID xMsClientRequestIdInternal = null; - if (requestOptions != null) { - xMsClientRequestIdInternal = requestOptions.getXMsClientRequestId(); - } - UUID xMsClientRequestId = xMsClientRequestIdInternal; - Response res = service.listSync(this.client.getEndpoint(), select, xMsClientRequestId, - this.client.getApiVersion(), accept, context); - return new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), - res.getValue().getIndexes(), null, null); - } - - /** - * Lists all indexes available for a search service. - * - * @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. - * @param requestOptions Parameter group. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return response from a List Indexes request as paginated response with {@link PagedIterable}. - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - public PagedIterable list(String select, RequestOptions requestOptions) { - return new PagedIterable<>(() -> listSinglePage(select, requestOptions, Context.NONE)); - } - - /** - * Lists all indexes available for a search service. - * - * @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. - * @param requestOptions Parameter group. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return response from a List Indexes request as paginated response with {@link PagedIterable}. - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - public PagedIterable list(String select, RequestOptions requestOptions, Context context) { - return new PagedIterable<>(() -> listSinglePage(select, requestOptions, context)); - } - - /** - * Creates a new search index or updates an index if it already exists. - * - * @param indexName The definition of the index to create or update. - * @param index The definition of the index to create or update. - * @param allowIndexDowntime 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. - * @param ifMatch Defines the If-Match condition. The operation will be performed only if the ETag on the server - * matches this value. - * @param ifNoneMatch Defines the If-None-Match condition. The operation will be performed only if the ETag on the - * server does not match this value. - * @param requestOptions Parameter group. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return represents a search index definition, which describes the fields and search behavior of an index along - * with {@link Response} on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> createOrUpdateWithResponseAsync(String indexName, SearchIndex index, - Boolean allowIndexDowntime, String ifMatch, String ifNoneMatch, RequestOptions requestOptions) { - return FluxUtil.withContext(context -> createOrUpdateWithResponseAsync(indexName, index, allowIndexDowntime, - ifMatch, ifNoneMatch, requestOptions, context)); - } - - /** - * Creates a new search index or updates an index if it already exists. - * - * @param indexName The definition of the index to create or update. - * @param index The definition of the index to create or update. - * @param allowIndexDowntime 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. - * @param ifMatch Defines the If-Match condition. The operation will be performed only if the ETag on the server - * matches this value. - * @param ifNoneMatch Defines the If-None-Match condition. The operation will be performed only if the ETag on the - * server does not match this value. - * @param requestOptions Parameter group. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return represents a search index definition, which describes the fields and search behavior of an index along - * with {@link Response} on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> createOrUpdateWithResponseAsync(String indexName, SearchIndex index, - Boolean allowIndexDowntime, String ifMatch, String ifNoneMatch, RequestOptions requestOptions, - Context context) { - final String prefer = "return=representation"; - final String accept = "application/json; odata.metadata=minimal"; - UUID xMsClientRequestIdInternal = null; - if (requestOptions != null) { - xMsClientRequestIdInternal = requestOptions.getXMsClientRequestId(); - } - UUID xMsClientRequestId = xMsClientRequestIdInternal; - return service.createOrUpdate(this.client.getEndpoint(), indexName, allowIndexDowntime, xMsClientRequestId, - ifMatch, ifNoneMatch, prefer, this.client.getApiVersion(), accept, index, context); - } - - /** - * Creates a new search index or updates an index if it already exists. - * - * @param indexName The definition of the index to create or update. - * @param index The definition of the index to create or update. - * @param allowIndexDowntime 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. - * @param ifMatch Defines the If-Match condition. The operation will be performed only if the ETag on the server - * matches this value. - * @param ifNoneMatch Defines the If-None-Match condition. The operation will be performed only if the ETag on the - * server does not match this value. - * @param requestOptions Parameter group. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return represents a search index definition, which describes the fields and search behavior of an index on - * successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono createOrUpdateAsync(String indexName, SearchIndex index, Boolean allowIndexDowntime, - String ifMatch, String ifNoneMatch, RequestOptions requestOptions) { - return createOrUpdateWithResponseAsync(indexName, index, allowIndexDowntime, ifMatch, ifNoneMatch, - requestOptions).flatMap(res -> Mono.justOrEmpty(res.getValue())); - } - - /** - * Creates a new search index or updates an index if it already exists. - * - * @param indexName The definition of the index to create or update. - * @param index The definition of the index to create or update. - * @param allowIndexDowntime 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. - * @param ifMatch Defines the If-Match condition. The operation will be performed only if the ETag on the server - * matches this value. - * @param ifNoneMatch Defines the If-None-Match condition. The operation will be performed only if the ETag on the - * server does not match this value. - * @param requestOptions Parameter group. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return represents a search index definition, which describes the fields and search behavior of an index on - * successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono createOrUpdateAsync(String indexName, SearchIndex index, Boolean allowIndexDowntime, - String ifMatch, String ifNoneMatch, RequestOptions requestOptions, Context context) { - return createOrUpdateWithResponseAsync(indexName, index, allowIndexDowntime, ifMatch, ifNoneMatch, - requestOptions, context).flatMap(res -> Mono.justOrEmpty(res.getValue())); - } - - /** - * Creates a new search index or updates an index if it already exists. - * - * @param indexName The definition of the index to create or update. - * @param index The definition of the index to create or update. - * @param allowIndexDowntime 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. - * @param ifMatch Defines the If-Match condition. The operation will be performed only if the ETag on the server - * matches this value. - * @param ifNoneMatch Defines the If-None-Match condition. The operation will be performed only if the ETag on the - * server does not match this value. - * @param requestOptions Parameter group. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return represents a search index definition, which describes the fields and search behavior of an index along - * with {@link Response}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Response createOrUpdateWithResponse(String indexName, SearchIndex index, - Boolean allowIndexDowntime, String ifMatch, String ifNoneMatch, RequestOptions requestOptions, - Context context) { - final String prefer = "return=representation"; - final String accept = "application/json; odata.metadata=minimal"; - UUID xMsClientRequestIdInternal = null; - if (requestOptions != null) { - xMsClientRequestIdInternal = requestOptions.getXMsClientRequestId(); - } - UUID xMsClientRequestId = xMsClientRequestIdInternal; - return service.createOrUpdateSync(this.client.getEndpoint(), indexName, allowIndexDowntime, xMsClientRequestId, - ifMatch, ifNoneMatch, prefer, this.client.getApiVersion(), accept, index, context); - } - - /** - * Creates a new search index or updates an index if it already exists. - * - * @param indexName The definition of the index to create or update. - * @param index The definition of the index to create or update. - * @param allowIndexDowntime 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. - * @param ifMatch Defines the If-Match condition. The operation will be performed only if the ETag on the server - * matches this value. - * @param ifNoneMatch Defines the If-None-Match condition. The operation will be performed only if the ETag on the - * server does not match this value. - * @param requestOptions Parameter group. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return represents a search index definition, which describes the fields and search behavior of an index. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public SearchIndex createOrUpdate(String indexName, SearchIndex index, Boolean allowIndexDowntime, String ifMatch, - String ifNoneMatch, RequestOptions requestOptions) { - return createOrUpdateWithResponse(indexName, index, allowIndexDowntime, ifMatch, ifNoneMatch, requestOptions, - Context.NONE).getValue(); - } - - /** - * 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 indexName The name of the index to delete. - * @param ifMatch Defines the If-Match condition. The operation will be performed only if the ETag on the server - * matches this value. - * @param ifNoneMatch Defines the If-None-Match condition. The operation will be performed only if the ETag on the - * server does not match this value. - * @param requestOptions Parameter group. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the {@link Response} on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> deleteWithResponseAsync(String indexName, String ifMatch, String ifNoneMatch, - RequestOptions requestOptions) { - return FluxUtil - .withContext(context -> deleteWithResponseAsync(indexName, ifMatch, ifNoneMatch, requestOptions, context)); - } - - /** - * 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 indexName The name of the index to delete. - * @param ifMatch Defines the If-Match condition. The operation will be performed only if the ETag on the server - * matches this value. - * @param ifNoneMatch Defines the If-None-Match condition. The operation will be performed only if the ETag on the - * server does not match this value. - * @param requestOptions Parameter group. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the {@link Response} on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> deleteWithResponseAsync(String indexName, String ifMatch, String ifNoneMatch, - RequestOptions requestOptions, Context context) { - final String accept = "application/json; odata.metadata=minimal"; - UUID xMsClientRequestIdInternal = null; - if (requestOptions != null) { - xMsClientRequestIdInternal = requestOptions.getXMsClientRequestId(); - } - UUID xMsClientRequestId = xMsClientRequestIdInternal; - return service.delete(this.client.getEndpoint(), indexName, xMsClientRequestId, ifMatch, ifNoneMatch, - this.client.getApiVersion(), accept, context); - } - - /** - * 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 indexName The name of the index to delete. - * @param ifMatch Defines the If-Match condition. The operation will be performed only if the ETag on the server - * matches this value. - * @param ifNoneMatch Defines the If-None-Match condition. The operation will be performed only if the ETag on the - * server does not match this value. - * @param requestOptions Parameter group. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return A {@link Mono} that completes when a successful response is received. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono deleteAsync(String indexName, String ifMatch, String ifNoneMatch, RequestOptions requestOptions) { - return deleteWithResponseAsync(indexName, ifMatch, ifNoneMatch, requestOptions) - .flatMap(ignored -> Mono.empty()); - } - - /** - * 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 indexName The name of the index to delete. - * @param ifMatch Defines the If-Match condition. The operation will be performed only if the ETag on the server - * matches this value. - * @param ifNoneMatch Defines the If-None-Match condition. The operation will be performed only if the ETag on the - * server does not match this value. - * @param requestOptions Parameter group. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return A {@link Mono} that completes when a successful response is received. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono deleteAsync(String indexName, String ifMatch, String ifNoneMatch, RequestOptions requestOptions, - Context context) { - return deleteWithResponseAsync(indexName, ifMatch, ifNoneMatch, requestOptions, context) - .flatMap(ignored -> Mono.empty()); - } - - /** - * 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 indexName The name of the index to delete. - * @param ifMatch Defines the If-Match condition. The operation will be performed only if the ETag on the server - * matches this value. - * @param ifNoneMatch Defines the If-None-Match condition. The operation will be performed only if the ETag on the - * server does not match this value. - * @param requestOptions Parameter group. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the {@link Response}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Response deleteWithResponse(String indexName, String ifMatch, String ifNoneMatch, - RequestOptions requestOptions, Context context) { - final String accept = "application/json; odata.metadata=minimal"; - UUID xMsClientRequestIdInternal = null; - if (requestOptions != null) { - xMsClientRequestIdInternal = requestOptions.getXMsClientRequestId(); - } - UUID xMsClientRequestId = xMsClientRequestIdInternal; - return service.deleteSync(this.client.getEndpoint(), indexName, xMsClientRequestId, ifMatch, ifNoneMatch, - this.client.getApiVersion(), accept, context); - } - - /** - * 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 indexName The name of the index to delete. - * @param ifMatch Defines the If-Match condition. The operation will be performed only if the ETag on the server - * matches this value. - * @param ifNoneMatch Defines the If-None-Match condition. The operation will be performed only if the ETag on the - * server does not match this value. - * @param requestOptions Parameter group. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public void delete(String indexName, String ifMatch, String ifNoneMatch, RequestOptions requestOptions) { - deleteWithResponse(indexName, ifMatch, ifNoneMatch, requestOptions, Context.NONE); - } - - /** - * Retrieves an index definition. - * - * @param indexName The name of the index to retrieve. - * @param requestOptions Parameter group. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return represents a search index definition, which describes the fields and search behavior of an index along - * with {@link Response} on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> getWithResponseAsync(String indexName, RequestOptions requestOptions) { - return FluxUtil.withContext(context -> getWithResponseAsync(indexName, requestOptions, context)); - } - - /** - * Retrieves an index definition. - * - * @param indexName The name of the index to retrieve. - * @param requestOptions Parameter group. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return represents a search index definition, which describes the fields and search behavior of an index along - * with {@link Response} on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> getWithResponseAsync(String indexName, RequestOptions requestOptions, - Context context) { - final String accept = "application/json; odata.metadata=minimal"; - UUID xMsClientRequestIdInternal = null; - if (requestOptions != null) { - xMsClientRequestIdInternal = requestOptions.getXMsClientRequestId(); - } - UUID xMsClientRequestId = xMsClientRequestIdInternal; - return service.get(this.client.getEndpoint(), indexName, xMsClientRequestId, this.client.getApiVersion(), - accept, context); - } - - /** - * Retrieves an index definition. - * - * @param indexName The name of the index to retrieve. - * @param requestOptions Parameter group. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return represents a search index definition, which describes the fields and search behavior of an index on - * successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono getAsync(String indexName, RequestOptions requestOptions) { - return getWithResponseAsync(indexName, requestOptions).flatMap(res -> Mono.justOrEmpty(res.getValue())); - } - - /** - * Retrieves an index definition. - * - * @param indexName The name of the index to retrieve. - * @param requestOptions Parameter group. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return represents a search index definition, which describes the fields and search behavior of an index on - * successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono getAsync(String indexName, RequestOptions requestOptions, Context context) { - return getWithResponseAsync(indexName, requestOptions, context) - .flatMap(res -> Mono.justOrEmpty(res.getValue())); - } - - /** - * Retrieves an index definition. - * - * @param indexName The name of the index to retrieve. - * @param requestOptions Parameter group. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return represents a search index definition, which describes the fields and search behavior of an index along - * with {@link Response}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Response getWithResponse(String indexName, RequestOptions requestOptions, Context context) { - final String accept = "application/json; odata.metadata=minimal"; - UUID xMsClientRequestIdInternal = null; - if (requestOptions != null) { - xMsClientRequestIdInternal = requestOptions.getXMsClientRequestId(); - } - UUID xMsClientRequestId = xMsClientRequestIdInternal; - return service.getSync(this.client.getEndpoint(), indexName, xMsClientRequestId, this.client.getApiVersion(), - accept, context); - } - - /** - * Retrieves an index definition. - * - * @param indexName The name of the index to retrieve. - * @param requestOptions Parameter group. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return represents a search index definition, which describes the fields and search behavior of an index. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public SearchIndex get(String indexName, RequestOptions requestOptions) { - return getWithResponse(indexName, requestOptions, Context.NONE).getValue(); - } - - /** - * Returns statistics for the given index, including a document count and storage usage. - * - * @param indexName The name of the index for which to retrieve statistics. - * @param requestOptions Parameter group. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return statistics for a given index along with {@link Response} on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> getStatisticsWithResponseAsync(String indexName, - RequestOptions requestOptions) { - return FluxUtil.withContext(context -> getStatisticsWithResponseAsync(indexName, requestOptions, context)); - } - - /** - * Returns statistics for the given index, including a document count and storage usage. - * - * @param indexName The name of the index for which to retrieve statistics. - * @param requestOptions Parameter group. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return statistics for a given index along with {@link Response} on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> getStatisticsWithResponseAsync(String indexName, - RequestOptions requestOptions, Context context) { - final String accept = "application/json; odata.metadata=minimal"; - UUID xMsClientRequestIdInternal = null; - if (requestOptions != null) { - xMsClientRequestIdInternal = requestOptions.getXMsClientRequestId(); - } - UUID xMsClientRequestId = xMsClientRequestIdInternal; - return service.getStatistics(this.client.getEndpoint(), indexName, xMsClientRequestId, - this.client.getApiVersion(), accept, context); - } - - /** - * Returns statistics for the given index, including a document count and storage usage. - * - * @param indexName The name of the index for which to retrieve statistics. - * @param requestOptions Parameter group. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return statistics for a given index on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono getStatisticsAsync(String indexName, RequestOptions requestOptions) { - return getStatisticsWithResponseAsync(indexName, requestOptions) - .flatMap(res -> Mono.justOrEmpty(res.getValue())); - } - - /** - * Returns statistics for the given index, including a document count and storage usage. - * - * @param indexName The name of the index for which to retrieve statistics. - * @param requestOptions Parameter group. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return statistics for a given index on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono getStatisticsAsync(String indexName, RequestOptions requestOptions, - Context context) { - return getStatisticsWithResponseAsync(indexName, requestOptions, context) - .flatMap(res -> Mono.justOrEmpty(res.getValue())); - } - - /** - * Returns statistics for the given index, including a document count and storage usage. - * - * @param indexName The name of the index for which to retrieve statistics. - * @param requestOptions Parameter group. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return statistics for a given index along with {@link Response}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Response getStatisticsWithResponse(String indexName, RequestOptions requestOptions, - Context context) { - final String accept = "application/json; odata.metadata=minimal"; - UUID xMsClientRequestIdInternal = null; - if (requestOptions != null) { - xMsClientRequestIdInternal = requestOptions.getXMsClientRequestId(); - } - UUID xMsClientRequestId = xMsClientRequestIdInternal; - return service.getStatisticsSync(this.client.getEndpoint(), indexName, xMsClientRequestId, - this.client.getApiVersion(), accept, context); - } - - /** - * Returns statistics for the given index, including a document count and storage usage. - * - * @param indexName The name of the index for which to retrieve statistics. - * @param requestOptions Parameter group. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return statistics for a given index. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public SearchIndexStatistics getStatistics(String indexName, RequestOptions requestOptions) { - return getStatisticsWithResponse(indexName, requestOptions, Context.NONE).getValue(); - } - - /** - * Shows how an analyzer breaks text into tokens. - * - * @param indexName The name of the index for which to test an analyzer. - * @param request The text and analyzer or analysis components to test. - * @param requestOptions Parameter group. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the result of testing an analyzer on text along with {@link Response} on successful completion of - * {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> analyzeWithResponseAsync(String indexName, AnalyzeRequest request, - RequestOptions requestOptions) { - return FluxUtil.withContext(context -> analyzeWithResponseAsync(indexName, request, requestOptions, context)); - } - - /** - * Shows how an analyzer breaks text into tokens. - * - * @param indexName The name of the index for which to test an analyzer. - * @param request The text and analyzer or analysis components to test. - * @param requestOptions Parameter group. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the result of testing an analyzer on text along with {@link Response} on successful completion of - * {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> analyzeWithResponseAsync(String indexName, AnalyzeRequest request, - RequestOptions requestOptions, Context context) { - final String accept = "application/json; odata.metadata=minimal"; - UUID xMsClientRequestIdInternal = null; - if (requestOptions != null) { - xMsClientRequestIdInternal = requestOptions.getXMsClientRequestId(); - } - UUID xMsClientRequestId = xMsClientRequestIdInternal; - return service.analyze(this.client.getEndpoint(), indexName, xMsClientRequestId, this.client.getApiVersion(), - accept, request, context); - } - - /** - * Shows how an analyzer breaks text into tokens. - * - * @param indexName The name of the index for which to test an analyzer. - * @param request The text and analyzer or analysis components to test. - * @param requestOptions Parameter group. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the result of testing an analyzer on text on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono analyzeAsync(String indexName, AnalyzeRequest request, RequestOptions requestOptions) { - return analyzeWithResponseAsync(indexName, request, requestOptions) - .flatMap(res -> Mono.justOrEmpty(res.getValue())); - } - - /** - * Shows how an analyzer breaks text into tokens. - * - * @param indexName The name of the index for which to test an analyzer. - * @param request The text and analyzer or analysis components to test. - * @param requestOptions Parameter group. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the result of testing an analyzer on text on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono analyzeAsync(String indexName, AnalyzeRequest request, RequestOptions requestOptions, - Context context) { - return analyzeWithResponseAsync(indexName, request, requestOptions, context) - .flatMap(res -> Mono.justOrEmpty(res.getValue())); - } - - /** - * Shows how an analyzer breaks text into tokens. - * - * @param indexName The name of the index for which to test an analyzer. - * @param request The text and analyzer or analysis components to test. - * @param requestOptions Parameter group. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the result of testing an analyzer on text along with {@link Response}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Response analyzeWithResponse(String indexName, AnalyzeRequest request, - RequestOptions requestOptions, Context context) { - final String accept = "application/json; odata.metadata=minimal"; - UUID xMsClientRequestIdInternal = null; - if (requestOptions != null) { - xMsClientRequestIdInternal = requestOptions.getXMsClientRequestId(); - } - UUID xMsClientRequestId = xMsClientRequestIdInternal; - return service.analyzeSync(this.client.getEndpoint(), indexName, xMsClientRequestId, - this.client.getApiVersion(), accept, request, context); - } - - /** - * Shows how an analyzer breaks text into tokens. - * - * @param indexName The name of the index for which to test an analyzer. - * @param request The text and analyzer or analysis components to test. - * @param requestOptions Parameter group. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the result of testing an analyzer on text. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public AnalyzeResult analyze(String indexName, AnalyzeRequest request, RequestOptions requestOptions) { - return analyzeWithResponse(indexName, request, requestOptions, Context.NONE).getValue(); - } -} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/implementation/SearchServiceClientImpl.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/implementation/SearchServiceClientImpl.java deleted file mode 100644 index 027aa537544a..000000000000 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/implementation/SearchServiceClientImpl.java +++ /dev/null @@ -1,358 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -package com.azure.search.documents.indexes.implementation; - -import com.azure.core.annotation.ExpectedResponses; -import com.azure.core.annotation.Get; -import com.azure.core.annotation.HeaderParam; -import com.azure.core.annotation.Host; -import com.azure.core.annotation.HostParam; -import com.azure.core.annotation.QueryParam; -import com.azure.core.annotation.ReturnType; -import com.azure.core.annotation.ServiceInterface; -import com.azure.core.annotation.ServiceMethod; -import com.azure.core.annotation.UnexpectedResponseExceptionType; -import com.azure.core.http.HttpPipeline; -import com.azure.core.http.HttpPipelineBuilder; -import com.azure.core.http.policy.RetryPolicy; -import com.azure.core.http.policy.UserAgentPolicy; -import com.azure.core.http.rest.Response; -import com.azure.core.http.rest.RestProxy; -import com.azure.core.util.Context; -import com.azure.core.util.FluxUtil; -import com.azure.core.util.serializer.JacksonAdapter; -import com.azure.core.util.serializer.SerializerAdapter; -import com.azure.search.documents.indexes.implementation.models.ErrorResponseException; -import com.azure.search.documents.indexes.implementation.models.RequestOptions; -import com.azure.search.documents.indexes.models.SearchServiceStatistics; -import java.util.UUID; -import reactor.core.publisher.Mono; - -/** - * Initializes a new instance of the SearchServiceClient type. - */ -public final class SearchServiceClientImpl { - /** - * The proxy service used to perform REST calls. - */ - private final SearchServiceClientService service; - - /** - * The endpoint URL of the search service. - */ - private final String endpoint; - - /** - * Gets The endpoint URL of the search service. - * - * @return the endpoint value. - */ - public String getEndpoint() { - return this.endpoint; - } - - /** - * Api Version. - */ - private final String apiVersion; - - /** - * Gets Api Version. - * - * @return the apiVersion value. - */ - public String getApiVersion() { - return this.apiVersion; - } - - /** - * The HTTP pipeline to send requests through. - */ - private final HttpPipeline httpPipeline; - - /** - * Gets The HTTP pipeline to send requests through. - * - * @return the httpPipeline value. - */ - public HttpPipeline getHttpPipeline() { - return this.httpPipeline; - } - - /** - * The serializer to serialize an object into a string. - */ - private final SerializerAdapter serializerAdapter; - - /** - * Gets The serializer to serialize an object into a string. - * - * @return the serializerAdapter value. - */ - public SerializerAdapter getSerializerAdapter() { - return this.serializerAdapter; - } - - /** - * The DataSourcesImpl object to access its operations. - */ - private final DataSourcesImpl dataSources; - - /** - * Gets the DataSourcesImpl object to access its operations. - * - * @return the DataSourcesImpl object. - */ - public DataSourcesImpl getDataSources() { - return this.dataSources; - } - - /** - * The IndexersImpl object to access its operations. - */ - private final IndexersImpl indexers; - - /** - * Gets the IndexersImpl object to access its operations. - * - * @return the IndexersImpl object. - */ - public IndexersImpl getIndexers() { - return this.indexers; - } - - /** - * The SkillsetsImpl object to access its operations. - */ - private final SkillsetsImpl skillsets; - - /** - * Gets the SkillsetsImpl object to access its operations. - * - * @return the SkillsetsImpl object. - */ - public SkillsetsImpl getSkillsets() { - return this.skillsets; - } - - /** - * The SynonymMapsImpl object to access its operations. - */ - private final SynonymMapsImpl synonymMaps; - - /** - * Gets the SynonymMapsImpl object to access its operations. - * - * @return the SynonymMapsImpl object. - */ - public SynonymMapsImpl getSynonymMaps() { - return this.synonymMaps; - } - - /** - * The IndexesImpl object to access its operations. - */ - private final IndexesImpl indexes; - - /** - * Gets the IndexesImpl object to access its operations. - * - * @return the IndexesImpl object. - */ - public IndexesImpl getIndexes() { - return this.indexes; - } - - /** - * The AliasesImpl object to access its operations. - */ - private final AliasesImpl aliases; - - /** - * Gets the AliasesImpl object to access its operations. - * - * @return the AliasesImpl object. - */ - public AliasesImpl getAliases() { - return this.aliases; - } - - /** - * Initializes an instance of SearchServiceClient client. - * - * @param endpoint The endpoint URL of the search service. - * @param apiVersion Api Version. - */ - public SearchServiceClientImpl(String endpoint, String apiVersion) { - this(new HttpPipelineBuilder().policies(new UserAgentPolicy(), new RetryPolicy()).build(), - JacksonAdapter.createDefaultSerializerAdapter(), endpoint, apiVersion); - } - - /** - * Initializes an instance of SearchServiceClient client. - * - * @param httpPipeline The HTTP pipeline to send requests through. - * @param endpoint The endpoint URL of the search service. - * @param apiVersion Api Version. - */ - public SearchServiceClientImpl(HttpPipeline httpPipeline, String endpoint, String apiVersion) { - this(httpPipeline, JacksonAdapter.createDefaultSerializerAdapter(), endpoint, apiVersion); - } - - /** - * Initializes an instance of SearchServiceClient client. - * - * @param httpPipeline The HTTP pipeline to send requests through. - * @param serializerAdapter The serializer to serialize an object into a string. - * @param endpoint The endpoint URL of the search service. - * @param apiVersion Api Version. - */ - public SearchServiceClientImpl(HttpPipeline httpPipeline, SerializerAdapter serializerAdapter, String endpoint, - String apiVersion) { - this.httpPipeline = httpPipeline; - this.serializerAdapter = serializerAdapter; - this.endpoint = endpoint; - this.apiVersion = apiVersion; - this.dataSources = new DataSourcesImpl(this); - this.indexers = new IndexersImpl(this); - this.skillsets = new SkillsetsImpl(this); - this.synonymMaps = new SynonymMapsImpl(this); - this.indexes = new IndexesImpl(this); - this.aliases = new AliasesImpl(this); - this.service - = RestProxy.create(SearchServiceClientService.class, this.httpPipeline, this.getSerializerAdapter()); - } - - /** - * The interface defining all the services for SearchServiceClient to be used by the proxy service to perform REST - * calls. - */ - @Host("{endpoint}") - @ServiceInterface(name = "SearchServiceClient") - public interface SearchServiceClientService { - @Get("/servicestats") - @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(ErrorResponseException.class) - Mono> getServiceStatistics(@HostParam("endpoint") String endpoint, - @HeaderParam("x-ms-client-request-id") UUID xMsClientRequestId, - @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, Context context); - - @Get("/servicestats") - @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(ErrorResponseException.class) - Response getServiceStatisticsSync(@HostParam("endpoint") String endpoint, - @HeaderParam("x-ms-client-request-id") UUID xMsClientRequestId, - @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, Context context); - } - - /** - * Gets service level statistics for a search service. - * - * @param requestOptions Parameter group. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return service level statistics for a search service along with {@link Response} on successful completion of - * {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> - getServiceStatisticsWithResponseAsync(RequestOptions requestOptions) { - return FluxUtil.withContext(context -> getServiceStatisticsWithResponseAsync(requestOptions, context)); - } - - /** - * Gets service level statistics for a search service. - * - * @param requestOptions Parameter group. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return service level statistics for a search service along with {@link Response} on successful completion of - * {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> getServiceStatisticsWithResponseAsync(RequestOptions requestOptions, - Context context) { - final String accept = "application/json; odata.metadata=minimal"; - UUID xMsClientRequestIdInternal = null; - if (requestOptions != null) { - xMsClientRequestIdInternal = requestOptions.getXMsClientRequestId(); - } - UUID xMsClientRequestId = xMsClientRequestIdInternal; - return service.getServiceStatistics(this.getEndpoint(), xMsClientRequestId, this.getApiVersion(), accept, - context); - } - - /** - * Gets service level statistics for a search service. - * - * @param requestOptions Parameter group. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return service level statistics for a search service on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono getServiceStatisticsAsync(RequestOptions requestOptions) { - return getServiceStatisticsWithResponseAsync(requestOptions).flatMap(res -> Mono.justOrEmpty(res.getValue())); - } - - /** - * Gets service level statistics for a search service. - * - * @param requestOptions Parameter group. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return service level statistics for a search service on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono getServiceStatisticsAsync(RequestOptions requestOptions, Context context) { - return getServiceStatisticsWithResponseAsync(requestOptions, context) - .flatMap(res -> Mono.justOrEmpty(res.getValue())); - } - - /** - * Gets service level statistics for a search service. - * - * @param requestOptions Parameter group. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return service level statistics for a search service along with {@link Response}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Response getServiceStatisticsWithResponse(RequestOptions requestOptions, - Context context) { - final String accept = "application/json; odata.metadata=minimal"; - UUID xMsClientRequestIdInternal = null; - if (requestOptions != null) { - xMsClientRequestIdInternal = requestOptions.getXMsClientRequestId(); - } - UUID xMsClientRequestId = xMsClientRequestIdInternal; - return service.getServiceStatisticsSync(this.getEndpoint(), xMsClientRequestId, this.getApiVersion(), accept, - context); - } - - /** - * Gets service level statistics for a search service. - * - * @param requestOptions Parameter group. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return service level statistics for a search service. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public SearchServiceStatistics getServiceStatistics(RequestOptions requestOptions) { - return getServiceStatisticsWithResponse(requestOptions, Context.NONE).getValue(); - } -} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/implementation/SkillsetsImpl.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/implementation/SkillsetsImpl.java deleted file mode 100644 index b6b213e21df0..000000000000 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/implementation/SkillsetsImpl.java +++ /dev/null @@ -1,945 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -package com.azure.search.documents.indexes.implementation; - -import com.azure.core.annotation.BodyParam; -import com.azure.core.annotation.Delete; -import com.azure.core.annotation.ExpectedResponses; -import com.azure.core.annotation.Get; -import com.azure.core.annotation.HeaderParam; -import com.azure.core.annotation.Host; -import com.azure.core.annotation.HostParam; -import com.azure.core.annotation.PathParam; -import com.azure.core.annotation.Post; -import com.azure.core.annotation.Put; -import com.azure.core.annotation.QueryParam; -import com.azure.core.annotation.ReturnType; -import com.azure.core.annotation.ServiceInterface; -import com.azure.core.annotation.ServiceMethod; -import com.azure.core.annotation.UnexpectedResponseExceptionType; -import com.azure.core.http.rest.Response; -import com.azure.core.http.rest.RestProxy; -import com.azure.core.util.Context; -import com.azure.core.util.FluxUtil; -import com.azure.search.documents.indexes.implementation.models.ErrorResponseException; -import com.azure.search.documents.indexes.implementation.models.ListSkillsetsResult; -import com.azure.search.documents.indexes.implementation.models.RequestOptions; -import com.azure.search.documents.indexes.implementation.models.SkillNames; -import com.azure.search.documents.indexes.models.SearchIndexerSkillset; -import java.util.UUID; -import reactor.core.publisher.Mono; - -/** - * An instance of this class provides access to all the operations defined in Skillsets. - */ -public final class SkillsetsImpl { - /** - * The proxy service used to perform REST calls. - */ - private final SkillsetsService service; - - /** - * The service client containing this operation class. - */ - private final SearchServiceClientImpl client; - - /** - * Initializes an instance of SkillsetsImpl. - * - * @param client the instance of the service client containing this operation class. - */ - SkillsetsImpl(SearchServiceClientImpl client) { - this.service - = RestProxy.create(SkillsetsService.class, client.getHttpPipeline(), client.getSerializerAdapter()); - this.client = client; - } - - /** - * The interface defining all the services for SearchServiceClientSkillsets to be used by the proxy service to - * perform REST calls. - */ - @Host("{endpoint}") - @ServiceInterface(name = "SearchServiceClientS") - public interface SkillsetsService { - @Put("/skillsets('{skillsetName}')") - @ExpectedResponses({ 200, 201 }) - @UnexpectedResponseExceptionType(ErrorResponseException.class) - Mono> createOrUpdate(@HostParam("endpoint") String endpoint, - @PathParam("skillsetName") String skillsetName, - @HeaderParam("x-ms-client-request-id") UUID xMsClientRequestId, @HeaderParam("If-Match") String ifMatch, - @HeaderParam("If-None-Match") String ifNoneMatch, @HeaderParam("Prefer") String prefer, - @QueryParam("api-version") String apiVersion, - @QueryParam("ignoreResetRequirements") Boolean skipIndexerResetRequirementForCache, - @QueryParam("disableCacheReprocessingChangeDetection") Boolean disableCacheReprocessingChangeDetection, - @HeaderParam("Accept") String accept, @BodyParam("application/json") SearchIndexerSkillset skillset, - Context context); - - @Put("/skillsets('{skillsetName}')") - @ExpectedResponses({ 200, 201 }) - @UnexpectedResponseExceptionType(ErrorResponseException.class) - Response createOrUpdateSync(@HostParam("endpoint") String endpoint, - @PathParam("skillsetName") String skillsetName, - @HeaderParam("x-ms-client-request-id") UUID xMsClientRequestId, @HeaderParam("If-Match") String ifMatch, - @HeaderParam("If-None-Match") String ifNoneMatch, @HeaderParam("Prefer") String prefer, - @QueryParam("api-version") String apiVersion, - @QueryParam("ignoreResetRequirements") Boolean skipIndexerResetRequirementForCache, - @QueryParam("disableCacheReprocessingChangeDetection") Boolean disableCacheReprocessingChangeDetection, - @HeaderParam("Accept") String accept, @BodyParam("application/json") SearchIndexerSkillset skillset, - Context context); - - @Delete("/skillsets('{skillsetName}')") - @ExpectedResponses({ 204, 404 }) - @UnexpectedResponseExceptionType(ErrorResponseException.class) - Mono> delete(@HostParam("endpoint") String endpoint, - @PathParam("skillsetName") String skillsetName, - @HeaderParam("x-ms-client-request-id") UUID xMsClientRequestId, @HeaderParam("If-Match") String ifMatch, - @HeaderParam("If-None-Match") String ifNoneMatch, @QueryParam("api-version") String apiVersion, - @HeaderParam("Accept") String accept, Context context); - - @Delete("/skillsets('{skillsetName}')") - @ExpectedResponses({ 204, 404 }) - @UnexpectedResponseExceptionType(ErrorResponseException.class) - Response deleteSync(@HostParam("endpoint") String endpoint, - @PathParam("skillsetName") String skillsetName, - @HeaderParam("x-ms-client-request-id") UUID xMsClientRequestId, @HeaderParam("If-Match") String ifMatch, - @HeaderParam("If-None-Match") String ifNoneMatch, @QueryParam("api-version") String apiVersion, - @HeaderParam("Accept") String accept, Context context); - - @Get("/skillsets('{skillsetName}')") - @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(ErrorResponseException.class) - Mono> get(@HostParam("endpoint") String endpoint, - @PathParam("skillsetName") String skillsetName, - @HeaderParam("x-ms-client-request-id") UUID xMsClientRequestId, - @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, Context context); - - @Get("/skillsets('{skillsetName}')") - @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(ErrorResponseException.class) - Response getSync(@HostParam("endpoint") String endpoint, - @PathParam("skillsetName") String skillsetName, - @HeaderParam("x-ms-client-request-id") UUID xMsClientRequestId, - @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, Context context); - - @Get("/skillsets") - @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(ErrorResponseException.class) - Mono> list(@HostParam("endpoint") String endpoint, - @QueryParam("$select") String select, @HeaderParam("x-ms-client-request-id") UUID xMsClientRequestId, - @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, Context context); - - @Get("/skillsets") - @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(ErrorResponseException.class) - Response listSync(@HostParam("endpoint") String endpoint, - @QueryParam("$select") String select, @HeaderParam("x-ms-client-request-id") UUID xMsClientRequestId, - @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, Context context); - - @Post("/skillsets") - @ExpectedResponses({ 201 }) - @UnexpectedResponseExceptionType(ErrorResponseException.class) - Mono> create(@HostParam("endpoint") String endpoint, - @HeaderParam("x-ms-client-request-id") UUID xMsClientRequestId, - @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, - @BodyParam("application/json") SearchIndexerSkillset skillset, Context context); - - @Post("/skillsets") - @ExpectedResponses({ 201 }) - @UnexpectedResponseExceptionType(ErrorResponseException.class) - Response createSync(@HostParam("endpoint") String endpoint, - @HeaderParam("x-ms-client-request-id") UUID xMsClientRequestId, - @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, - @BodyParam("application/json") SearchIndexerSkillset skillset, Context context); - - @Post("/skillsets('{skillsetName}')/search.resetskills") - @ExpectedResponses({ 204 }) - @UnexpectedResponseExceptionType(ErrorResponseException.class) - Mono> resetSkills(@HostParam("endpoint") String endpoint, - @PathParam("skillsetName") String skillsetName, - @HeaderParam("x-ms-client-request-id") UUID xMsClientRequestId, - @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, - @BodyParam("application/json") SkillNames skillNames, Context context); - - @Post("/skillsets('{skillsetName}')/search.resetskills") - @ExpectedResponses({ 204 }) - @UnexpectedResponseExceptionType(ErrorResponseException.class) - Response resetSkillsSync(@HostParam("endpoint") String endpoint, - @PathParam("skillsetName") String skillsetName, - @HeaderParam("x-ms-client-request-id") UUID xMsClientRequestId, - @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, - @BodyParam("application/json") SkillNames skillNames, Context context); - } - - /** - * Creates a new skillset in a search service or updates the skillset if it already exists. - * - * @param skillsetName The name of the skillset to create or update. - * @param skillset The skillset containing one or more skills to create or update in a search service. - * @param ifMatch Defines the If-Match condition. The operation will be performed only if the ETag on the server - * matches this value. - * @param ifNoneMatch Defines the If-None-Match condition. The operation will be performed only if the ETag on the - * server does not match this value. - * @param skipIndexerResetRequirementForCache Ignores cache reset requirements. - * @param disableCacheReprocessingChangeDetection Disables cache reprocessing change detection. - * @param requestOptions Parameter group. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a list of skills along with {@link Response} on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> createOrUpdateWithResponseAsync(String skillsetName, - SearchIndexerSkillset skillset, String ifMatch, String ifNoneMatch, Boolean skipIndexerResetRequirementForCache, - Boolean disableCacheReprocessingChangeDetection, RequestOptions requestOptions) { - return FluxUtil - .withContext(context -> createOrUpdateWithResponseAsync(skillsetName, skillset, ifMatch, ifNoneMatch, - skipIndexerResetRequirementForCache, disableCacheReprocessingChangeDetection, requestOptions, context)); - } - - /** - * Creates a new skillset in a search service or updates the skillset if it already exists. - * - * @param skillsetName The name of the skillset to create or update. - * @param skillset The skillset containing one or more skills to create or update in a search service. - * @param ifMatch Defines the If-Match condition. The operation will be performed only if the ETag on the server - * matches this value. - * @param ifNoneMatch Defines the If-None-Match condition. The operation will be performed only if the ETag on the - * server does not match this value. - * @param skipIndexerResetRequirementForCache Ignores cache reset requirements. - * @param disableCacheReprocessingChangeDetection Disables cache reprocessing change detection. - * @param requestOptions Parameter group. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a list of skills along with {@link Response} on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> createOrUpdateWithResponseAsync(String skillsetName, - SearchIndexerSkillset skillset, String ifMatch, String ifNoneMatch, Boolean skipIndexerResetRequirementForCache, - Boolean disableCacheReprocessingChangeDetection, RequestOptions requestOptions, Context context) { - final String prefer = "return=representation"; - final String accept = "application/json; odata.metadata=minimal"; - UUID xMsClientRequestIdInternal = null; - if (requestOptions != null) { - xMsClientRequestIdInternal = requestOptions.getXMsClientRequestId(); - } - UUID xMsClientRequestId = xMsClientRequestIdInternal; - return service.createOrUpdate(this.client.getEndpoint(), skillsetName, xMsClientRequestId, ifMatch, ifNoneMatch, - prefer, this.client.getApiVersion(), skipIndexerResetRequirementForCache, - disableCacheReprocessingChangeDetection, accept, skillset, context); - } - - /** - * Creates a new skillset in a search service or updates the skillset if it already exists. - * - * @param skillsetName The name of the skillset to create or update. - * @param skillset The skillset containing one or more skills to create or update in a search service. - * @param ifMatch Defines the If-Match condition. The operation will be performed only if the ETag on the server - * matches this value. - * @param ifNoneMatch Defines the If-None-Match condition. The operation will be performed only if the ETag on the - * server does not match this value. - * @param skipIndexerResetRequirementForCache Ignores cache reset requirements. - * @param disableCacheReprocessingChangeDetection Disables cache reprocessing change detection. - * @param requestOptions Parameter group. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a list of skills on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono createOrUpdateAsync(String skillsetName, SearchIndexerSkillset skillset, - String ifMatch, String ifNoneMatch, Boolean skipIndexerResetRequirementForCache, - Boolean disableCacheReprocessingChangeDetection, RequestOptions requestOptions) { - return createOrUpdateWithResponseAsync(skillsetName, skillset, ifMatch, ifNoneMatch, - skipIndexerResetRequirementForCache, disableCacheReprocessingChangeDetection, requestOptions) - .flatMap(res -> Mono.justOrEmpty(res.getValue())); - } - - /** - * Creates a new skillset in a search service or updates the skillset if it already exists. - * - * @param skillsetName The name of the skillset to create or update. - * @param skillset The skillset containing one or more skills to create or update in a search service. - * @param ifMatch Defines the If-Match condition. The operation will be performed only if the ETag on the server - * matches this value. - * @param ifNoneMatch Defines the If-None-Match condition. The operation will be performed only if the ETag on the - * server does not match this value. - * @param skipIndexerResetRequirementForCache Ignores cache reset requirements. - * @param disableCacheReprocessingChangeDetection Disables cache reprocessing change detection. - * @param requestOptions Parameter group. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a list of skills on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono createOrUpdateAsync(String skillsetName, SearchIndexerSkillset skillset, - String ifMatch, String ifNoneMatch, Boolean skipIndexerResetRequirementForCache, - Boolean disableCacheReprocessingChangeDetection, RequestOptions requestOptions, Context context) { - return createOrUpdateWithResponseAsync(skillsetName, skillset, ifMatch, ifNoneMatch, - skipIndexerResetRequirementForCache, disableCacheReprocessingChangeDetection, requestOptions, context) - .flatMap(res -> Mono.justOrEmpty(res.getValue())); - } - - /** - * Creates a new skillset in a search service or updates the skillset if it already exists. - * - * @param skillsetName The name of the skillset to create or update. - * @param skillset The skillset containing one or more skills to create or update in a search service. - * @param ifMatch Defines the If-Match condition. The operation will be performed only if the ETag on the server - * matches this value. - * @param ifNoneMatch Defines the If-None-Match condition. The operation will be performed only if the ETag on the - * server does not match this value. - * @param skipIndexerResetRequirementForCache Ignores cache reset requirements. - * @param disableCacheReprocessingChangeDetection Disables cache reprocessing change detection. - * @param requestOptions Parameter group. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a list of skills along with {@link Response}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Response createOrUpdateWithResponse(String skillsetName, - SearchIndexerSkillset skillset, String ifMatch, String ifNoneMatch, Boolean skipIndexerResetRequirementForCache, - Boolean disableCacheReprocessingChangeDetection, RequestOptions requestOptions, Context context) { - final String prefer = "return=representation"; - final String accept = "application/json; odata.metadata=minimal"; - UUID xMsClientRequestIdInternal = null; - if (requestOptions != null) { - xMsClientRequestIdInternal = requestOptions.getXMsClientRequestId(); - } - UUID xMsClientRequestId = xMsClientRequestIdInternal; - return service.createOrUpdateSync(this.client.getEndpoint(), skillsetName, xMsClientRequestId, ifMatch, - ifNoneMatch, prefer, this.client.getApiVersion(), skipIndexerResetRequirementForCache, - disableCacheReprocessingChangeDetection, accept, skillset, context); - } - - /** - * Creates a new skillset in a search service or updates the skillset if it already exists. - * - * @param skillsetName The name of the skillset to create or update. - * @param skillset The skillset containing one or more skills to create or update in a search service. - * @param ifMatch Defines the If-Match condition. The operation will be performed only if the ETag on the server - * matches this value. - * @param ifNoneMatch Defines the If-None-Match condition. The operation will be performed only if the ETag on the - * server does not match this value. - * @param skipIndexerResetRequirementForCache Ignores cache reset requirements. - * @param disableCacheReprocessingChangeDetection Disables cache reprocessing change detection. - * @param requestOptions Parameter group. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a list of skills. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public SearchIndexerSkillset createOrUpdate(String skillsetName, SearchIndexerSkillset skillset, String ifMatch, - String ifNoneMatch, Boolean skipIndexerResetRequirementForCache, - Boolean disableCacheReprocessingChangeDetection, RequestOptions requestOptions) { - return createOrUpdateWithResponse(skillsetName, skillset, ifMatch, ifNoneMatch, - skipIndexerResetRequirementForCache, disableCacheReprocessingChangeDetection, requestOptions, Context.NONE) - .getValue(); - } - - /** - * Deletes a skillset in a search service. - * - * @param skillsetName The name of the skillset to delete. - * @param ifMatch Defines the If-Match condition. The operation will be performed only if the ETag on the server - * matches this value. - * @param ifNoneMatch Defines the If-None-Match condition. The operation will be performed only if the ETag on the - * server does not match this value. - * @param requestOptions Parameter group. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the {@link Response} on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> deleteWithResponseAsync(String skillsetName, String ifMatch, String ifNoneMatch, - RequestOptions requestOptions) { - return FluxUtil.withContext( - context -> deleteWithResponseAsync(skillsetName, ifMatch, ifNoneMatch, requestOptions, context)); - } - - /** - * Deletes a skillset in a search service. - * - * @param skillsetName The name of the skillset to delete. - * @param ifMatch Defines the If-Match condition. The operation will be performed only if the ETag on the server - * matches this value. - * @param ifNoneMatch Defines the If-None-Match condition. The operation will be performed only if the ETag on the - * server does not match this value. - * @param requestOptions Parameter group. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the {@link Response} on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> deleteWithResponseAsync(String skillsetName, String ifMatch, String ifNoneMatch, - RequestOptions requestOptions, Context context) { - final String accept = "application/json; odata.metadata=minimal"; - UUID xMsClientRequestIdInternal = null; - if (requestOptions != null) { - xMsClientRequestIdInternal = requestOptions.getXMsClientRequestId(); - } - UUID xMsClientRequestId = xMsClientRequestIdInternal; - return service.delete(this.client.getEndpoint(), skillsetName, xMsClientRequestId, ifMatch, ifNoneMatch, - this.client.getApiVersion(), accept, context); - } - - /** - * Deletes a skillset in a search service. - * - * @param skillsetName The name of the skillset to delete. - * @param ifMatch Defines the If-Match condition. The operation will be performed only if the ETag on the server - * matches this value. - * @param ifNoneMatch Defines the If-None-Match condition. The operation will be performed only if the ETag on the - * server does not match this value. - * @param requestOptions Parameter group. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return A {@link Mono} that completes when a successful response is received. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono deleteAsync(String skillsetName, String ifMatch, String ifNoneMatch, - RequestOptions requestOptions) { - return deleteWithResponseAsync(skillsetName, ifMatch, ifNoneMatch, requestOptions) - .flatMap(ignored -> Mono.empty()); - } - - /** - * Deletes a skillset in a search service. - * - * @param skillsetName The name of the skillset to delete. - * @param ifMatch Defines the If-Match condition. The operation will be performed only if the ETag on the server - * matches this value. - * @param ifNoneMatch Defines the If-None-Match condition. The operation will be performed only if the ETag on the - * server does not match this value. - * @param requestOptions Parameter group. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return A {@link Mono} that completes when a successful response is received. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono deleteAsync(String skillsetName, String ifMatch, String ifNoneMatch, - RequestOptions requestOptions, Context context) { - return deleteWithResponseAsync(skillsetName, ifMatch, ifNoneMatch, requestOptions, context) - .flatMap(ignored -> Mono.empty()); - } - - /** - * Deletes a skillset in a search service. - * - * @param skillsetName The name of the skillset to delete. - * @param ifMatch Defines the If-Match condition. The operation will be performed only if the ETag on the server - * matches this value. - * @param ifNoneMatch Defines the If-None-Match condition. The operation will be performed only if the ETag on the - * server does not match this value. - * @param requestOptions Parameter group. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the {@link Response}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Response deleteWithResponse(String skillsetName, String ifMatch, String ifNoneMatch, - RequestOptions requestOptions, Context context) { - final String accept = "application/json; odata.metadata=minimal"; - UUID xMsClientRequestIdInternal = null; - if (requestOptions != null) { - xMsClientRequestIdInternal = requestOptions.getXMsClientRequestId(); - } - UUID xMsClientRequestId = xMsClientRequestIdInternal; - return service.deleteSync(this.client.getEndpoint(), skillsetName, xMsClientRequestId, ifMatch, ifNoneMatch, - this.client.getApiVersion(), accept, context); - } - - /** - * Deletes a skillset in a search service. - * - * @param skillsetName The name of the skillset to delete. - * @param ifMatch Defines the If-Match condition. The operation will be performed only if the ETag on the server - * matches this value. - * @param ifNoneMatch Defines the If-None-Match condition. The operation will be performed only if the ETag on the - * server does not match this value. - * @param requestOptions Parameter group. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public void delete(String skillsetName, String ifMatch, String ifNoneMatch, RequestOptions requestOptions) { - deleteWithResponse(skillsetName, ifMatch, ifNoneMatch, requestOptions, Context.NONE); - } - - /** - * Retrieves a skillset in a search service. - * - * @param skillsetName The name of the skillset to retrieve. - * @param requestOptions Parameter group. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a list of skills along with {@link Response} on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> getWithResponseAsync(String skillsetName, - RequestOptions requestOptions) { - return FluxUtil.withContext(context -> getWithResponseAsync(skillsetName, requestOptions, context)); - } - - /** - * Retrieves a skillset in a search service. - * - * @param skillsetName The name of the skillset to retrieve. - * @param requestOptions Parameter group. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a list of skills along with {@link Response} on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> getWithResponseAsync(String skillsetName, - RequestOptions requestOptions, Context context) { - final String accept = "application/json; odata.metadata=minimal"; - UUID xMsClientRequestIdInternal = null; - if (requestOptions != null) { - xMsClientRequestIdInternal = requestOptions.getXMsClientRequestId(); - } - UUID xMsClientRequestId = xMsClientRequestIdInternal; - return service.get(this.client.getEndpoint(), skillsetName, xMsClientRequestId, this.client.getApiVersion(), - accept, context); - } - - /** - * Retrieves a skillset in a search service. - * - * @param skillsetName The name of the skillset to retrieve. - * @param requestOptions Parameter group. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a list of skills on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono getAsync(String skillsetName, RequestOptions requestOptions) { - return getWithResponseAsync(skillsetName, requestOptions).flatMap(res -> Mono.justOrEmpty(res.getValue())); - } - - /** - * Retrieves a skillset in a search service. - * - * @param skillsetName The name of the skillset to retrieve. - * @param requestOptions Parameter group. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a list of skills on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono getAsync(String skillsetName, RequestOptions requestOptions, Context context) { - return getWithResponseAsync(skillsetName, requestOptions, context) - .flatMap(res -> Mono.justOrEmpty(res.getValue())); - } - - /** - * Retrieves a skillset in a search service. - * - * @param skillsetName The name of the skillset to retrieve. - * @param requestOptions Parameter group. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a list of skills along with {@link Response}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Response getWithResponse(String skillsetName, RequestOptions requestOptions, - Context context) { - final String accept = "application/json; odata.metadata=minimal"; - UUID xMsClientRequestIdInternal = null; - if (requestOptions != null) { - xMsClientRequestIdInternal = requestOptions.getXMsClientRequestId(); - } - UUID xMsClientRequestId = xMsClientRequestIdInternal; - return service.getSync(this.client.getEndpoint(), skillsetName, xMsClientRequestId, this.client.getApiVersion(), - accept, context); - } - - /** - * Retrieves a skillset in a search service. - * - * @param skillsetName The name of the skillset to retrieve. - * @param requestOptions Parameter group. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a list of skills. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public SearchIndexerSkillset get(String skillsetName, RequestOptions requestOptions) { - return getWithResponse(skillsetName, requestOptions, Context.NONE).getValue(); - } - - /** - * List all skillsets in a search service. - * - * @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. - * @param requestOptions Parameter group. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return response from a list skillset request along with {@link Response} on successful completion of - * {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> listWithResponseAsync(String select, RequestOptions requestOptions) { - return FluxUtil.withContext(context -> listWithResponseAsync(select, requestOptions, context)); - } - - /** - * List all skillsets in a search service. - * - * @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. - * @param requestOptions Parameter group. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return response from a list skillset request along with {@link Response} on successful completion of - * {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> listWithResponseAsync(String select, RequestOptions requestOptions, - Context context) { - final String accept = "application/json; odata.metadata=minimal"; - UUID xMsClientRequestIdInternal = null; - if (requestOptions != null) { - xMsClientRequestIdInternal = requestOptions.getXMsClientRequestId(); - } - UUID xMsClientRequestId = xMsClientRequestIdInternal; - return service.list(this.client.getEndpoint(), select, xMsClientRequestId, this.client.getApiVersion(), accept, - context); - } - - /** - * List all skillsets in a search service. - * - * @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. - * @param requestOptions Parameter group. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return response from a list skillset request on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono listAsync(String select, RequestOptions requestOptions) { - return listWithResponseAsync(select, requestOptions).flatMap(res -> Mono.justOrEmpty(res.getValue())); - } - - /** - * List all skillsets in a search service. - * - * @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. - * @param requestOptions Parameter group. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return response from a list skillset request on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono listAsync(String select, RequestOptions requestOptions, Context context) { - return listWithResponseAsync(select, requestOptions, context).flatMap(res -> Mono.justOrEmpty(res.getValue())); - } - - /** - * List all skillsets in a search service. - * - * @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. - * @param requestOptions Parameter group. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return response from a list skillset request along with {@link Response}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Response listWithResponse(String select, RequestOptions requestOptions, - Context context) { - final String accept = "application/json; odata.metadata=minimal"; - UUID xMsClientRequestIdInternal = null; - if (requestOptions != null) { - xMsClientRequestIdInternal = requestOptions.getXMsClientRequestId(); - } - UUID xMsClientRequestId = xMsClientRequestIdInternal; - return service.listSync(this.client.getEndpoint(), select, xMsClientRequestId, this.client.getApiVersion(), - accept, context); - } - - /** - * List all skillsets in a search service. - * - * @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. - * @param requestOptions Parameter group. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return response from a list skillset request. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public ListSkillsetsResult list(String select, RequestOptions requestOptions) { - return listWithResponse(select, requestOptions, Context.NONE).getValue(); - } - - /** - * Creates a new skillset in a search service. - * - * @param skillset The skillset containing one or more skills to create in a search service. - * @param requestOptions Parameter group. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a list of skills along with {@link Response} on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> createWithResponseAsync(SearchIndexerSkillset skillset, - RequestOptions requestOptions) { - return FluxUtil.withContext(context -> createWithResponseAsync(skillset, requestOptions, context)); - } - - /** - * Creates a new skillset in a search service. - * - * @param skillset The skillset containing one or more skills to create in a search service. - * @param requestOptions Parameter group. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a list of skills along with {@link Response} on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> createWithResponseAsync(SearchIndexerSkillset skillset, - RequestOptions requestOptions, Context context) { - final String accept = "application/json; odata.metadata=minimal"; - UUID xMsClientRequestIdInternal = null; - if (requestOptions != null) { - xMsClientRequestIdInternal = requestOptions.getXMsClientRequestId(); - } - UUID xMsClientRequestId = xMsClientRequestIdInternal; - return service.create(this.client.getEndpoint(), xMsClientRequestId, this.client.getApiVersion(), accept, - skillset, context); - } - - /** - * Creates a new skillset in a search service. - * - * @param skillset The skillset containing one or more skills to create in a search service. - * @param requestOptions Parameter group. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a list of skills on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono createAsync(SearchIndexerSkillset skillset, RequestOptions requestOptions) { - return createWithResponseAsync(skillset, requestOptions).flatMap(res -> Mono.justOrEmpty(res.getValue())); - } - - /** - * Creates a new skillset in a search service. - * - * @param skillset The skillset containing one or more skills to create in a search service. - * @param requestOptions Parameter group. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a list of skills on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono createAsync(SearchIndexerSkillset skillset, RequestOptions requestOptions, - Context context) { - return createWithResponseAsync(skillset, requestOptions, context) - .flatMap(res -> Mono.justOrEmpty(res.getValue())); - } - - /** - * Creates a new skillset in a search service. - * - * @param skillset The skillset containing one or more skills to create in a search service. - * @param requestOptions Parameter group. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a list of skills along with {@link Response}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Response createWithResponse(SearchIndexerSkillset skillset, - RequestOptions requestOptions, Context context) { - final String accept = "application/json; odata.metadata=minimal"; - UUID xMsClientRequestIdInternal = null; - if (requestOptions != null) { - xMsClientRequestIdInternal = requestOptions.getXMsClientRequestId(); - } - UUID xMsClientRequestId = xMsClientRequestIdInternal; - return service.createSync(this.client.getEndpoint(), xMsClientRequestId, this.client.getApiVersion(), accept, - skillset, context); - } - - /** - * Creates a new skillset in a search service. - * - * @param skillset The skillset containing one or more skills to create in a search service. - * @param requestOptions Parameter group. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return a list of skills. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public SearchIndexerSkillset create(SearchIndexerSkillset skillset, RequestOptions requestOptions) { - return createWithResponse(skillset, requestOptions, Context.NONE).getValue(); - } - - /** - * Reset an existing skillset in a search service. - * - * @param skillsetName The name of the skillset to reset. - * @param skillNames The names of skills to reset. - * @param requestOptions Parameter group. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the {@link Response} on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> resetSkillsWithResponseAsync(String skillsetName, SkillNames skillNames, - RequestOptions requestOptions) { - return FluxUtil - .withContext(context -> resetSkillsWithResponseAsync(skillsetName, skillNames, requestOptions, context)); - } - - /** - * Reset an existing skillset in a search service. - * - * @param skillsetName The name of the skillset to reset. - * @param skillNames The names of skills to reset. - * @param requestOptions Parameter group. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the {@link Response} on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> resetSkillsWithResponseAsync(String skillsetName, SkillNames skillNames, - RequestOptions requestOptions, Context context) { - final String accept = "application/json; odata.metadata=minimal"; - UUID xMsClientRequestIdInternal = null; - if (requestOptions != null) { - xMsClientRequestIdInternal = requestOptions.getXMsClientRequestId(); - } - UUID xMsClientRequestId = xMsClientRequestIdInternal; - return service.resetSkills(this.client.getEndpoint(), skillsetName, xMsClientRequestId, - this.client.getApiVersion(), accept, skillNames, context); - } - - /** - * Reset an existing skillset in a search service. - * - * @param skillsetName The name of the skillset to reset. - * @param skillNames The names of skills to reset. - * @param requestOptions Parameter group. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return A {@link Mono} that completes when a successful response is received. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono resetSkillsAsync(String skillsetName, SkillNames skillNames, RequestOptions requestOptions) { - return resetSkillsWithResponseAsync(skillsetName, skillNames, requestOptions).flatMap(ignored -> Mono.empty()); - } - - /** - * Reset an existing skillset in a search service. - * - * @param skillsetName The name of the skillset to reset. - * @param skillNames The names of skills to reset. - * @param requestOptions Parameter group. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return A {@link Mono} that completes when a successful response is received. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono resetSkillsAsync(String skillsetName, SkillNames skillNames, RequestOptions requestOptions, - Context context) { - return resetSkillsWithResponseAsync(skillsetName, skillNames, requestOptions, context) - .flatMap(ignored -> Mono.empty()); - } - - /** - * Reset an existing skillset in a search service. - * - * @param skillsetName The name of the skillset to reset. - * @param skillNames The names of skills to reset. - * @param requestOptions Parameter group. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the {@link Response}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Response resetSkillsWithResponse(String skillsetName, SkillNames skillNames, - RequestOptions requestOptions, Context context) { - final String accept = "application/json; odata.metadata=minimal"; - UUID xMsClientRequestIdInternal = null; - if (requestOptions != null) { - xMsClientRequestIdInternal = requestOptions.getXMsClientRequestId(); - } - UUID xMsClientRequestId = xMsClientRequestIdInternal; - return service.resetSkillsSync(this.client.getEndpoint(), skillsetName, xMsClientRequestId, - this.client.getApiVersion(), accept, skillNames, context); - } - - /** - * Reset an existing skillset in a search service. - * - * @param skillsetName The name of the skillset to reset. - * @param skillNames The names of skills to reset. - * @param requestOptions Parameter group. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public void resetSkills(String skillsetName, SkillNames skillNames, RequestOptions requestOptions) { - resetSkillsWithResponse(skillsetName, skillNames, requestOptions, Context.NONE); - } -} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/implementation/SynonymMapsImpl.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/implementation/SynonymMapsImpl.java deleted file mode 100644 index e6c6c4961d20..000000000000 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/implementation/SynonymMapsImpl.java +++ /dev/null @@ -1,774 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -package com.azure.search.documents.indexes.implementation; - -import com.azure.core.annotation.BodyParam; -import com.azure.core.annotation.Delete; -import com.azure.core.annotation.ExpectedResponses; -import com.azure.core.annotation.Get; -import com.azure.core.annotation.HeaderParam; -import com.azure.core.annotation.Host; -import com.azure.core.annotation.HostParam; -import com.azure.core.annotation.PathParam; -import com.azure.core.annotation.Post; -import com.azure.core.annotation.Put; -import com.azure.core.annotation.QueryParam; -import com.azure.core.annotation.ReturnType; -import com.azure.core.annotation.ServiceInterface; -import com.azure.core.annotation.ServiceMethod; -import com.azure.core.annotation.UnexpectedResponseExceptionType; -import com.azure.core.http.rest.Response; -import com.azure.core.http.rest.RestProxy; -import com.azure.core.util.Context; -import com.azure.core.util.FluxUtil; -import com.azure.search.documents.indexes.implementation.models.ErrorResponseException; -import com.azure.search.documents.indexes.implementation.models.ListSynonymMapsResult; -import com.azure.search.documents.indexes.implementation.models.RequestOptions; -import com.azure.search.documents.indexes.models.SynonymMap; -import java.util.UUID; -import reactor.core.publisher.Mono; - -/** - * An instance of this class provides access to all the operations defined in SynonymMaps. - */ -public final class SynonymMapsImpl { - /** - * The proxy service used to perform REST calls. - */ - private final SynonymMapsService service; - - /** - * The service client containing this operation class. - */ - private final SearchServiceClientImpl client; - - /** - * Initializes an instance of SynonymMapsImpl. - * - * @param client the instance of the service client containing this operation class. - */ - SynonymMapsImpl(SearchServiceClientImpl client) { - this.service - = RestProxy.create(SynonymMapsService.class, client.getHttpPipeline(), client.getSerializerAdapter()); - this.client = client; - } - - /** - * The interface defining all the services for SearchServiceClientSynonymMaps to be used by the proxy service to - * perform REST calls. - */ - @Host("{endpoint}") - @ServiceInterface(name = "SearchServiceClientS") - public interface SynonymMapsService { - @Put("/synonymmaps('{synonymMapName}')") - @ExpectedResponses({ 200, 201 }) - @UnexpectedResponseExceptionType(ErrorResponseException.class) - Mono> createOrUpdate(@HostParam("endpoint") String endpoint, - @PathParam("synonymMapName") String synonymMapName, - @HeaderParam("x-ms-client-request-id") UUID xMsClientRequestId, @HeaderParam("If-Match") String ifMatch, - @HeaderParam("If-None-Match") String ifNoneMatch, @HeaderParam("Prefer") String prefer, - @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, - @BodyParam("application/json") SynonymMap synonymMap, Context context); - - @Put("/synonymmaps('{synonymMapName}')") - @ExpectedResponses({ 200, 201 }) - @UnexpectedResponseExceptionType(ErrorResponseException.class) - Response createOrUpdateSync(@HostParam("endpoint") String endpoint, - @PathParam("synonymMapName") String synonymMapName, - @HeaderParam("x-ms-client-request-id") UUID xMsClientRequestId, @HeaderParam("If-Match") String ifMatch, - @HeaderParam("If-None-Match") String ifNoneMatch, @HeaderParam("Prefer") String prefer, - @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, - @BodyParam("application/json") SynonymMap synonymMap, Context context); - - @Delete("/synonymmaps('{synonymMapName}')") - @ExpectedResponses({ 204, 404 }) - @UnexpectedResponseExceptionType(ErrorResponseException.class) - Mono> delete(@HostParam("endpoint") String endpoint, - @PathParam("synonymMapName") String synonymMapName, - @HeaderParam("x-ms-client-request-id") UUID xMsClientRequestId, @HeaderParam("If-Match") String ifMatch, - @HeaderParam("If-None-Match") String ifNoneMatch, @QueryParam("api-version") String apiVersion, - @HeaderParam("Accept") String accept, Context context); - - @Delete("/synonymmaps('{synonymMapName}')") - @ExpectedResponses({ 204, 404 }) - @UnexpectedResponseExceptionType(ErrorResponseException.class) - Response deleteSync(@HostParam("endpoint") String endpoint, - @PathParam("synonymMapName") String synonymMapName, - @HeaderParam("x-ms-client-request-id") UUID xMsClientRequestId, @HeaderParam("If-Match") String ifMatch, - @HeaderParam("If-None-Match") String ifNoneMatch, @QueryParam("api-version") String apiVersion, - @HeaderParam("Accept") String accept, Context context); - - @Get("/synonymmaps('{synonymMapName}')") - @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(ErrorResponseException.class) - Mono> get(@HostParam("endpoint") String endpoint, - @PathParam("synonymMapName") String synonymMapName, - @HeaderParam("x-ms-client-request-id") UUID xMsClientRequestId, - @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, Context context); - - @Get("/synonymmaps('{synonymMapName}')") - @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(ErrorResponseException.class) - Response getSync(@HostParam("endpoint") String endpoint, - @PathParam("synonymMapName") String synonymMapName, - @HeaderParam("x-ms-client-request-id") UUID xMsClientRequestId, - @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, Context context); - - @Get("/synonymmaps") - @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(ErrorResponseException.class) - Mono> list(@HostParam("endpoint") String endpoint, - @QueryParam("$select") String select, @HeaderParam("x-ms-client-request-id") UUID xMsClientRequestId, - @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, Context context); - - @Get("/synonymmaps") - @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(ErrorResponseException.class) - Response listSync(@HostParam("endpoint") String endpoint, - @QueryParam("$select") String select, @HeaderParam("x-ms-client-request-id") UUID xMsClientRequestId, - @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, Context context); - - @Post("/synonymmaps") - @ExpectedResponses({ 201 }) - @UnexpectedResponseExceptionType(ErrorResponseException.class) - Mono> create(@HostParam("endpoint") String endpoint, - @HeaderParam("x-ms-client-request-id") UUID xMsClientRequestId, - @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, - @BodyParam("application/json") SynonymMap synonymMap, Context context); - - @Post("/synonymmaps") - @ExpectedResponses({ 201 }) - @UnexpectedResponseExceptionType(ErrorResponseException.class) - Response createSync(@HostParam("endpoint") String endpoint, - @HeaderParam("x-ms-client-request-id") UUID xMsClientRequestId, - @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, - @BodyParam("application/json") SynonymMap synonymMap, Context context); - } - - /** - * Creates a new synonym map or updates a synonym map if it already exists. - * - * @param synonymMapName The name of the synonym map to create or update. - * @param synonymMap The definition of the synonym map to create or update. - * @param ifMatch Defines the If-Match condition. The operation will be performed only if the ETag on the server - * matches this value. - * @param ifNoneMatch Defines the If-None-Match condition. The operation will be performed only if the ETag on the - * server does not match this value. - * @param requestOptions Parameter group. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return represents a synonym map definition along with {@link Response} on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> createOrUpdateWithResponseAsync(String synonymMapName, SynonymMap synonymMap, - String ifMatch, String ifNoneMatch, RequestOptions requestOptions) { - return FluxUtil.withContext(context -> createOrUpdateWithResponseAsync(synonymMapName, synonymMap, ifMatch, - ifNoneMatch, requestOptions, context)); - } - - /** - * Creates a new synonym map or updates a synonym map if it already exists. - * - * @param synonymMapName The name of the synonym map to create or update. - * @param synonymMap The definition of the synonym map to create or update. - * @param ifMatch Defines the If-Match condition. The operation will be performed only if the ETag on the server - * matches this value. - * @param ifNoneMatch Defines the If-None-Match condition. The operation will be performed only if the ETag on the - * server does not match this value. - * @param requestOptions Parameter group. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return represents a synonym map definition along with {@link Response} on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> createOrUpdateWithResponseAsync(String synonymMapName, SynonymMap synonymMap, - String ifMatch, String ifNoneMatch, RequestOptions requestOptions, Context context) { - final String prefer = "return=representation"; - final String accept = "application/json; odata.metadata=minimal"; - UUID xMsClientRequestIdInternal = null; - if (requestOptions != null) { - xMsClientRequestIdInternal = requestOptions.getXMsClientRequestId(); - } - UUID xMsClientRequestId = xMsClientRequestIdInternal; - return service.createOrUpdate(this.client.getEndpoint(), synonymMapName, xMsClientRequestId, ifMatch, - ifNoneMatch, prefer, this.client.getApiVersion(), accept, synonymMap, context); - } - - /** - * Creates a new synonym map or updates a synonym map if it already exists. - * - * @param synonymMapName The name of the synonym map to create or update. - * @param synonymMap The definition of the synonym map to create or update. - * @param ifMatch Defines the If-Match condition. The operation will be performed only if the ETag on the server - * matches this value. - * @param ifNoneMatch Defines the If-None-Match condition. The operation will be performed only if the ETag on the - * server does not match this value. - * @param requestOptions Parameter group. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return represents a synonym map definition on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono createOrUpdateAsync(String synonymMapName, SynonymMap synonymMap, String ifMatch, - String ifNoneMatch, RequestOptions requestOptions) { - return createOrUpdateWithResponseAsync(synonymMapName, synonymMap, ifMatch, ifNoneMatch, requestOptions) - .flatMap(res -> Mono.justOrEmpty(res.getValue())); - } - - /** - * Creates a new synonym map or updates a synonym map if it already exists. - * - * @param synonymMapName The name of the synonym map to create or update. - * @param synonymMap The definition of the synonym map to create or update. - * @param ifMatch Defines the If-Match condition. The operation will be performed only if the ETag on the server - * matches this value. - * @param ifNoneMatch Defines the If-None-Match condition. The operation will be performed only if the ETag on the - * server does not match this value. - * @param requestOptions Parameter group. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return represents a synonym map definition on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono createOrUpdateAsync(String synonymMapName, SynonymMap synonymMap, String ifMatch, - String ifNoneMatch, RequestOptions requestOptions, Context context) { - return createOrUpdateWithResponseAsync(synonymMapName, synonymMap, ifMatch, ifNoneMatch, requestOptions, - context).flatMap(res -> Mono.justOrEmpty(res.getValue())); - } - - /** - * Creates a new synonym map or updates a synonym map if it already exists. - * - * @param synonymMapName The name of the synonym map to create or update. - * @param synonymMap The definition of the synonym map to create or update. - * @param ifMatch Defines the If-Match condition. The operation will be performed only if the ETag on the server - * matches this value. - * @param ifNoneMatch Defines the If-None-Match condition. The operation will be performed only if the ETag on the - * server does not match this value. - * @param requestOptions Parameter group. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return represents a synonym map definition along with {@link Response}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Response createOrUpdateWithResponse(String synonymMapName, SynonymMap synonymMap, String ifMatch, - String ifNoneMatch, RequestOptions requestOptions, Context context) { - final String prefer = "return=representation"; - final String accept = "application/json; odata.metadata=minimal"; - UUID xMsClientRequestIdInternal = null; - if (requestOptions != null) { - xMsClientRequestIdInternal = requestOptions.getXMsClientRequestId(); - } - UUID xMsClientRequestId = xMsClientRequestIdInternal; - return service.createOrUpdateSync(this.client.getEndpoint(), synonymMapName, xMsClientRequestId, ifMatch, - ifNoneMatch, prefer, this.client.getApiVersion(), accept, synonymMap, context); - } - - /** - * Creates a new synonym map or updates a synonym map if it already exists. - * - * @param synonymMapName The name of the synonym map to create or update. - * @param synonymMap The definition of the synonym map to create or update. - * @param ifMatch Defines the If-Match condition. The operation will be performed only if the ETag on the server - * matches this value. - * @param ifNoneMatch Defines the If-None-Match condition. The operation will be performed only if the ETag on the - * server does not match this value. - * @param requestOptions Parameter group. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return represents a synonym map definition. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public SynonymMap createOrUpdate(String synonymMapName, SynonymMap synonymMap, String ifMatch, String ifNoneMatch, - RequestOptions requestOptions) { - return createOrUpdateWithResponse(synonymMapName, synonymMap, ifMatch, ifNoneMatch, requestOptions, - Context.NONE).getValue(); - } - - /** - * Deletes a synonym map. - * - * @param synonymMapName The name of the synonym map to delete. - * @param ifMatch Defines the If-Match condition. The operation will be performed only if the ETag on the server - * matches this value. - * @param ifNoneMatch Defines the If-None-Match condition. The operation will be performed only if the ETag on the - * server does not match this value. - * @param requestOptions Parameter group. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the {@link Response} on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> deleteWithResponseAsync(String synonymMapName, String ifMatch, String ifNoneMatch, - RequestOptions requestOptions) { - return FluxUtil.withContext( - context -> deleteWithResponseAsync(synonymMapName, ifMatch, ifNoneMatch, requestOptions, context)); - } - - /** - * Deletes a synonym map. - * - * @param synonymMapName The name of the synonym map to delete. - * @param ifMatch Defines the If-Match condition. The operation will be performed only if the ETag on the server - * matches this value. - * @param ifNoneMatch Defines the If-None-Match condition. The operation will be performed only if the ETag on the - * server does not match this value. - * @param requestOptions Parameter group. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the {@link Response} on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> deleteWithResponseAsync(String synonymMapName, String ifMatch, String ifNoneMatch, - RequestOptions requestOptions, Context context) { - final String accept = "application/json; odata.metadata=minimal"; - UUID xMsClientRequestIdInternal = null; - if (requestOptions != null) { - xMsClientRequestIdInternal = requestOptions.getXMsClientRequestId(); - } - UUID xMsClientRequestId = xMsClientRequestIdInternal; - return service.delete(this.client.getEndpoint(), synonymMapName, xMsClientRequestId, ifMatch, ifNoneMatch, - this.client.getApiVersion(), accept, context); - } - - /** - * Deletes a synonym map. - * - * @param synonymMapName The name of the synonym map to delete. - * @param ifMatch Defines the If-Match condition. The operation will be performed only if the ETag on the server - * matches this value. - * @param ifNoneMatch Defines the If-None-Match condition. The operation will be performed only if the ETag on the - * server does not match this value. - * @param requestOptions Parameter group. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return A {@link Mono} that completes when a successful response is received. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono deleteAsync(String synonymMapName, String ifMatch, String ifNoneMatch, - RequestOptions requestOptions) { - return deleteWithResponseAsync(synonymMapName, ifMatch, ifNoneMatch, requestOptions) - .flatMap(ignored -> Mono.empty()); - } - - /** - * Deletes a synonym map. - * - * @param synonymMapName The name of the synonym map to delete. - * @param ifMatch Defines the If-Match condition. The operation will be performed only if the ETag on the server - * matches this value. - * @param ifNoneMatch Defines the If-None-Match condition. The operation will be performed only if the ETag on the - * server does not match this value. - * @param requestOptions Parameter group. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return A {@link Mono} that completes when a successful response is received. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono deleteAsync(String synonymMapName, String ifMatch, String ifNoneMatch, - RequestOptions requestOptions, Context context) { - return deleteWithResponseAsync(synonymMapName, ifMatch, ifNoneMatch, requestOptions, context) - .flatMap(ignored -> Mono.empty()); - } - - /** - * Deletes a synonym map. - * - * @param synonymMapName The name of the synonym map to delete. - * @param ifMatch Defines the If-Match condition. The operation will be performed only if the ETag on the server - * matches this value. - * @param ifNoneMatch Defines the If-None-Match condition. The operation will be performed only if the ETag on the - * server does not match this value. - * @param requestOptions Parameter group. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the {@link Response}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Response deleteWithResponse(String synonymMapName, String ifMatch, String ifNoneMatch, - RequestOptions requestOptions, Context context) { - final String accept = "application/json; odata.metadata=minimal"; - UUID xMsClientRequestIdInternal = null; - if (requestOptions != null) { - xMsClientRequestIdInternal = requestOptions.getXMsClientRequestId(); - } - UUID xMsClientRequestId = xMsClientRequestIdInternal; - return service.deleteSync(this.client.getEndpoint(), synonymMapName, xMsClientRequestId, ifMatch, ifNoneMatch, - this.client.getApiVersion(), accept, context); - } - - /** - * Deletes a synonym map. - * - * @param synonymMapName The name of the synonym map to delete. - * @param ifMatch Defines the If-Match condition. The operation will be performed only if the ETag on the server - * matches this value. - * @param ifNoneMatch Defines the If-None-Match condition. The operation will be performed only if the ETag on the - * server does not match this value. - * @param requestOptions Parameter group. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public void delete(String synonymMapName, String ifMatch, String ifNoneMatch, RequestOptions requestOptions) { - deleteWithResponse(synonymMapName, ifMatch, ifNoneMatch, requestOptions, Context.NONE); - } - - /** - * Retrieves a synonym map definition. - * - * @param synonymMapName The name of the synonym map to retrieve. - * @param requestOptions Parameter group. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return represents a synonym map definition along with {@link Response} on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> getWithResponseAsync(String synonymMapName, RequestOptions requestOptions) { - return FluxUtil.withContext(context -> getWithResponseAsync(synonymMapName, requestOptions, context)); - } - - /** - * Retrieves a synonym map definition. - * - * @param synonymMapName The name of the synonym map to retrieve. - * @param requestOptions Parameter group. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return represents a synonym map definition along with {@link Response} on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> getWithResponseAsync(String synonymMapName, RequestOptions requestOptions, - Context context) { - final String accept = "application/json; odata.metadata=minimal"; - UUID xMsClientRequestIdInternal = null; - if (requestOptions != null) { - xMsClientRequestIdInternal = requestOptions.getXMsClientRequestId(); - } - UUID xMsClientRequestId = xMsClientRequestIdInternal; - return service.get(this.client.getEndpoint(), synonymMapName, xMsClientRequestId, this.client.getApiVersion(), - accept, context); - } - - /** - * Retrieves a synonym map definition. - * - * @param synonymMapName The name of the synonym map to retrieve. - * @param requestOptions Parameter group. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return represents a synonym map definition on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono getAsync(String synonymMapName, RequestOptions requestOptions) { - return getWithResponseAsync(synonymMapName, requestOptions).flatMap(res -> Mono.justOrEmpty(res.getValue())); - } - - /** - * Retrieves a synonym map definition. - * - * @param synonymMapName The name of the synonym map to retrieve. - * @param requestOptions Parameter group. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return represents a synonym map definition on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono getAsync(String synonymMapName, RequestOptions requestOptions, Context context) { - return getWithResponseAsync(synonymMapName, requestOptions, context) - .flatMap(res -> Mono.justOrEmpty(res.getValue())); - } - - /** - * Retrieves a synonym map definition. - * - * @param synonymMapName The name of the synonym map to retrieve. - * @param requestOptions Parameter group. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return represents a synonym map definition along with {@link Response}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Response getWithResponse(String synonymMapName, RequestOptions requestOptions, Context context) { - final String accept = "application/json; odata.metadata=minimal"; - UUID xMsClientRequestIdInternal = null; - if (requestOptions != null) { - xMsClientRequestIdInternal = requestOptions.getXMsClientRequestId(); - } - UUID xMsClientRequestId = xMsClientRequestIdInternal; - return service.getSync(this.client.getEndpoint(), synonymMapName, xMsClientRequestId, - this.client.getApiVersion(), accept, context); - } - - /** - * Retrieves a synonym map definition. - * - * @param synonymMapName The name of the synonym map to retrieve. - * @param requestOptions Parameter group. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return represents a synonym map definition. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public SynonymMap get(String synonymMapName, RequestOptions requestOptions) { - return getWithResponse(synonymMapName, requestOptions, Context.NONE).getValue(); - } - - /** - * Lists all synonym maps available for a search service. - * - * @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. - * @param requestOptions Parameter group. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return response from a List SynonymMaps request along with {@link Response} on successful completion of - * {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> listWithResponseAsync(String select, RequestOptions requestOptions) { - return FluxUtil.withContext(context -> listWithResponseAsync(select, requestOptions, context)); - } - - /** - * Lists all synonym maps available for a search service. - * - * @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. - * @param requestOptions Parameter group. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return response from a List SynonymMaps request along with {@link Response} on successful completion of - * {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> listWithResponseAsync(String select, RequestOptions requestOptions, - Context context) { - final String accept = "application/json; odata.metadata=minimal"; - UUID xMsClientRequestIdInternal = null; - if (requestOptions != null) { - xMsClientRequestIdInternal = requestOptions.getXMsClientRequestId(); - } - UUID xMsClientRequestId = xMsClientRequestIdInternal; - return service.list(this.client.getEndpoint(), select, xMsClientRequestId, this.client.getApiVersion(), accept, - context); - } - - /** - * Lists all synonym maps available for a search service. - * - * @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. - * @param requestOptions Parameter group. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return response from a List SynonymMaps request on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono listAsync(String select, RequestOptions requestOptions) { - return listWithResponseAsync(select, requestOptions).flatMap(res -> Mono.justOrEmpty(res.getValue())); - } - - /** - * Lists all synonym maps available for a search service. - * - * @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. - * @param requestOptions Parameter group. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return response from a List SynonymMaps request on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono listAsync(String select, RequestOptions requestOptions, Context context) { - return listWithResponseAsync(select, requestOptions, context).flatMap(res -> Mono.justOrEmpty(res.getValue())); - } - - /** - * Lists all synonym maps available for a search service. - * - * @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. - * @param requestOptions Parameter group. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return response from a List SynonymMaps request along with {@link Response}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Response listWithResponse(String select, RequestOptions requestOptions, - Context context) { - final String accept = "application/json; odata.metadata=minimal"; - UUID xMsClientRequestIdInternal = null; - if (requestOptions != null) { - xMsClientRequestIdInternal = requestOptions.getXMsClientRequestId(); - } - UUID xMsClientRequestId = xMsClientRequestIdInternal; - return service.listSync(this.client.getEndpoint(), select, xMsClientRequestId, this.client.getApiVersion(), - accept, context); - } - - /** - * Lists all synonym maps available for a search service. - * - * @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. - * @param requestOptions Parameter group. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return response from a List SynonymMaps request. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public ListSynonymMapsResult list(String select, RequestOptions requestOptions) { - return listWithResponse(select, requestOptions, Context.NONE).getValue(); - } - - /** - * Creates a new synonym map. - * - * @param synonymMap The definition of the synonym map to create. - * @param requestOptions Parameter group. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return represents a synonym map definition along with {@link Response} on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> createWithResponseAsync(SynonymMap synonymMap, RequestOptions requestOptions) { - return FluxUtil.withContext(context -> createWithResponseAsync(synonymMap, requestOptions, context)); - } - - /** - * Creates a new synonym map. - * - * @param synonymMap The definition of the synonym map to create. - * @param requestOptions Parameter group. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return represents a synonym map definition along with {@link Response} on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> createWithResponseAsync(SynonymMap synonymMap, RequestOptions requestOptions, - Context context) { - final String accept = "application/json; odata.metadata=minimal"; - UUID xMsClientRequestIdInternal = null; - if (requestOptions != null) { - xMsClientRequestIdInternal = requestOptions.getXMsClientRequestId(); - } - UUID xMsClientRequestId = xMsClientRequestIdInternal; - return service.create(this.client.getEndpoint(), xMsClientRequestId, this.client.getApiVersion(), accept, - synonymMap, context); - } - - /** - * Creates a new synonym map. - * - * @param synonymMap The definition of the synonym map to create. - * @param requestOptions Parameter group. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return represents a synonym map definition on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono createAsync(SynonymMap synonymMap, RequestOptions requestOptions) { - return createWithResponseAsync(synonymMap, requestOptions).flatMap(res -> Mono.justOrEmpty(res.getValue())); - } - - /** - * Creates a new synonym map. - * - * @param synonymMap The definition of the synonym map to create. - * @param requestOptions Parameter group. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return represents a synonym map definition on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono createAsync(SynonymMap synonymMap, RequestOptions requestOptions, Context context) { - return createWithResponseAsync(synonymMap, requestOptions, context) - .flatMap(res -> Mono.justOrEmpty(res.getValue())); - } - - /** - * Creates a new synonym map. - * - * @param synonymMap The definition of the synonym map to create. - * @param requestOptions Parameter group. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return represents a synonym map definition along with {@link Response}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Response createWithResponse(SynonymMap synonymMap, RequestOptions requestOptions, - Context context) { - final String accept = "application/json; odata.metadata=minimal"; - UUID xMsClientRequestIdInternal = null; - if (requestOptions != null) { - xMsClientRequestIdInternal = requestOptions.getXMsClientRequestId(); - } - UUID xMsClientRequestId = xMsClientRequestIdInternal; - return service.createSync(this.client.getEndpoint(), xMsClientRequestId, this.client.getApiVersion(), accept, - synonymMap, context); - } - - /** - * Creates a new synonym map. - * - * @param synonymMap The definition of the synonym map to create. - * @param requestOptions Parameter group. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return represents a synonym map definition. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public SynonymMap create(SynonymMap synonymMap, RequestOptions requestOptions) { - return createWithResponse(synonymMap, requestOptions, Context.NONE).getValue(); - } -} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/implementation/models/EdgeNGramTokenFilterV1.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/implementation/models/EdgeNGramTokenFilterV1.java deleted file mode 100644 index d9920dde070d..000000000000 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/implementation/models/EdgeNGramTokenFilterV1.java +++ /dev/null @@ -1,184 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -package com.azure.search.documents.indexes.implementation.models; - -import com.azure.core.annotation.Fluent; -import com.azure.json.JsonReader; -import com.azure.json.JsonToken; -import com.azure.json.JsonWriter; -import com.azure.search.documents.indexes.models.EdgeNGramTokenFilterSide; -import com.azure.search.documents.indexes.models.TokenFilter; -import java.io.IOException; - -/** - * 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. - */ -@Fluent -public final class EdgeNGramTokenFilterV1 extends TokenFilter { - /* - * A URI fragment specifying the type of token filter. - */ - private String odataType = "#Microsoft.Azure.Search.EdgeNGramTokenFilter"; - - /* - * The minimum n-gram length. Default is 1. Must be less than the value of maxGram. - */ - private Integer minGram; - - /* - * The maximum n-gram length. Default is 2. - */ - private Integer maxGram; - - /* - * Specifies which side of the input the n-gram should be generated from. Default is "front". - */ - private EdgeNGramTokenFilterSide side; - - /** - * Creates an instance of EdgeNGramTokenFilterV1 class. - * - * @param name the name value to set. - */ - public EdgeNGramTokenFilterV1(String name) { - super(name); - } - - /** - * Get the odataType property: A URI fragment specifying the type of token filter. - * - * @return the odataType value. - */ - @Override - public String getOdataType() { - return this.odataType; - } - - /** - * Get the minGram property: The minimum n-gram length. Default is 1. Must be less than the value of maxGram. - * - * @return the minGram value. - */ - public Integer getMinGram() { - return this.minGram; - } - - /** - * Set the minGram property: The minimum n-gram length. Default is 1. Must be less than the value of maxGram. - * - * @param minGram the minGram value to set. - * @return the EdgeNGramTokenFilterV1 object itself. - */ - public EdgeNGramTokenFilterV1 setMinGram(Integer minGram) { - this.minGram = minGram; - return this; - } - - /** - * Get the maxGram property: The maximum n-gram length. Default is 2. - * - * @return the maxGram value. - */ - public Integer getMaxGram() { - return this.maxGram; - } - - /** - * Set the maxGram property: The maximum n-gram length. Default is 2. - * - * @param maxGram the maxGram value to set. - * @return the EdgeNGramTokenFilterV1 object itself. - */ - public EdgeNGramTokenFilterV1 setMaxGram(Integer maxGram) { - this.maxGram = maxGram; - return this; - } - - /** - * Get the side property: Specifies which side of the input the n-gram should be generated from. Default is "front". - * - * @return the side value. - */ - public EdgeNGramTokenFilterSide getSide() { - return this.side; - } - - /** - * Set the side property: Specifies which side of the input the n-gram should be generated from. Default is "front". - * - * @param side the side value to set. - * @return the EdgeNGramTokenFilterV1 object itself. - */ - public EdgeNGramTokenFilterV1 setSide(EdgeNGramTokenFilterSide side) { - this.side = side; - return this; - } - - /** - * {@inheritDoc} - */ - @Override - public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { - jsonWriter.writeStartObject(); - jsonWriter.writeStringField("name", getName()); - jsonWriter.writeStringField("@odata.type", this.odataType); - jsonWriter.writeNumberField("minGram", this.minGram); - jsonWriter.writeNumberField("maxGram", this.maxGram); - jsonWriter.writeStringField("side", this.side == null ? null : this.side.toString()); - return jsonWriter.writeEndObject(); - } - - /** - * Reads an instance of EdgeNGramTokenFilterV1 from the JsonReader. - * - * @param jsonReader The JsonReader being read. - * @return An instance of EdgeNGramTokenFilterV1 if the JsonReader was pointing to an instance of it, or null if it - * was pointing to JSON null. - * @throws IllegalStateException If the deserialized JSON object was missing any required properties. - * @throws IOException If an error occurs while reading the EdgeNGramTokenFilterV1. - */ - public static EdgeNGramTokenFilterV1 fromJson(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - boolean nameFound = false; - String name = null; - String odataType = "#Microsoft.Azure.Search.EdgeNGramTokenFilter"; - Integer minGram = null; - Integer maxGram = null; - EdgeNGramTokenFilterSide side = null; - while (reader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = reader.getFieldName(); - reader.nextToken(); - - if ("name".equals(fieldName)) { - name = reader.getString(); - nameFound = true; - } else if ("@odata.type".equals(fieldName)) { - odataType = reader.getString(); - } else if ("minGram".equals(fieldName)) { - minGram = reader.getNullable(JsonReader::getInt); - } else if ("maxGram".equals(fieldName)) { - maxGram = reader.getNullable(JsonReader::getInt); - } else if ("side".equals(fieldName)) { - side = EdgeNGramTokenFilterSide.fromString(reader.getString()); - } else { - reader.skipChildren(); - } - } - if (nameFound) { - EdgeNGramTokenFilterV1 deserializedEdgeNGramTokenFilterV1 = new EdgeNGramTokenFilterV1(name); - deserializedEdgeNGramTokenFilterV1.odataType = odataType; - deserializedEdgeNGramTokenFilterV1.minGram = minGram; - deserializedEdgeNGramTokenFilterV1.maxGram = maxGram; - deserializedEdgeNGramTokenFilterV1.side = side; - - return deserializedEdgeNGramTokenFilterV1; - } - throw new IllegalStateException("Missing required property: name"); - }); - } -} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/implementation/models/ErrorAdditionalInfo.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/implementation/models/ErrorAdditionalInfo.java deleted file mode 100644 index 781d77efae53..000000000000 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/implementation/models/ErrorAdditionalInfo.java +++ /dev/null @@ -1,91 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -package com.azure.search.documents.indexes.implementation.models; - -import com.azure.core.annotation.Immutable; -import com.azure.json.JsonReader; -import com.azure.json.JsonSerializable; -import com.azure.json.JsonToken; -import com.azure.json.JsonWriter; -import java.io.IOException; - -/** - * The resource management error additional info. - */ -@Immutable -public final class ErrorAdditionalInfo implements JsonSerializable { - /* - * The additional info type. - */ - private String type; - - /* - * The additional info. - */ - private Object info; - - /** - * Creates an instance of ErrorAdditionalInfo class. - */ - public ErrorAdditionalInfo() { - } - - /** - * Get the type property: The additional info type. - * - * @return the type value. - */ - public String getType() { - return this.type; - } - - /** - * Get the info property: The additional info. - * - * @return the info value. - */ - public Object getInfo() { - return this.info; - } - - /** - * {@inheritDoc} - */ - @Override - public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { - jsonWriter.writeStartObject(); - return jsonWriter.writeEndObject(); - } - - /** - * Reads an instance of ErrorAdditionalInfo from the JsonReader. - * - * @param jsonReader The JsonReader being read. - * @return An instance of ErrorAdditionalInfo if the JsonReader was pointing to an instance of it, or null if it was - * pointing to JSON null. - * @throws IOException If an error occurs while reading the ErrorAdditionalInfo. - */ - public static ErrorAdditionalInfo fromJson(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - ErrorAdditionalInfo deserializedErrorAdditionalInfo = new ErrorAdditionalInfo(); - while (reader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = reader.getFieldName(); - reader.nextToken(); - - if ("type".equals(fieldName)) { - deserializedErrorAdditionalInfo.type = reader.getString(); - } else if ("info".equals(fieldName)) { - deserializedErrorAdditionalInfo.info = reader.readUntyped(); - } else { - reader.skipChildren(); - } - } - - return deserializedErrorAdditionalInfo; - }); - } -} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/implementation/models/ErrorDetail.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/implementation/models/ErrorDetail.java deleted file mode 100644 index 50c24a7cca3b..000000000000 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/implementation/models/ErrorDetail.java +++ /dev/null @@ -1,143 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -package com.azure.search.documents.indexes.implementation.models; - -import com.azure.core.annotation.Immutable; -import com.azure.json.JsonReader; -import com.azure.json.JsonSerializable; -import com.azure.json.JsonToken; -import com.azure.json.JsonWriter; -import java.io.IOException; -import java.util.List; - -/** - * The error detail. - */ -@Immutable -public final class ErrorDetail implements JsonSerializable { - /* - * The error code. - */ - private String code; - - /* - * The error message. - */ - private String message; - - /* - * The error target. - */ - private String target; - - /* - * The error details. - */ - private List details; - - /* - * The error additional info. - */ - private List additionalInfo; - - /** - * Creates an instance of ErrorDetail class. - */ - public ErrorDetail() { - } - - /** - * Get the code property: The error code. - * - * @return the code value. - */ - public String getCode() { - return this.code; - } - - /** - * Get the message property: The error message. - * - * @return the message value. - */ - public String getMessage() { - return this.message; - } - - /** - * Get the target property: The error target. - * - * @return the target value. - */ - public String getTarget() { - return this.target; - } - - /** - * Get the details property: The error details. - * - * @return the details value. - */ - public List getDetails() { - return this.details; - } - - /** - * Get the additionalInfo property: The error additional info. - * - * @return the additionalInfo value. - */ - public List getAdditionalInfo() { - return this.additionalInfo; - } - - /** - * {@inheritDoc} - */ - @Override - public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { - jsonWriter.writeStartObject(); - return jsonWriter.writeEndObject(); - } - - /** - * Reads an instance of ErrorDetail from the JsonReader. - * - * @param jsonReader The JsonReader being read. - * @return An instance of ErrorDetail if the JsonReader was pointing to an instance of it, or null if it was - * pointing to JSON null. - * @throws IOException If an error occurs while reading the ErrorDetail. - */ - public static ErrorDetail fromJson(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - ErrorDetail deserializedErrorDetail = new ErrorDetail(); - while (reader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = reader.getFieldName(); - reader.nextToken(); - - if ("code".equals(fieldName)) { - deserializedErrorDetail.code = reader.getString(); - } else if ("message".equals(fieldName)) { - deserializedErrorDetail.message = reader.getString(); - } else if ("target".equals(fieldName)) { - deserializedErrorDetail.target = reader.getString(); - } else if ("details".equals(fieldName)) { - List details = reader.readArray(reader1 -> ErrorDetail.fromJson(reader1)); - deserializedErrorDetail.details = details; - } else if ("additionalInfo".equals(fieldName)) { - List additionalInfo - = reader.readArray(reader1 -> ErrorAdditionalInfo.fromJson(reader1)); - deserializedErrorDetail.additionalInfo = additionalInfo; - } else { - reader.skipChildren(); - } - } - - return deserializedErrorDetail; - }); - } -} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/implementation/models/ErrorResponse.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/implementation/models/ErrorResponse.java deleted file mode 100644 index 9682f3d2c4af..000000000000 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/implementation/models/ErrorResponse.java +++ /dev/null @@ -1,90 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -package com.azure.search.documents.indexes.implementation.models; - -import com.azure.core.annotation.Fluent; -import com.azure.json.JsonReader; -import com.azure.json.JsonSerializable; -import com.azure.json.JsonToken; -import com.azure.json.JsonWriter; -import java.io.IOException; - -/** - * Error response - * - * Common error response for all Azure Resource Manager APIs to return error details for failed operations. (This also - * follows the OData error response format.). - */ -@Fluent -public final class ErrorResponse implements JsonSerializable { - /* - * The error object. - */ - private ErrorDetail error; - - /** - * Creates an instance of ErrorResponse class. - */ - public ErrorResponse() { - } - - /** - * Get the error property: The error object. - * - * @return the error value. - */ - public ErrorDetail getError() { - return this.error; - } - - /** - * Set the error property: The error object. - * - * @param error the error value to set. - * @return the ErrorResponse object itself. - */ - public ErrorResponse setError(ErrorDetail error) { - this.error = error; - return this; - } - - /** - * {@inheritDoc} - */ - @Override - public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { - jsonWriter.writeStartObject(); - jsonWriter.writeJsonField("error", this.error); - return jsonWriter.writeEndObject(); - } - - /** - * Reads an instance of ErrorResponse from the JsonReader. - * - * @param jsonReader The JsonReader being read. - * @return An instance of ErrorResponse if the JsonReader was pointing to an instance of it, or null if it was - * pointing to JSON null. - * @throws IOException If an error occurs while reading the ErrorResponse. - */ - public static ErrorResponse fromJson(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - ErrorResponse deserializedErrorResponse = new ErrorResponse(); - while (reader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = reader.getFieldName(); - reader.nextToken(); - - if ("error".equals(fieldName)) { - deserializedErrorResponse.error = ErrorDetail.fromJson(reader); - } else { - reader.skipChildren(); - } - } - - return deserializedErrorResponse; - }); - } -} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/implementation/models/ErrorResponseException.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/implementation/models/ErrorResponseException.java deleted file mode 100644 index a0df39ca1d27..000000000000 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/implementation/models/ErrorResponseException.java +++ /dev/null @@ -1,44 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -package com.azure.search.documents.indexes.implementation.models; - -import com.azure.core.exception.HttpResponseException; -import com.azure.core.http.HttpResponse; - -/** - * Exception thrown for an invalid response with ErrorResponse information. - */ -public final class ErrorResponseException extends HttpResponseException { - /** - * Initializes a new instance of the ErrorResponseException class. - * - * @param message the exception message or the response content if a message is not available. - * @param response the HTTP response. - */ - public ErrorResponseException(String message, HttpResponse response) { - super(message, response); - } - - /** - * Initializes a new instance of the ErrorResponseException class. - * - * @param message the exception message or the response content if a message is not available. - * @param response the HTTP response. - * @param value the deserialized response value. - */ - public ErrorResponseException(String message, HttpResponse response, ErrorResponse value) { - super(message, response, value); - } - - /** - * {@inheritDoc} - */ - @Override - public ErrorResponse getValue() { - return (ErrorResponse) super.getValue(); - } -} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/implementation/models/KeywordTokenizerV1.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/implementation/models/KeywordTokenizerV1.java deleted file mode 100644 index fde22e8d6b7e..000000000000 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/implementation/models/KeywordTokenizerV1.java +++ /dev/null @@ -1,122 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -package com.azure.search.documents.indexes.implementation.models; - -import com.azure.core.annotation.Fluent; -import com.azure.json.JsonReader; -import com.azure.json.JsonToken; -import com.azure.json.JsonWriter; -import com.azure.search.documents.indexes.models.LexicalTokenizer; -import java.io.IOException; - -/** - * Emits the entire input as a single token. This tokenizer is implemented using Apache Lucene. - */ -@Fluent -public final class KeywordTokenizerV1 extends LexicalTokenizer { - /* - * A URI fragment specifying the type of tokenizer. - */ - private String odataType = "#Microsoft.Azure.Search.KeywordTokenizer"; - - /* - * The read buffer size in bytes. Default is 256. - */ - private Integer bufferSize; - - /** - * Creates an instance of KeywordTokenizerV1 class. - * - * @param name the name value to set. - */ - public KeywordTokenizerV1(String name) { - super(name); - } - - /** - * Get the odataType property: A URI fragment specifying the type of tokenizer. - * - * @return the odataType value. - */ - @Override - public String getOdataType() { - return this.odataType; - } - - /** - * Get the bufferSize property: The read buffer size in bytes. Default is 256. - * - * @return the bufferSize value. - */ - public Integer getBufferSize() { - return this.bufferSize; - } - - /** - * Set the bufferSize property: The read buffer size in bytes. Default is 256. - * - * @param bufferSize the bufferSize value to set. - * @return the KeywordTokenizerV1 object itself. - */ - public KeywordTokenizerV1 setBufferSize(Integer bufferSize) { - this.bufferSize = bufferSize; - return this; - } - - /** - * {@inheritDoc} - */ - @Override - public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { - jsonWriter.writeStartObject(); - jsonWriter.writeStringField("name", getName()); - jsonWriter.writeStringField("@odata.type", this.odataType); - jsonWriter.writeNumberField("bufferSize", this.bufferSize); - return jsonWriter.writeEndObject(); - } - - /** - * Reads an instance of KeywordTokenizerV1 from the JsonReader. - * - * @param jsonReader The JsonReader being read. - * @return An instance of KeywordTokenizerV1 if the JsonReader was pointing to an instance of it, or null if it was - * pointing to JSON null. - * @throws IllegalStateException If the deserialized JSON object was missing any required properties. - * @throws IOException If an error occurs while reading the KeywordTokenizerV1. - */ - public static KeywordTokenizerV1 fromJson(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - boolean nameFound = false; - String name = null; - String odataType = "#Microsoft.Azure.Search.KeywordTokenizer"; - Integer bufferSize = null; - while (reader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = reader.getFieldName(); - reader.nextToken(); - - if ("name".equals(fieldName)) { - name = reader.getString(); - nameFound = true; - } else if ("@odata.type".equals(fieldName)) { - odataType = reader.getString(); - } else if ("bufferSize".equals(fieldName)) { - bufferSize = reader.getNullable(JsonReader::getInt); - } else { - reader.skipChildren(); - } - } - if (nameFound) { - KeywordTokenizerV1 deserializedKeywordTokenizerV1 = new KeywordTokenizerV1(name); - deserializedKeywordTokenizerV1.odataType = odataType; - deserializedKeywordTokenizerV1.bufferSize = bufferSize; - - return deserializedKeywordTokenizerV1; - } - throw new IllegalStateException("Missing required property: name"); - }); - } -} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/implementation/models/ListAliasesResult.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/implementation/models/ListAliasesResult.java deleted file mode 100644 index 90946d5a0e54..000000000000 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/implementation/models/ListAliasesResult.java +++ /dev/null @@ -1,85 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -package com.azure.search.documents.indexes.implementation.models; - -import com.azure.core.annotation.Immutable; -import com.azure.json.JsonReader; -import com.azure.json.JsonSerializable; -import com.azure.json.JsonToken; -import com.azure.json.JsonWriter; -import com.azure.search.documents.indexes.models.SearchAlias; -import java.io.IOException; -import java.util.List; - -/** - * Response from a List Aliases request. If successful, it includes the associated index mappings for all aliases. - */ -@Immutable -public final class ListAliasesResult implements JsonSerializable { - /* - * The aliases in the Search service. - */ - private final List aliases; - - /** - * Creates an instance of ListAliasesResult class. - * - * @param aliases the aliases value to set. - */ - public ListAliasesResult(List aliases) { - this.aliases = aliases; - } - - /** - * Get the aliases property: The aliases in the Search service. - * - * @return the aliases value. - */ - public List getAliases() { - return this.aliases; - } - - /** - * {@inheritDoc} - */ - @Override - public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { - jsonWriter.writeStartObject(); - return jsonWriter.writeEndObject(); - } - - /** - * Reads an instance of ListAliasesResult from the JsonReader. - * - * @param jsonReader The JsonReader being read. - * @return An instance of ListAliasesResult if the JsonReader was pointing to an instance of it, or null if it was - * pointing to JSON null. - * @throws IllegalStateException If the deserialized JSON object was missing any required properties. - * @throws IOException If an error occurs while reading the ListAliasesResult. - */ - public static ListAliasesResult fromJson(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - boolean aliasesFound = false; - List aliases = null; - while (reader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = reader.getFieldName(); - reader.nextToken(); - - if ("value".equals(fieldName)) { - aliases = reader.readArray(reader1 -> SearchAlias.fromJson(reader1)); - aliasesFound = true; - } else { - reader.skipChildren(); - } - } - if (aliasesFound) { - return new ListAliasesResult(aliases); - } - throw new IllegalStateException("Missing required property: value"); - }); - } -} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/implementation/models/ListIndexesResult.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/implementation/models/ListIndexesResult.java deleted file mode 100644 index de74d1b075aa..000000000000 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/implementation/models/ListIndexesResult.java +++ /dev/null @@ -1,85 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -package com.azure.search.documents.indexes.implementation.models; - -import com.azure.core.annotation.Immutable; -import com.azure.json.JsonReader; -import com.azure.json.JsonSerializable; -import com.azure.json.JsonToken; -import com.azure.json.JsonWriter; -import com.azure.search.documents.indexes.models.SearchIndex; -import java.io.IOException; -import java.util.List; - -/** - * Response from a List Indexes request. If successful, it includes the full definitions of all indexes. - */ -@Immutable -public final class ListIndexesResult implements JsonSerializable { - /* - * The indexes in the Search service. - */ - private final List indexes; - - /** - * Creates an instance of ListIndexesResult class. - * - * @param indexes the indexes value to set. - */ - public ListIndexesResult(List indexes) { - this.indexes = indexes; - } - - /** - * Get the indexes property: The indexes in the Search service. - * - * @return the indexes value. - */ - public List getIndexes() { - return this.indexes; - } - - /** - * {@inheritDoc} - */ - @Override - public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { - jsonWriter.writeStartObject(); - return jsonWriter.writeEndObject(); - } - - /** - * Reads an instance of ListIndexesResult from the JsonReader. - * - * @param jsonReader The JsonReader being read. - * @return An instance of ListIndexesResult if the JsonReader was pointing to an instance of it, or null if it was - * pointing to JSON null. - * @throws IllegalStateException If the deserialized JSON object was missing any required properties. - * @throws IOException If an error occurs while reading the ListIndexesResult. - */ - public static ListIndexesResult fromJson(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - boolean indexesFound = false; - List indexes = null; - while (reader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = reader.getFieldName(); - reader.nextToken(); - - if ("value".equals(fieldName)) { - indexes = reader.readArray(reader1 -> SearchIndex.fromJson(reader1)); - indexesFound = true; - } else { - reader.skipChildren(); - } - } - if (indexesFound) { - return new ListIndexesResult(indexes); - } - throw new IllegalStateException("Missing required property: value"); - }); - } -} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/implementation/models/LuceneStandardTokenizerV1.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/implementation/models/LuceneStandardTokenizerV1.java deleted file mode 100644 index a42b153f912e..000000000000 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/implementation/models/LuceneStandardTokenizerV1.java +++ /dev/null @@ -1,124 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -package com.azure.search.documents.indexes.implementation.models; - -import com.azure.core.annotation.Fluent; -import com.azure.json.JsonReader; -import com.azure.json.JsonToken; -import com.azure.json.JsonWriter; -import com.azure.search.documents.indexes.models.LexicalTokenizer; -import java.io.IOException; - -/** - * Breaks text following the Unicode Text Segmentation rules. This tokenizer is implemented using Apache Lucene. - */ -@Fluent -public final class LuceneStandardTokenizerV1 extends LexicalTokenizer { - /* - * A URI fragment specifying the type of tokenizer. - */ - private String odataType = "#Microsoft.Azure.Search.StandardTokenizer"; - - /* - * The maximum token length. Default is 255. Tokens longer than the maximum length are split. - */ - private Integer maxTokenLength; - - /** - * Creates an instance of LuceneStandardTokenizerV1 class. - * - * @param name the name value to set. - */ - public LuceneStandardTokenizerV1(String name) { - super(name); - } - - /** - * Get the odataType property: A URI fragment specifying the type of tokenizer. - * - * @return the odataType value. - */ - @Override - public String getOdataType() { - return this.odataType; - } - - /** - * Get the maxTokenLength property: The maximum token length. Default is 255. Tokens longer than the maximum length - * are split. - * - * @return the maxTokenLength value. - */ - public Integer getMaxTokenLength() { - return this.maxTokenLength; - } - - /** - * Set the maxTokenLength property: The maximum token length. Default is 255. Tokens longer than the maximum length - * are split. - * - * @param maxTokenLength the maxTokenLength value to set. - * @return the LuceneStandardTokenizerV1 object itself. - */ - public LuceneStandardTokenizerV1 setMaxTokenLength(Integer maxTokenLength) { - this.maxTokenLength = maxTokenLength; - return this; - } - - /** - * {@inheritDoc} - */ - @Override - public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { - jsonWriter.writeStartObject(); - jsonWriter.writeStringField("name", getName()); - jsonWriter.writeStringField("@odata.type", this.odataType); - jsonWriter.writeNumberField("maxTokenLength", this.maxTokenLength); - return jsonWriter.writeEndObject(); - } - - /** - * Reads an instance of LuceneStandardTokenizerV1 from the JsonReader. - * - * @param jsonReader The JsonReader being read. - * @return An instance of LuceneStandardTokenizerV1 if the JsonReader was pointing to an instance of it, or null if - * it was pointing to JSON null. - * @throws IllegalStateException If the deserialized JSON object was missing any required properties. - * @throws IOException If an error occurs while reading the LuceneStandardTokenizerV1. - */ - public static LuceneStandardTokenizerV1 fromJson(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - boolean nameFound = false; - String name = null; - String odataType = "#Microsoft.Azure.Search.StandardTokenizer"; - Integer maxTokenLength = null; - while (reader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = reader.getFieldName(); - reader.nextToken(); - - if ("name".equals(fieldName)) { - name = reader.getString(); - nameFound = true; - } else if ("@odata.type".equals(fieldName)) { - odataType = reader.getString(); - } else if ("maxTokenLength".equals(fieldName)) { - maxTokenLength = reader.getNullable(JsonReader::getInt); - } else { - reader.skipChildren(); - } - } - if (nameFound) { - LuceneStandardTokenizerV1 deserializedLuceneStandardTokenizerV1 = new LuceneStandardTokenizerV1(name); - deserializedLuceneStandardTokenizerV1.odataType = odataType; - deserializedLuceneStandardTokenizerV1.maxTokenLength = maxTokenLength; - - return deserializedLuceneStandardTokenizerV1; - } - throw new IllegalStateException("Missing required property: name"); - }); - } -} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/implementation/models/NGramTokenFilterV1.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/implementation/models/NGramTokenFilterV1.java deleted file mode 100644 index fbac3836a61d..000000000000 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/implementation/models/NGramTokenFilterV1.java +++ /dev/null @@ -1,152 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -package com.azure.search.documents.indexes.implementation.models; - -import com.azure.core.annotation.Fluent; -import com.azure.json.JsonReader; -import com.azure.json.JsonToken; -import com.azure.json.JsonWriter; -import com.azure.search.documents.indexes.models.TokenFilter; -import java.io.IOException; - -/** - * Generates n-grams of the given size(s). This token filter is implemented using Apache Lucene. - */ -@Fluent -public final class NGramTokenFilterV1 extends TokenFilter { - /* - * A URI fragment specifying the type of token filter. - */ - private String odataType = "#Microsoft.Azure.Search.NGramTokenFilter"; - - /* - * The minimum n-gram length. Default is 1. Must be less than the value of maxGram. - */ - private Integer minGram; - - /* - * The maximum n-gram length. Default is 2. - */ - private Integer maxGram; - - /** - * Creates an instance of NGramTokenFilterV1 class. - * - * @param name the name value to set. - */ - public NGramTokenFilterV1(String name) { - super(name); - } - - /** - * Get the odataType property: A URI fragment specifying the type of token filter. - * - * @return the odataType value. - */ - @Override - public String getOdataType() { - return this.odataType; - } - - /** - * Get the minGram property: The minimum n-gram length. Default is 1. Must be less than the value of maxGram. - * - * @return the minGram value. - */ - public Integer getMinGram() { - return this.minGram; - } - - /** - * Set the minGram property: The minimum n-gram length. Default is 1. Must be less than the value of maxGram. - * - * @param minGram the minGram value to set. - * @return the NGramTokenFilterV1 object itself. - */ - public NGramTokenFilterV1 setMinGram(Integer minGram) { - this.minGram = minGram; - return this; - } - - /** - * Get the maxGram property: The maximum n-gram length. Default is 2. - * - * @return the maxGram value. - */ - public Integer getMaxGram() { - return this.maxGram; - } - - /** - * Set the maxGram property: The maximum n-gram length. Default is 2. - * - * @param maxGram the maxGram value to set. - * @return the NGramTokenFilterV1 object itself. - */ - public NGramTokenFilterV1 setMaxGram(Integer maxGram) { - this.maxGram = maxGram; - return this; - } - - /** - * {@inheritDoc} - */ - @Override - public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { - jsonWriter.writeStartObject(); - jsonWriter.writeStringField("name", getName()); - jsonWriter.writeStringField("@odata.type", this.odataType); - jsonWriter.writeNumberField("minGram", this.minGram); - jsonWriter.writeNumberField("maxGram", this.maxGram); - return jsonWriter.writeEndObject(); - } - - /** - * Reads an instance of NGramTokenFilterV1 from the JsonReader. - * - * @param jsonReader The JsonReader being read. - * @return An instance of NGramTokenFilterV1 if the JsonReader was pointing to an instance of it, or null if it was - * pointing to JSON null. - * @throws IllegalStateException If the deserialized JSON object was missing any required properties. - * @throws IOException If an error occurs while reading the NGramTokenFilterV1. - */ - public static NGramTokenFilterV1 fromJson(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - boolean nameFound = false; - String name = null; - String odataType = "#Microsoft.Azure.Search.NGramTokenFilter"; - Integer minGram = null; - Integer maxGram = null; - while (reader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = reader.getFieldName(); - reader.nextToken(); - - if ("name".equals(fieldName)) { - name = reader.getString(); - nameFound = true; - } else if ("@odata.type".equals(fieldName)) { - odataType = reader.getString(); - } else if ("minGram".equals(fieldName)) { - minGram = reader.getNullable(JsonReader::getInt); - } else if ("maxGram".equals(fieldName)) { - maxGram = reader.getNullable(JsonReader::getInt); - } else { - reader.skipChildren(); - } - } - if (nameFound) { - NGramTokenFilterV1 deserializedNGramTokenFilterV1 = new NGramTokenFilterV1(name); - deserializedNGramTokenFilterV1.odataType = odataType; - deserializedNGramTokenFilterV1.minGram = minGram; - deserializedNGramTokenFilterV1.maxGram = maxGram; - - return deserializedNGramTokenFilterV1; - } - throw new IllegalStateException("Missing required property: name"); - }); - } -} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/implementation/models/RequestOptions.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/implementation/models/RequestOptions.java deleted file mode 100644 index 95bb6d93cb71..000000000000 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/implementation/models/RequestOptions.java +++ /dev/null @@ -1,47 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -package com.azure.search.documents.indexes.implementation.models; - -import com.azure.core.annotation.Fluent; -import java.util.UUID; - -/** - * Parameter group. - */ -@Fluent -public final class RequestOptions { - /* - * The tracking ID sent with the request to help with debugging. - */ - private UUID xMsClientRequestId; - - /** - * Creates an instance of RequestOptions class. - */ - public RequestOptions() { - } - - /** - * Get the xMsClientRequestId property: The tracking ID sent with the request to help with debugging. - * - * @return the xMsClientRequestId value. - */ - public UUID getXMsClientRequestId() { - return this.xMsClientRequestId; - } - - /** - * Set the xMsClientRequestId property: The tracking ID sent with the request to help with debugging. - * - * @param xMsClientRequestId the xMsClientRequestId value to set. - * @return the RequestOptions object itself. - */ - public RequestOptions setXMsClientRequestId(UUID xMsClientRequestId) { - this.xMsClientRequestId = xMsClientRequestId; - return this; - } -} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/implementation/models/package-info.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/implementation/models/package-info.java deleted file mode 100644 index 56e723fe238f..000000000000 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/implementation/models/package-info.java +++ /dev/null @@ -1,12 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -/** - * Package containing the data models for SearchServiceClient. - * Client that can be used to manage and query indexes and documents, as well as manage other resources, on a search - * service. - */ -package com.azure.search.documents.indexes.implementation.models; diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/implementation/package-info.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/implementation/package-info.java deleted file mode 100644 index e869574d7f5f..000000000000 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/implementation/package-info.java +++ /dev/null @@ -1,12 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -/** - * Package containing the implementations for SearchServiceClient. - * Client that can be used to manage and query indexes and documents, as well as manage other resources, on a search - * service. - */ -package com.azure.search.documents.indexes.implementation; diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/AIStudioModelCatalogName.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/AIStudioModelCatalogName.java deleted file mode 100644 index fd4e1132040d..000000000000 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/AIStudioModelCatalogName.java +++ /dev/null @@ -1,78 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -package com.azure.search.documents.indexes.models; - -import com.azure.core.util.ExpandableStringEnum; -import java.util.Collection; - -/** - * The name of the embedding model from the Azure AI Studio Catalog that will be called. - */ -public final class AIStudioModelCatalogName extends ExpandableStringEnum { - /** - * Static value OpenAI-CLIP-Image-Text-Embeddings-vit-base-patch32 for AIStudioModelCatalogName. - */ - public static final AIStudioModelCatalogName OPEN_AICLIP_IMAGE_TEXT_EMBEDDINGS_VIT_BASE_PATCH32 - = fromString("OpenAI-CLIP-Image-Text-Embeddings-vit-base-patch32"); - - /** - * Static value OpenAI-CLIP-Image-Text-Embeddings-ViT-Large-Patch14-336 for AIStudioModelCatalogName. - */ - public static final AIStudioModelCatalogName OPEN_AICLIP_IMAGE_TEXT_EMBEDDINGS_VI_TLARGE_PATCH14336 - = fromString("OpenAI-CLIP-Image-Text-Embeddings-ViT-Large-Patch14-336"); - - /** - * Static value Facebook-DinoV2-Image-Embeddings-ViT-Base for AIStudioModelCatalogName. - */ - public static final AIStudioModelCatalogName FACEBOOK_DINO_V2IMAGE_EMBEDDINGS_VI_TBASE - = fromString("Facebook-DinoV2-Image-Embeddings-ViT-Base"); - - /** - * Static value Facebook-DinoV2-Image-Embeddings-ViT-Giant for AIStudioModelCatalogName. - */ - public static final AIStudioModelCatalogName FACEBOOK_DINO_V2IMAGE_EMBEDDINGS_VI_TGIANT - = fromString("Facebook-DinoV2-Image-Embeddings-ViT-Giant"); - - /** - * Static value Cohere-embed-v3-english for AIStudioModelCatalogName. - */ - public static final AIStudioModelCatalogName COHERE_EMBED_V3ENGLISH = fromString("Cohere-embed-v3-english"); - - /** - * Static value Cohere-embed-v3-multilingual for AIStudioModelCatalogName. - */ - public static final AIStudioModelCatalogName COHERE_EMBED_V3MULTILINGUAL - = fromString("Cohere-embed-v3-multilingual"); - - /** - * Creates a new instance of AIStudioModelCatalogName value. - * - * @deprecated Use the {@link #fromString(String)} factory method. - */ - @Deprecated - public AIStudioModelCatalogName() { - } - - /** - * Creates or finds a AIStudioModelCatalogName from its string representation. - * - * @param name a name to look for. - * @return the corresponding AIStudioModelCatalogName. - */ - public static AIStudioModelCatalogName fromString(String name) { - return fromString(name, AIStudioModelCatalogName.class); - } - - /** - * Gets known AIStudioModelCatalogName values. - * - * @return known AIStudioModelCatalogName values. - */ - public static Collection values() { - return values(AIStudioModelCatalogName.class); - } -} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/AnalyzeTextOptions.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/AnalyzeTextOptions.java deleted file mode 100644 index 3d7b3b0ee4f4..000000000000 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/AnalyzeTextOptions.java +++ /dev/null @@ -1,133 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.search.documents.indexes.models; - -import com.azure.core.annotation.Fluent; - -import java.util.Arrays; -import java.util.List; - -/** - * Specifies some text and analysis components used to break that text into - * tokens. - */ -@Fluent -public final class AnalyzeTextOptions { - /* - * The text to break into tokens. - */ - private final String text; - - /* - * The name of the analyzer to use to break the given text. - */ - private final LexicalAnalyzerName analyzerName; - - /* - * The name of the tokenizer to use to break the given text. - */ - private final LexicalTokenizerName tokenizerName; - - /* - * An optional list of token filters to use when breaking the given text. - */ - private List tokenFilters; - - /* - * An optional list of character filters to use when breaking the given - * text. - */ - private List charFilters; - - /** - * Constructor to {@link AnalyzeTextOptions} which takes analyzerName. - * - * @param text The text break into tokens. - * @param analyzerName The name of the analyzer to use to break the given text. - */ - public AnalyzeTextOptions(String text, LexicalAnalyzerName analyzerName) { - this.text = text; - this.analyzerName = analyzerName; - this.tokenizerName = null; - } - - /** - * Constructor to {@link AnalyzeTextOptions} which takes tokenizerName. - * - * @param text The text break into tokens. - * @param tokenizerName The name of the tokenizer to use to break the given text. - */ - public AnalyzeTextOptions(String text, LexicalTokenizerName tokenizerName) { - this.text = text; - this.tokenizerName = tokenizerName; - this.analyzerName = null; - } - - /** - * Get the text property: The text to break into tokens. - * - * @return the text value. - */ - public String getText() { - return this.text; - } - - /** - * Get the analyzer name property: The name of the analyzer to use to break the given text. - * - * @return the analyzer value. - */ - public LexicalAnalyzerName getAnalyzerName() { - return this.analyzerName; - } - - /** - * Get the tokenizer name property: The name of the tokenizer to use to break the given text. - * - * @return the tokenizer value. - */ - public LexicalTokenizerName getTokenizerName() { - return this.tokenizerName; - } - - /** - * Get the tokenFilters property: An optional list of token filters to use when breaking the given text. - * - * @return the tokenFilters value. - */ - public List getTokenFilters() { - return this.tokenFilters; - } - - /** - * Set the tokenFilters property: An optional list of token filters to use when breaking the given text. - * - * @param tokenFilters the tokenFilters value to set. - * @return the AnalyzeRequest object itself. - */ - public AnalyzeTextOptions setTokenFilters(TokenFilterName... tokenFilters) { - this.tokenFilters = (tokenFilters == null) ? null : Arrays.asList(tokenFilters); - return this; - } - - /** - * Get the charFilters property: An optional list of character filters to use when breaking the given text. - * - * @return the charFilters value. - */ - public List getCharFilters() { - return this.charFilters; - } - - /** - * Set the charFilters property: An optional list of character filters to use when breaking the given text. - * - * @param charFilters the charFilters value to set. - * @return the AnalyzeRequest object itself. - */ - public AnalyzeTextOptions setCharFilters(CharFilterName... charFilters) { - this.charFilters = (charFilters == null) ? null : Arrays.asList(charFilters); - return this; - } -} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/BlobIndexerPdfTextRotationAlgorithm.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/BlobIndexerPdfTextRotationAlgorithm.java deleted file mode 100644 index 6dc9aeab21f8..000000000000 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/BlobIndexerPdfTextRotationAlgorithm.java +++ /dev/null @@ -1,57 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -package com.azure.search.documents.indexes.models; - -import com.azure.core.util.ExpandableStringEnum; -import java.util.Collection; - -/** - * Determines algorithm for text extraction from PDF files in Azure blob storage. - */ -public final class BlobIndexerPdfTextRotationAlgorithm - extends ExpandableStringEnum { - /** - * Leverages normal text extraction. This is the default. - */ - public static final BlobIndexerPdfTextRotationAlgorithm NONE = fromString("none"); - - /** - * May produce better and more readable text extraction from PDF files that have rotated text within them. Note that - * there may be a small performance speed impact when this parameter is used. This parameter only applies to PDF - * files, and only to PDFs with embedded text. If the rotated text appears within an embedded image in the PDF, this - * parameter does not apply. - */ - public static final BlobIndexerPdfTextRotationAlgorithm DETECT_ANGLES = fromString("detectAngles"); - - /** - * Creates a new instance of BlobIndexerPdfTextRotationAlgorithm value. - * - * @deprecated Use the {@link #fromString(String)} factory method. - */ - @Deprecated - public BlobIndexerPdfTextRotationAlgorithm() { - } - - /** - * Creates or finds a BlobIndexerPdfTextRotationAlgorithm from its string representation. - * - * @param name a name to look for. - * @return the corresponding BlobIndexerPdfTextRotationAlgorithm. - */ - public static BlobIndexerPdfTextRotationAlgorithm fromString(String name) { - return fromString(name, BlobIndexerPdfTextRotationAlgorithm.class); - } - - /** - * Gets known BlobIndexerPdfTextRotationAlgorithm values. - * - * @return known BlobIndexerPdfTextRotationAlgorithm values. - */ - public static Collection values() { - return values(BlobIndexerPdfTextRotationAlgorithm.class); - } -} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/CjkBigramTokenFilterScripts.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/CjkBigramTokenFilterScripts.java deleted file mode 100644 index 8bf0a5c2f51e..000000000000 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/CjkBigramTokenFilterScripts.java +++ /dev/null @@ -1,68 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -package com.azure.search.documents.indexes.models; - -/** - * Scripts that can be ignored by CjkBigramTokenFilter. - */ -public enum CjkBigramTokenFilterScripts { - /** - * Ignore Han script when forming bigrams of CJK terms. - */ - HAN("han"), - - /** - * Ignore Hiragana script when forming bigrams of CJK terms. - */ - HIRAGANA("hiragana"), - - /** - * Ignore Katakana script when forming bigrams of CJK terms. - */ - KATAKANA("katakana"), - - /** - * Ignore Hangul script when forming bigrams of CJK terms. - */ - HANGUL("hangul"); - - /** - * The actual serialized value for a CjkBigramTokenFilterScripts instance. - */ - private final String value; - - CjkBigramTokenFilterScripts(String value) { - this.value = value; - } - - /** - * Parses a serialized value to a CjkBigramTokenFilterScripts instance. - * - * @param value the serialized value to parse. - * @return the parsed CjkBigramTokenFilterScripts object, or null if unable to parse. - */ - public static CjkBigramTokenFilterScripts fromString(String value) { - if (value == null) { - return null; - } - CjkBigramTokenFilterScripts[] items = CjkBigramTokenFilterScripts.values(); - for (CjkBigramTokenFilterScripts item : items) { - if (item.toString().equalsIgnoreCase(value)) { - return item; - } - } - return null; - } - - /** - * {@inheritDoc} - */ - @Override - public String toString() { - return this.value; - } -} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/EdgeNGramTokenFilter.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/EdgeNGramTokenFilter.java deleted file mode 100644 index 3a51ce77df99..000000000000 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/EdgeNGramTokenFilter.java +++ /dev/null @@ -1,130 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.search.documents.indexes.models; - -import com.azure.json.JsonWriter; -import com.azure.search.documents.indexes.implementation.models.EdgeNGramTokenFilterV1; -import com.azure.search.documents.indexes.implementation.models.EdgeNGramTokenFilterV2; - -import java.io.IOException; - -/** - * 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. - */ -public final class EdgeNGramTokenFilter extends TokenFilter { - private final EdgeNGramTokenFilterV1 v1Filter; - private final EdgeNGramTokenFilterV2 v2Filter; - - EdgeNGramTokenFilter(EdgeNGramTokenFilterV1 v1Filter) { - super(v1Filter.getName()); - - this.v1Filter = v1Filter; - this.v2Filter = null; - } - - EdgeNGramTokenFilter(EdgeNGramTokenFilterV2 v2Filter) { - super(v2Filter.getName()); - - this.v1Filter = null; - this.v2Filter = v2Filter; - } - - /** - * Constructor of {@link TokenFilter}. - * - * @param 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. - */ - public EdgeNGramTokenFilter(String name) { - super(name); - - this.v1Filter = null; - this.v2Filter = new EdgeNGramTokenFilterV2(name); - } - - /** - * Get the minGram property: The minimum n-gram length. Default is 1. Must - * be less than the value of maxGram. - * - * @return the minGram value. - */ - public Integer getMinGram() { - return (v1Filter != null) ? v1Filter.getMinGram() : v2Filter.getMinGram(); - } - - /** - * Set the minGram property: The minimum n-gram length. Default is 1. Must - * be less than the value of maxGram. - * - * @param minGram the minGram value to set. - * @return the EdgeNGramTokenFilter object itself. - */ - public EdgeNGramTokenFilter setMinGram(Integer minGram) { - if (v1Filter != null) { - v1Filter.setMinGram(minGram); - } else { - v2Filter.setMinGram(minGram); - } - return this; - } - - /** - * Get the maxGram property: The maximum n-gram length. Default is 2. - * - * @return the maxGram value. - */ - public Integer getMaxGram() { - return (v1Filter != null) ? v1Filter.getMaxGram() : v2Filter.getMaxGram(); - } - - /** - * Set the maxGram property: The maximum n-gram length. Default is 2. - * - * @param maxGram the maxGram value to set. - * @return the EdgeNGramTokenFilter object itself. - */ - public EdgeNGramTokenFilter setMaxGram(Integer maxGram) { - if (v1Filter != null) { - v1Filter.setMaxGram(maxGram); - } else { - v2Filter.setMaxGram(maxGram); - } - return this; - } - - /** - * Get the side property: Specifies which side of the input the n-gram - * should be generated from. Default is "front". Possible values include: - * 'Front', 'Back'. - * - * @return the side value. - */ - public EdgeNGramTokenFilterSide getSide() { - return (v1Filter != null) ? v1Filter.getSide() : v2Filter.getSide(); - } - - /** - * Set the side property: Specifies which side of the input the n-gram - * should be generated from. Default is "front". Possible values include: - * 'Front', 'Back'. - * - * @param side the side value to set. - * @return the EdgeNGramTokenFilter object itself. - */ - public EdgeNGramTokenFilter setSide(EdgeNGramTokenFilterSide side) { - if (v1Filter != null) { - v1Filter.setSide(side); - } else { - v2Filter.setSide(side); - } - return this; - } - - @Override - public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { - return (v1Filter != null) ? v1Filter.toJson(jsonWriter) : v2Filter.toJson(jsonWriter); - } -} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/EdgeNGramTokenFilterSide.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/EdgeNGramTokenFilterSide.java deleted file mode 100644 index f4bc300842f4..000000000000 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/EdgeNGramTokenFilterSide.java +++ /dev/null @@ -1,58 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -package com.azure.search.documents.indexes.models; - -/** - * Specifies which side of the input an n-gram should be generated from. - */ -public enum EdgeNGramTokenFilterSide { - /** - * Specifies that the n-gram should be generated from the front of the input. - */ - FRONT("front"), - - /** - * Specifies that the n-gram should be generated from the back of the input. - */ - BACK("back"); - - /** - * The actual serialized value for a EdgeNGramTokenFilterSide instance. - */ - private final String value; - - EdgeNGramTokenFilterSide(String value) { - this.value = value; - } - - /** - * Parses a serialized value to a EdgeNGramTokenFilterSide instance. - * - * @param value the serialized value to parse. - * @return the parsed EdgeNGramTokenFilterSide object, or null if unable to parse. - */ - public static EdgeNGramTokenFilterSide fromString(String value) { - if (value == null) { - return null; - } - EdgeNGramTokenFilterSide[] items = EdgeNGramTokenFilterSide.values(); - for (EdgeNGramTokenFilterSide item : items) { - if (item.toString().equalsIgnoreCase(value)) { - return item; - } - } - return null; - } - - /** - * {@inheritDoc} - */ - @Override - public String toString() { - return this.value; - } -} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/EntityRecognitionSkill.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/EntityRecognitionSkill.java deleted file mode 100644 index cad7bbaadc1b..000000000000 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/EntityRecognitionSkill.java +++ /dev/null @@ -1,291 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.search.documents.indexes.models; - -import com.azure.core.annotation.Fluent; -import com.azure.core.util.logging.ClientLogger; -import com.azure.json.JsonWriter; -import com.azure.search.documents.indexes.implementation.models.EntityRecognitionSkillV1; -import com.azure.search.documents.indexes.implementation.models.EntityRecognitionSkillV3; - -import java.io.IOException; -import java.util.List; -import java.util.Objects; -import java.util.stream.Collectors; - -/** Text analytics entity recognition. */ -@Fluent -public final class EntityRecognitionSkill extends SearchIndexerSkill { - - private static final ClientLogger LOGGER = new ClientLogger(EntityRecognitionSkill.class); - - /* - * Identifies the concrete type of the skill. - */ - private final EntityRecognitionSkillVersion version; - - private final EntityRecognitionSkillV1 v1Skill; - private final EntityRecognitionSkillV3 v3Skill; - - EntityRecognitionSkill(EntityRecognitionSkillV1 v1Skill) { - super(v1Skill.getInputs(), v1Skill.getOutputs()); - this.version = EntityRecognitionSkillVersion.V1; - this.v1Skill = v1Skill; - this.v3Skill = null; - } - - EntityRecognitionSkill(EntityRecognitionSkillV3 v3Skill) { - super(v3Skill.getInputs(), v3Skill.getOutputs()); - this.version = EntityRecognitionSkillVersion.V3; - this.v1Skill = null; - this.v3Skill = v3Skill; - } - - /** - * Creates an instance of EntityRecognitionSkill class. - *

- * The instance of SentimentSkill uses {@link EntityRecognitionSkillVersion#V1}, to set the specific version of the - * skill use {@link #EntityRecognitionSkill(List, List, EntityRecognitionSkillVersion)}. - * - * @param inputs the inputs value to set. - * @param outputs the outputs value to set. - * @deprecated Use {@link #EntityRecognitionSkill(List, List, EntityRecognitionSkillVersion)} as - * {@link EntityRecognitionSkillVersion#V1} is deprecated. See - * skill deprecation for - * more information. - */ - @Deprecated - public EntityRecognitionSkill(List inputs, List outputs) { - this(inputs, outputs, EntityRecognitionSkillVersion.V1); - } - - /** - * Creates an instance of EntityRecognitionSkill class. - * - * @param inputs the inputs value to set. - * @param outputs the outputs value to set. - * @param version the EntityRecognitionSkillVersion value to set. - * @throws NullPointerException If {@code version} is null. - */ - public EntityRecognitionSkill(List inputs, List outputs, - EntityRecognitionSkillVersion version) { - super(inputs, outputs); - this.version = Objects.requireNonNull(version, "'version' cannot be null."); - - if (version == EntityRecognitionSkillVersion.V1) { - this.v1Skill = new EntityRecognitionSkillV1(inputs, outputs); - this.v3Skill = null; - } else { - this.v1Skill = null; - this.v3Skill = new EntityRecognitionSkillV3(inputs, outputs); - } - } - - /** - * Gets the version of the {@link EntityRecognitionSkill}. - * - * @return The version of the {@link EntityRecognitionSkill}. - */ - public EntityRecognitionSkillVersion getSkillVersion() { - return this.version; - } - - /** - * Get the categories property: A list of entity categories that should be extracted. - * - * @return the categories value. - */ - public List getCategories() { - if (v1Skill != null) { - return v1Skill.getCategories(); - } else { - List categories = v3Skill.getCategories(); - if (categories == null) { - return null; - } else { - return categories.stream().map(EntityCategory::fromString).collect(Collectors.toList()); - } - } - } - - /** - * Set the categories property: A list of entity categories that should be extracted. - * - * @param categories the categories value to set. - * @return the EntityRecognitionSkill object itself. - */ - public EntityRecognitionSkill setCategories(List categories) { - if (v1Skill != null) { - v1Skill.setCategories(categories); - } else { - if (categories == null) { - v3Skill.setCategories(null); - } else { - v3Skill.setCategories(categories.stream().map(EntityCategory::toString).collect(Collectors.toList())); - } - } - - return this; - } - - /** - * Get the defaultLanguageCode property: A value indicating which language code to use. Default is en. - * - * @return the defaultLanguageCode value. - */ - public EntityRecognitionSkillLanguage getDefaultLanguageCode() { - return (v1Skill != null) - ? v1Skill.getDefaultLanguageCode() - : EntityRecognitionSkillLanguage.fromString(v3Skill.getDefaultLanguageCode()); - } - - /** - * Set the defaultLanguageCode property: A value indicating which language code to use. Default is en. - * - * @param defaultLanguageCode the defaultLanguageCode value to set. - * @return the EntityRecognitionSkill object itself. - */ - public EntityRecognitionSkill setDefaultLanguageCode(EntityRecognitionSkillLanguage defaultLanguageCode) { - if (v1Skill != null) { - v1Skill.setDefaultLanguageCode(defaultLanguageCode); - } else { - v3Skill.setDefaultLanguageCode((defaultLanguageCode == null) ? null : defaultLanguageCode.toString()); - } - - return this; - } - - /** - * Get the includeTypelessEntities property: 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. - * - * @return the includeTypelessEntities value. - */ - public Boolean areTypelessEntitiesIncluded() { - return (v1Skill != null) ? v1Skill.isIncludeTypelessEntities() : null; - } - - /** - * Set the includeTypelessEntities property: 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. - * - * @param includeTypelessEntities the includeTypelessEntities value to set. - * @return the EntityRecognitionSkill object itself. - * @throws IllegalArgumentException If {@code includeTypelessEntities} is supplied when {@link #getSkillVersion()} - * is {@link EntityRecognitionSkillVersion#V3}. - */ - public EntityRecognitionSkill setTypelessEntitiesIncluded(Boolean includeTypelessEntities) { - if (includeTypelessEntities != null && version == EntityRecognitionSkillVersion.V3) { - throw LOGGER.logExceptionAsError(new IllegalArgumentException( - "EntityRecognitionSkill using V3 doesn't support 'includeTypelessEntities'.")); - } - - if (v1Skill != null) { - v1Skill.setIncludeTypelessEntities(includeTypelessEntities); - } - - return this; - } - - /** - * Get the minimumPrecision property: 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. - * - * @return the minimumPrecision value. - */ - public Double getMinimumPrecision() { - return (v1Skill != null) ? v1Skill.getMinimumPrecision() : v3Skill.getMinimumPrecision(); - } - - /** - * Set the minimumPrecision property: 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. - * - * @param minimumPrecision the minimumPrecision value to set. - * @return the EntityRecognitionSkill object itself. - */ - public EntityRecognitionSkill setMinimumPrecision(Double minimumPrecision) { - if (v1Skill != null) { - v1Skill.setMinimumPrecision(minimumPrecision); - } else { - v3Skill.setMinimumPrecision(minimumPrecision); - } - - return this; - } - - /** - * Get the modelVersion property: 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. - * - * @return the modelVersion value. - */ - public String getModelVersion() { - return (v1Skill != null) ? null : v3Skill.getModelVersion(); - } - - /** - * Set the modelVersion property: 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. - * - * @param modelVersion the modelVersion value to set. - * @return the EntityRecognitionSkill object itself. - * @throws IllegalArgumentException If {@code modelVersion} is supplied when {@link #getSkillVersion()} is {@link - * EntityRecognitionSkillVersion#V1}. - */ - public EntityRecognitionSkill setModelVersion(String modelVersion) { - if (modelVersion != null && version == EntityRecognitionSkillVersion.V1) { - throw LOGGER.logExceptionAsError( - new IllegalArgumentException("EntityRecognitionSkill using V1 doesn't support 'modelVersion'.")); - } - - if (v3Skill != null) { - v3Skill.setModelVersion(modelVersion); - } - - return this; - } - - /** - * Set the categories property: A list of entity categories that should be extracted. - * - * @param categories the categories value to set. - * @return the EntityRecognitionSkill object itself. - */ - public EntityRecognitionSkill setCategories(EntityCategory... categories) { - return setCategories((categories == null) ? null : java.util.Arrays.asList(categories)); - } - - /** {@inheritDoc} */ - @Override - public EntityRecognitionSkill setName(String name) { - super.setName(name); - return this; - } - - /** {@inheritDoc} */ - @Override - public EntityRecognitionSkill setDescription(String description) { - super.setDescription(description); - return this; - } - - /** {@inheritDoc} */ - @Override - public EntityRecognitionSkill setContext(String context) { - super.setContext(context); - return this; - } - - @Override - public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { - return (v1Skill != null) ? v1Skill.toJson(jsonWriter) : v3Skill.toJson(jsonWriter); - } -} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/EntityRecognitionSkillVersion.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/EntityRecognitionSkillVersion.java deleted file mode 100644 index d675220dbf47..000000000000 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/EntityRecognitionSkillVersion.java +++ /dev/null @@ -1,63 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.search.documents.indexes.models; - -/** - * Represents the version of {@link EntityRecognitionSkill}. - */ -public enum EntityRecognitionSkillVersion { - /** - * Version 1 of {@link EntityRecognitionSkill}. - * - * @deprecated This version of the skill is deprecated, please use {@link #V3}. See - * skill deprecation for - * more information. - */ - @Deprecated - V1("#Microsoft.Skills.Text.EntityRecognitionSkill"), - - /** - * Version 3 of {@link EntityRecognitionSkill}. - */ - V3("#Microsoft.Skills.Text.V3.EntityRecognitionSkill"); - - private final String odataType; - - EntityRecognitionSkillVersion(String odataType) { - this.odataType = odataType; - } - - /** - * Gets the latest {@link EntityRecognitionSkill} version. - * - * @return The latest {@link EntityRecognitionSkill} version. - */ - public static EntityRecognitionSkillVersion getLatest() { - return V3; - } - - /** - * Gets the {@link EntityRecognitionSkillVersion} from the string {@code value}. - *

- * If the {@code value} doesn't match any version null will be returned. - * - * @param value The value to convert to an {@link EntityRecognitionSkillVersion}. - * @return The {@link EntityRecognitionSkillVersion} corresponding to the {@code value}, or null if no versions - * match the {@code value}. - */ - public static EntityRecognitionSkillVersion fromString(String value) { - if (V1.odataType.equals(value)) { - return V1; - } else if (V3.odataType.equals(value)) { - return V3; - } else { - return null; - } - } - - @Override - public String toString() { - return odataType; - } -} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/FieldBuilderOptions.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/FieldBuilderOptions.java deleted file mode 100644 index 74cbb051b7bf..000000000000 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/FieldBuilderOptions.java +++ /dev/null @@ -1,57 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.search.documents.indexes.models; - -import com.azure.core.annotation.Fluent; -import com.azure.core.util.serializer.JsonSerializer; -import com.azure.core.util.serializer.MemberNameConverter; -import com.azure.core.util.serializer.MemberNameConverterProviders; -import com.azure.search.documents.indexes.SearchIndexAsyncClient; -import com.azure.search.documents.indexes.SearchIndexClient; - -import java.util.Objects; - -/** - * Additional parameters to build {@link SearchField}. - */ -@Fluent -public final class FieldBuilderOptions { - private JsonSerializer jsonSerializer; - - /** - * Creates an instance of {@link FieldBuilderOptions}. - */ - public FieldBuilderOptions() { - } - - /** - * Gets the serializer used to aid the construction of {@link SearchField SearchFields} in {@link - * SearchIndexClient#buildSearchFields(Class, FieldBuilderOptions)} buildSearchFields} or {@link - * SearchIndexAsyncClient#buildSearchFields(Class, FieldBuilderOptions) buildSearchFields}. - *

- * If {@link JsonSerializer} is {@code null} or doesn't implement the {@link MemberNameConverter} interface then - * {@link MemberNameConverterProviders#createInstance()} will be used to provide a converter from the classpath. - * - * @return The custom {@link JsonSerializer}. - */ - public JsonSerializer getJsonSerializer() { - return jsonSerializer; - } - - /** - * Sets the serializer. - *

- * For building {@link SearchField SearchFields} it is expected that the {@link JsonSerializer} passed also - * implements the {@link MemberNameConverter} interface. If it doesn't {@link - * MemberNameConverterProviders#createInstance()} will be used to provide a converter from the classpath. - * - * @param jsonSerializer The custom serializer. - * @return The updated FieldBuilderOptions object. - */ - public FieldBuilderOptions setJsonSerializer(JsonSerializer jsonSerializer) { - this.jsonSerializer = Objects.requireNonNull(jsonSerializer, "'jsonSerializer' cannot be null"); - return this; - } - -} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/IndexDocumentsBatch.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/IndexDocumentsBatch.java deleted file mode 100644 index 6ce233e128f5..000000000000 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/IndexDocumentsBatch.java +++ /dev/null @@ -1,104 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.search.documents.indexes.models; - -import com.azure.core.annotation.Fluent; -import com.azure.search.documents.SearchDocument; -import com.azure.search.documents.models.IndexAction; -import com.azure.search.documents.models.IndexActionType; -import com.azure.search.documents.models.IndexBatchBase; - -import java.util.ArrayList; - -/** - * Contains a batch of document write actions to send to the index. - * - * @param The type of documents contained by the indexing batch. - */ -@Fluent -public class IndexDocumentsBatch extends IndexBatchBase { - /** - * Constructor of {@link IndexDocumentsBatch}. - */ - public IndexDocumentsBatch() { - super(new ArrayList<>()); - } - - /** - * Adds document index actions to the batch. - * - * @param actions Index actions. - * @return The updated IndexDocumentsBatch object. - */ - public IndexDocumentsBatch addActions(Iterable> actions) { - actions.forEach(action -> this.getActions().add(action)); - return this; - } - - /** - * Adds upload document actions to the batch. - * - * @param documents Documents to be uploaded. - * @return The updated IndexDocumentsBatch object. - */ - public IndexDocumentsBatch addUploadActions(Iterable documents) { - addDocumentActions(documents, IndexActionType.UPLOAD); - return this; - } - - /** - * Adds document delete actions to the batch. - * - * @param documents Document to be deleted. - * @return The updated IndexDocumentsBatch object. - */ - public IndexDocumentsBatch addDeleteActions(Iterable documents) { - addDocumentActions(documents, IndexActionType.DELETE); - return this; - } - - /** - * Adds document delete actions based on key IDs to the batch. - * - * @param keyName The key field name. - * @param keyValues Keys of the documents to delete. - * @return The updated IndexDocumentsBatch object. - */ - @SuppressWarnings({ "unchecked", "rawtypes" }) - public IndexDocumentsBatch addDeleteActions(String keyName, Iterable keyValues) { - for (String val : keyValues) { - SearchDocument doc = new SearchDocument(); - doc.put(keyName, val); - IndexAction indexAction = new IndexAction().setActionType(IndexActionType.DELETE).setDocument(doc); - this.getActions().add(indexAction); - } - return this; - } - - /** - * Adds merge document actions to the batch. - * - * @param documents Documents to be merged. - * @return The updated IndexDocumentsBatch object. - */ - public IndexDocumentsBatch addMergeActions(Iterable documents) { - addDocumentActions(documents, IndexActionType.MERGE); - return this; - } - - /** - * Adds merge or upload document actions to the batch. - * - * @param documents Documents to be merged or uploaded. - * @return The updated IndexDocumentsBatch object. - */ - public IndexDocumentsBatch addMergeOrUploadActions(Iterable documents) { - addDocumentActions(documents, IndexActionType.MERGE_OR_UPLOAD); - return this; - } - - private void addDocumentActions(Iterable documents, IndexActionType actionType) { - documents.forEach(d -> this.getActions().add(new IndexAction().setActionType(actionType).setDocument(d))); - } -} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/IndexerExecutionStatus.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/IndexerExecutionStatus.java deleted file mode 100644 index 5f58151ef9b2..000000000000 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/IndexerExecutionStatus.java +++ /dev/null @@ -1,69 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -package com.azure.search.documents.indexes.models; - -/** - * Represents the status of an individual indexer execution. - */ -public enum IndexerExecutionStatus { - /** - * An indexer invocation has failed, but the failure may be transient. Indexer invocations will continue per - * schedule. - */ - TRANSIENT_FAILURE("transientFailure"), - - /** - * Indexer execution completed successfully. - */ - SUCCESS("success"), - - /** - * Indexer execution is in progress. - */ - IN_PROGRESS("inProgress"), - - /** - * Indexer has been reset. - */ - RESET("reset"); - - /** - * The actual serialized value for a IndexerExecutionStatus instance. - */ - private final String value; - - IndexerExecutionStatus(String value) { - this.value = value; - } - - /** - * Parses a serialized value to a IndexerExecutionStatus instance. - * - * @param value the serialized value to parse. - * @return the parsed IndexerExecutionStatus object, or null if unable to parse. - */ - public static IndexerExecutionStatus fromString(String value) { - if (value == null) { - return null; - } - IndexerExecutionStatus[] items = IndexerExecutionStatus.values(); - for (IndexerExecutionStatus item : items) { - if (item.toString().equalsIgnoreCase(value)) { - return item; - } - } - return null; - } - - /** - * {@inheritDoc} - */ - @Override - public String toString() { - return this.value; - } -} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/IndexerStatus.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/IndexerStatus.java deleted file mode 100644 index 7b7b8c76b497..000000000000 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/IndexerStatus.java +++ /dev/null @@ -1,63 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -package com.azure.search.documents.indexes.models; - -/** - * Represents the overall indexer status. - */ -public enum IndexerStatus { - /** - * Indicates that the indexer is in an unknown state. - */ - UNKNOWN("unknown"), - - /** - * Indicates that the indexer experienced an error that cannot be corrected without human intervention. - */ - ERROR("error"), - - /** - * Indicates that the indexer is running normally. - */ - RUNNING("running"); - - /** - * The actual serialized value for a IndexerStatus instance. - */ - private final String value; - - IndexerStatus(String value) { - this.value = value; - } - - /** - * Parses a serialized value to a IndexerStatus instance. - * - * @param value the serialized value to parse. - * @return the parsed IndexerStatus object, or null if unable to parse. - */ - public static IndexerStatus fromString(String value) { - if (value == null) { - return null; - } - IndexerStatus[] items = IndexerStatus.values(); - for (IndexerStatus item : items) { - if (item.toString().equalsIgnoreCase(value)) { - return item; - } - } - return null; - } - - /** - * {@inheritDoc} - */ - @Override - public String toString() { - return this.value; - } -} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/KeywordTokenizer.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/KeywordTokenizer.java deleted file mode 100644 index 71dddbe20485..000000000000 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/KeywordTokenizer.java +++ /dev/null @@ -1,82 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.search.documents.indexes.models; - -import com.azure.core.annotation.Fluent; -import com.azure.json.JsonWriter; -import com.azure.search.documents.indexes.implementation.models.KeywordTokenizerV1; -import com.azure.search.documents.indexes.implementation.models.KeywordTokenizerV2; - -import java.io.IOException; - -/** - * Emits the entire input as a single token. This tokenizer is implemented - * using Apache Lucene. - */ -@Fluent -public final class KeywordTokenizer extends LexicalTokenizer { - private final KeywordTokenizerV1 v1Tokenizer; - private final KeywordTokenizerV2 v2Tokenizer; - - KeywordTokenizer(KeywordTokenizerV1 v1Tokenizer) { - super(v1Tokenizer.getName()); - - this.v1Tokenizer = v1Tokenizer; - this.v2Tokenizer = null; - } - - KeywordTokenizer(KeywordTokenizerV2 v2Tokenizer) { - super(v2Tokenizer.getName()); - - this.v1Tokenizer = null; - this.v2Tokenizer = v2Tokenizer; - } - - /** - * Constructor of {@link KeywordTokenizer}. - * - * @param 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. - */ - public KeywordTokenizer(String name) { - super(name); - - this.v1Tokenizer = null; - this.v2Tokenizer = new KeywordTokenizerV2(name); - } - - /** - * Get the maxTokenLength property: 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. - * - * @return the maxTokenLength value. - */ - public Integer getMaxTokenLength() { - return (v1Tokenizer != null) ? v1Tokenizer.getBufferSize() : v2Tokenizer.getMaxTokenLength(); - } - - /** - * Set the maxTokenLength property: 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. - * - * @param maxTokenLength the maxTokenLength value to set. - * @return the KeywordTokenizerV2 object itself. - */ - public KeywordTokenizer setMaxTokenLength(Integer maxTokenLength) { - if (v1Tokenizer != null) { - v1Tokenizer.setBufferSize(maxTokenLength); - } else { - v2Tokenizer.setMaxTokenLength(maxTokenLength); - } - return this; - } - - @Override - public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { - return (v1Tokenizer != null) ? v1Tokenizer.toJson(jsonWriter) : v2Tokenizer.toJson(jsonWriter); - } -} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/LuceneStandardTokenizer.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/LuceneStandardTokenizer.java deleted file mode 100644 index dffb6e91ca4f..000000000000 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/LuceneStandardTokenizer.java +++ /dev/null @@ -1,80 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.search.documents.indexes.models; - -import com.azure.core.annotation.Fluent; -import com.azure.json.JsonWriter; -import com.azure.search.documents.indexes.implementation.models.LuceneStandardTokenizerV1; -import com.azure.search.documents.indexes.implementation.models.LuceneStandardTokenizerV2; - -import java.io.IOException; - -/** - * Breaks text following the Unicode Text Segmentation rules. This tokenizer is - * implemented using Apache Lucene. - */ -@Fluent -public final class LuceneStandardTokenizer extends LexicalTokenizer { - private final LuceneStandardTokenizerV1 v1Tokenizer; - private final LuceneStandardTokenizerV2 v2tokenizer; - - LuceneStandardTokenizer(LuceneStandardTokenizerV1 v1Tokenizer) { - super(v1Tokenizer.getName()); - - this.v1Tokenizer = v1Tokenizer; - this.v2tokenizer = null; - } - - LuceneStandardTokenizer(LuceneStandardTokenizerV2 v2tokenizer) { - super(v2tokenizer.getName()); - - this.v1Tokenizer = null; - this.v2tokenizer = v2tokenizer; - } - - /** - * Constructor of {@link LuceneStandardTokenizer}. - * - * @param 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. - */ - public LuceneStandardTokenizer(String name) { - super(name); - - this.v1Tokenizer = null; - this.v2tokenizer = new LuceneStandardTokenizerV2(name); - } - - /** - * Get the maxTokenLength property: The maximum token length. Default is - * 255. Tokens longer than the maximum length are split. - * - * @return the maxTokenLength value. - */ - public Integer getMaxTokenLength() { - return (v1Tokenizer != null) ? v1Tokenizer.getMaxTokenLength() : v2tokenizer.getMaxTokenLength(); - } - - /** - * Set the maxTokenLength property: The maximum token length. Default is - * 255. Tokens longer than the maximum length are split. - * - * @param maxTokenLength the maxTokenLength value to set. - * @return the LuceneStandardTokenizer object itself. - */ - public LuceneStandardTokenizer setMaxTokenLength(Integer maxTokenLength) { - if (v1Tokenizer != null) { - v1Tokenizer.setMaxTokenLength(maxTokenLength); - } else { - v2tokenizer.setMaxTokenLength(maxTokenLength); - } - return this; - } - - @Override - public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { - return (v1Tokenizer != null) ? v1Tokenizer.toJson(jsonWriter) : v2tokenizer.toJson(jsonWriter); - } -} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/MicrosoftStemmingTokenizerLanguage.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/MicrosoftStemmingTokenizerLanguage.java deleted file mode 100644 index 50b95588c34f..000000000000 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/MicrosoftStemmingTokenizerLanguage.java +++ /dev/null @@ -1,273 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -package com.azure.search.documents.indexes.models; - -/** - * Lists the languages supported by the Microsoft language stemming tokenizer. - */ -public enum MicrosoftStemmingTokenizerLanguage { - /** - * Selects the Microsoft stemming tokenizer for Arabic. - */ - ARABIC("arabic"), - - /** - * Selects the Microsoft stemming tokenizer for Bangla. - */ - BANGLA("bangla"), - - /** - * Selects the Microsoft stemming tokenizer for Bulgarian. - */ - BULGARIAN("bulgarian"), - - /** - * Selects the Microsoft stemming tokenizer for Catalan. - */ - CATALAN("catalan"), - - /** - * Selects the Microsoft stemming tokenizer for Croatian. - */ - CROATIAN("croatian"), - - /** - * Selects the Microsoft stemming tokenizer for Czech. - */ - CZECH("czech"), - - /** - * Selects the Microsoft stemming tokenizer for Danish. - */ - DANISH("danish"), - - /** - * Selects the Microsoft stemming tokenizer for Dutch. - */ - DUTCH("dutch"), - - /** - * Selects the Microsoft stemming tokenizer for English. - */ - ENGLISH("english"), - - /** - * Selects the Microsoft stemming tokenizer for Estonian. - */ - ESTONIAN("estonian"), - - /** - * Selects the Microsoft stemming tokenizer for Finnish. - */ - FINNISH("finnish"), - - /** - * Selects the Microsoft stemming tokenizer for French. - */ - FRENCH("french"), - - /** - * Selects the Microsoft stemming tokenizer for German. - */ - GERMAN("german"), - - /** - * Selects the Microsoft stemming tokenizer for Greek. - */ - GREEK("greek"), - - /** - * Selects the Microsoft stemming tokenizer for Gujarati. - */ - GUJARATI("gujarati"), - - /** - * Selects the Microsoft stemming tokenizer for Hebrew. - */ - HEBREW("hebrew"), - - /** - * Selects the Microsoft stemming tokenizer for Hindi. - */ - HINDI("hindi"), - - /** - * Selects the Microsoft stemming tokenizer for Hungarian. - */ - HUNGARIAN("hungarian"), - - /** - * Selects the Microsoft stemming tokenizer for Icelandic. - */ - ICELANDIC("icelandic"), - - /** - * Selects the Microsoft stemming tokenizer for Indonesian. - */ - INDONESIAN("indonesian"), - - /** - * Selects the Microsoft stemming tokenizer for Italian. - */ - ITALIAN("italian"), - - /** - * Selects the Microsoft stemming tokenizer for Kannada. - */ - KANNADA("kannada"), - - /** - * Selects the Microsoft stemming tokenizer for Latvian. - */ - LATVIAN("latvian"), - - /** - * Selects the Microsoft stemming tokenizer for Lithuanian. - */ - LITHUANIAN("lithuanian"), - - /** - * Selects the Microsoft stemming tokenizer for Malay. - */ - MALAY("malay"), - - /** - * Selects the Microsoft stemming tokenizer for Malayalam. - */ - MALAYALAM("malayalam"), - - /** - * Selects the Microsoft stemming tokenizer for Marathi. - */ - MARATHI("marathi"), - - /** - * Selects the Microsoft stemming tokenizer for Norwegian (Bokmål). - */ - NORWEGIAN_BOKMAAL("norwegianBokmaal"), - - /** - * Selects the Microsoft stemming tokenizer for Polish. - */ - POLISH("polish"), - - /** - * Selects the Microsoft stemming tokenizer for Portuguese. - */ - PORTUGUESE("portuguese"), - - /** - * Selects the Microsoft stemming tokenizer for Portuguese (Brazil). - */ - PORTUGUESE_BRAZILIAN("portugueseBrazilian"), - - /** - * Selects the Microsoft stemming tokenizer for Punjabi. - */ - PUNJABI("punjabi"), - - /** - * Selects the Microsoft stemming tokenizer for Romanian. - */ - ROMANIAN("romanian"), - - /** - * Selects the Microsoft stemming tokenizer for Russian. - */ - RUSSIAN("russian"), - - /** - * Selects the Microsoft stemming tokenizer for Serbian (Cyrillic). - */ - SERBIAN_CYRILLIC("serbianCyrillic"), - - /** - * Selects the Microsoft stemming tokenizer for Serbian (Latin). - */ - SERBIAN_LATIN("serbianLatin"), - - /** - * Selects the Microsoft stemming tokenizer for Slovak. - */ - SLOVAK("slovak"), - - /** - * Selects the Microsoft stemming tokenizer for Slovenian. - */ - SLOVENIAN("slovenian"), - - /** - * Selects the Microsoft stemming tokenizer for Spanish. - */ - SPANISH("spanish"), - - /** - * Selects the Microsoft stemming tokenizer for Swedish. - */ - SWEDISH("swedish"), - - /** - * Selects the Microsoft stemming tokenizer for Tamil. - */ - TAMIL("tamil"), - - /** - * Selects the Microsoft stemming tokenizer for Telugu. - */ - TELUGU("telugu"), - - /** - * Selects the Microsoft stemming tokenizer for Turkish. - */ - TURKISH("turkish"), - - /** - * Selects the Microsoft stemming tokenizer for Ukrainian. - */ - UKRAINIAN("ukrainian"), - - /** - * Selects the Microsoft stemming tokenizer for Urdu. - */ - URDU("urdu"); - - /** - * The actual serialized value for a MicrosoftStemmingTokenizerLanguage instance. - */ - private final String value; - - MicrosoftStemmingTokenizerLanguage(String value) { - this.value = value; - } - - /** - * Parses a serialized value to a MicrosoftStemmingTokenizerLanguage instance. - * - * @param value the serialized value to parse. - * @return the parsed MicrosoftStemmingTokenizerLanguage object, or null if unable to parse. - */ - public static MicrosoftStemmingTokenizerLanguage fromString(String value) { - if (value == null) { - return null; - } - MicrosoftStemmingTokenizerLanguage[] items = MicrosoftStemmingTokenizerLanguage.values(); - for (MicrosoftStemmingTokenizerLanguage item : items) { - if (item.toString().equalsIgnoreCase(value)) { - return item; - } - } - return null; - } - - /** - * {@inheritDoc} - */ - @Override - public String toString() { - return this.value; - } -} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/MicrosoftTokenizerLanguage.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/MicrosoftTokenizerLanguage.java deleted file mode 100644 index b422b07118f4..000000000000 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/MicrosoftTokenizerLanguage.java +++ /dev/null @@ -1,258 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -package com.azure.search.documents.indexes.models; - -/** - * Lists the languages supported by the Microsoft language tokenizer. - */ -public enum MicrosoftTokenizerLanguage { - /** - * Selects the Microsoft tokenizer for Bangla. - */ - BANGLA("bangla"), - - /** - * Selects the Microsoft tokenizer for Bulgarian. - */ - BULGARIAN("bulgarian"), - - /** - * Selects the Microsoft tokenizer for Catalan. - */ - CATALAN("catalan"), - - /** - * Selects the Microsoft tokenizer for Chinese (Simplified). - */ - CHINESE_SIMPLIFIED("chineseSimplified"), - - /** - * Selects the Microsoft tokenizer for Chinese (Traditional). - */ - CHINESE_TRADITIONAL("chineseTraditional"), - - /** - * Selects the Microsoft tokenizer for Croatian. - */ - CROATIAN("croatian"), - - /** - * Selects the Microsoft tokenizer for Czech. - */ - CZECH("czech"), - - /** - * Selects the Microsoft tokenizer for Danish. - */ - DANISH("danish"), - - /** - * Selects the Microsoft tokenizer for Dutch. - */ - DUTCH("dutch"), - - /** - * Selects the Microsoft tokenizer for English. - */ - ENGLISH("english"), - - /** - * Selects the Microsoft tokenizer for French. - */ - FRENCH("french"), - - /** - * Selects the Microsoft tokenizer for German. - */ - GERMAN("german"), - - /** - * Selects the Microsoft tokenizer for Greek. - */ - GREEK("greek"), - - /** - * Selects the Microsoft tokenizer for Gujarati. - */ - GUJARATI("gujarati"), - - /** - * Selects the Microsoft tokenizer for Hindi. - */ - HINDI("hindi"), - - /** - * Selects the Microsoft tokenizer for Icelandic. - */ - ICELANDIC("icelandic"), - - /** - * Selects the Microsoft tokenizer for Indonesian. - */ - INDONESIAN("indonesian"), - - /** - * Selects the Microsoft tokenizer for Italian. - */ - ITALIAN("italian"), - - /** - * Selects the Microsoft tokenizer for Japanese. - */ - JAPANESE("japanese"), - - /** - * Selects the Microsoft tokenizer for Kannada. - */ - KANNADA("kannada"), - - /** - * Selects the Microsoft tokenizer for Korean. - */ - KOREAN("korean"), - - /** - * Selects the Microsoft tokenizer for Malay. - */ - MALAY("malay"), - - /** - * Selects the Microsoft tokenizer for Malayalam. - */ - MALAYALAM("malayalam"), - - /** - * Selects the Microsoft tokenizer for Marathi. - */ - MARATHI("marathi"), - - /** - * Selects the Microsoft tokenizer for Norwegian (Bokmål). - */ - NORWEGIAN_BOKMAAL("norwegianBokmaal"), - - /** - * Selects the Microsoft tokenizer for Polish. - */ - POLISH("polish"), - - /** - * Selects the Microsoft tokenizer for Portuguese. - */ - PORTUGUESE("portuguese"), - - /** - * Selects the Microsoft tokenizer for Portuguese (Brazil). - */ - PORTUGUESE_BRAZILIAN("portugueseBrazilian"), - - /** - * Selects the Microsoft tokenizer for Punjabi. - */ - PUNJABI("punjabi"), - - /** - * Selects the Microsoft tokenizer for Romanian. - */ - ROMANIAN("romanian"), - - /** - * Selects the Microsoft tokenizer for Russian. - */ - RUSSIAN("russian"), - - /** - * Selects the Microsoft tokenizer for Serbian (Cyrillic). - */ - SERBIAN_CYRILLIC("serbianCyrillic"), - - /** - * Selects the Microsoft tokenizer for Serbian (Latin). - */ - SERBIAN_LATIN("serbianLatin"), - - /** - * Selects the Microsoft tokenizer for Slovenian. - */ - SLOVENIAN("slovenian"), - - /** - * Selects the Microsoft tokenizer for Spanish. - */ - SPANISH("spanish"), - - /** - * Selects the Microsoft tokenizer for Swedish. - */ - SWEDISH("swedish"), - - /** - * Selects the Microsoft tokenizer for Tamil. - */ - TAMIL("tamil"), - - /** - * Selects the Microsoft tokenizer for Telugu. - */ - TELUGU("telugu"), - - /** - * Selects the Microsoft tokenizer for Thai. - */ - THAI("thai"), - - /** - * Selects the Microsoft tokenizer for Ukrainian. - */ - UKRAINIAN("ukrainian"), - - /** - * Selects the Microsoft tokenizer for Urdu. - */ - URDU("urdu"), - - /** - * Selects the Microsoft tokenizer for Vietnamese. - */ - VIETNAMESE("vietnamese"); - - /** - * The actual serialized value for a MicrosoftTokenizerLanguage instance. - */ - private final String value; - - MicrosoftTokenizerLanguage(String value) { - this.value = value; - } - - /** - * Parses a serialized value to a MicrosoftTokenizerLanguage instance. - * - * @param value the serialized value to parse. - * @return the parsed MicrosoftTokenizerLanguage object, or null if unable to parse. - */ - public static MicrosoftTokenizerLanguage fromString(String value) { - if (value == null) { - return null; - } - MicrosoftTokenizerLanguage[] items = MicrosoftTokenizerLanguage.values(); - for (MicrosoftTokenizerLanguage item : items) { - if (item.toString().equalsIgnoreCase(value)) { - return item; - } - } - return null; - } - - /** - * {@inheritDoc} - */ - @Override - public String toString() { - return this.value; - } -} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/NGramTokenFilter.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/NGramTokenFilter.java deleted file mode 100644 index 79adc471c6e1..000000000000 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/NGramTokenFilter.java +++ /dev/null @@ -1,104 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.search.documents.indexes.models; - -import com.azure.core.annotation.Fluent; -import com.azure.json.JsonWriter; -import com.azure.search.documents.indexes.implementation.models.NGramTokenFilterV1; -import com.azure.search.documents.indexes.implementation.models.NGramTokenFilterV2; - -import java.io.IOException; - -/** - * Generates n-grams of the given size(s). This token filter is implemented - * using Apache Lucene. - */ -@Fluent -public final class NGramTokenFilter extends TokenFilter { - private final NGramTokenFilterV1 v1Filter; - private final NGramTokenFilterV2 v2Filter; - - NGramTokenFilter(NGramTokenFilterV1 v1Filter) { - super(v1Filter.getName()); - - this.v1Filter = v1Filter; - this.v2Filter = null; - } - - NGramTokenFilter(NGramTokenFilterV2 v2Filter) { - super(v2Filter.getName()); - - this.v1Filter = null; - this.v2Filter = v2Filter; - } - - /** - * Constructor of {@link NGramTokenFilter}. - * - * @param 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. - */ - public NGramTokenFilter(String name) { - super(name); - - this.v1Filter = null; - this.v2Filter = new NGramTokenFilterV2(name); - } - - /** - * Get the minGram property: The minimum n-gram length. Default is 1. Must - * be less than the value of maxGram. - * - * @return the minGram value. - */ - public Integer getMinGram() { - return (v1Filter != null) ? v1Filter.getMinGram() : v2Filter.getMinGram(); - } - - /** - * Set the minGram property: The minimum n-gram length. Default is 1. Must - * be less than the value of maxGram. - * - * @param minGram the minGram value to set. - * @return the NGramTokenFilter object itself. - */ - public NGramTokenFilter setMinGram(Integer minGram) { - if (v1Filter != null) { - v1Filter.setMinGram(minGram); - } else { - v2Filter.setMinGram(minGram); - } - return this; - } - - /** - * Get the maxGram property: The maximum n-gram length. Default is 2. - * - * @return the maxGram value. - */ - public Integer getMaxGram() { - return (v1Filter != null) ? v1Filter.getMaxGram() : v2Filter.getMaxGram(); - } - - /** - * Set the maxGram property: The maximum n-gram length. Default is 2. - * - * @param maxGram the maxGram value to set. - * @return the NGramTokenFilter object itself. - */ - public NGramTokenFilter setMaxGram(Integer maxGram) { - if (v1Filter != null) { - v1Filter.setMaxGram(maxGram); - } else { - v2Filter.setMaxGram(maxGram); - } - return this; - } - - @Override - public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { - return (v1Filter != null) ? v1Filter.toJson(jsonWriter) : v2Filter.toJson(jsonWriter); - } -} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/PhoneticEncoder.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/PhoneticEncoder.java deleted file mode 100644 index 69ff1fc6fdc5..000000000000 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/PhoneticEncoder.java +++ /dev/null @@ -1,103 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -package com.azure.search.documents.indexes.models; - -/** - * Identifies the type of phonetic encoder to use with a PhoneticTokenFilter. - */ -public enum PhoneticEncoder { - /** - * Encodes a token into a Metaphone value. - */ - METAPHONE("metaphone"), - - /** - * Encodes a token into a double metaphone value. - */ - DOUBLE_METAPHONE("doubleMetaphone"), - - /** - * Encodes a token into a Soundex value. - */ - SOUNDEX("soundex"), - - /** - * Encodes a token into a Refined Soundex value. - */ - REFINED_SOUNDEX("refinedSoundex"), - - /** - * Encodes a token into a Caverphone 1.0 value. - */ - CAVERPHONE1("caverphone1"), - - /** - * Encodes a token into a Caverphone 2.0 value. - */ - CAVERPHONE2("caverphone2"), - - /** - * Encodes a token into a Cologne Phonetic value. - */ - COLOGNE("cologne"), - - /** - * Encodes a token into a NYSIIS value. - */ - NYSIIS("nysiis"), - - /** - * Encodes a token using the Kölner Phonetik algorithm. - */ - KOELNER_PHONETIK("koelnerPhonetik"), - - /** - * Encodes a token using the Haase refinement of the Kölner Phonetik algorithm. - */ - HAASE_PHONETIK("haasePhonetik"), - - /** - * Encodes a token into a Beider-Morse value. - */ - BEIDER_MORSE("beiderMorse"); - - /** - * The actual serialized value for a PhoneticEncoder instance. - */ - private final String value; - - PhoneticEncoder(String value) { - this.value = value; - } - - /** - * Parses a serialized value to a PhoneticEncoder instance. - * - * @param value the serialized value to parse. - * @return the parsed PhoneticEncoder object, or null if unable to parse. - */ - public static PhoneticEncoder fromString(String value) { - if (value == null) { - return null; - } - PhoneticEncoder[] items = PhoneticEncoder.values(); - for (PhoneticEncoder item : items) { - if (item.toString().equalsIgnoreCase(value)) { - return item; - } - } - return null; - } - - /** - * {@inheritDoc} - */ - @Override - public String toString() { - return this.value; - } -} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/PiiDetectionSkillMaskingMode.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/PiiDetectionSkillMaskingMode.java deleted file mode 100644 index e71cb8f6a46d..000000000000 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/PiiDetectionSkillMaskingMode.java +++ /dev/null @@ -1,55 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -package com.azure.search.documents.indexes.models; - -import com.azure.core.util.ExpandableStringEnum; -import java.util.Collection; - -/** - * A string indicating what maskingMode to use to mask the personal information detected in the input text. - */ -public final class PiiDetectionSkillMaskingMode extends ExpandableStringEnum { - /** - * No masking occurs and the maskedText output will not be returned. - */ - public static final PiiDetectionSkillMaskingMode NONE = fromString("none"); - - /** - * Replaces the detected entities with the character given in the maskingCharacter parameter. The character will be - * repeated to the length of the detected entity so that the offsets will correctly correspond to both the input - * text as well as the output maskedText. - */ - public static final PiiDetectionSkillMaskingMode REPLACE = fromString("replace"); - - /** - * Creates a new instance of PiiDetectionSkillMaskingMode value. - * - * @deprecated Use the {@link #fromString(String)} factory method. - */ - @Deprecated - public PiiDetectionSkillMaskingMode() { - } - - /** - * Creates or finds a PiiDetectionSkillMaskingMode from its string representation. - * - * @param name a name to look for. - * @return the corresponding PiiDetectionSkillMaskingMode. - */ - public static PiiDetectionSkillMaskingMode fromString(String name) { - return fromString(name, PiiDetectionSkillMaskingMode.class); - } - - /** - * Gets known PiiDetectionSkillMaskingMode values. - * - * @return known PiiDetectionSkillMaskingMode values. - */ - public static Collection values() { - return values(PiiDetectionSkillMaskingMode.class); - } -} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/ScoringFunctionAggregation.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/ScoringFunctionAggregation.java deleted file mode 100644 index be3e85920ca3..000000000000 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/ScoringFunctionAggregation.java +++ /dev/null @@ -1,73 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -package com.azure.search.documents.indexes.models; - -/** - * Defines the aggregation function used to combine the results of all the scoring functions in a scoring profile. - */ -public enum ScoringFunctionAggregation { - /** - * Boost scores by the sum of all scoring function results. - */ - SUM("sum"), - - /** - * Boost scores by the average of all scoring function results. - */ - AVERAGE("average"), - - /** - * Boost scores by the minimum of all scoring function results. - */ - MINIMUM("minimum"), - - /** - * Boost scores by the maximum of all scoring function results. - */ - MAXIMUM("maximum"), - - /** - * Boost scores using the first applicable scoring function in the scoring profile. - */ - FIRST_MATCHING("firstMatching"); - - /** - * The actual serialized value for a ScoringFunctionAggregation instance. - */ - private final String value; - - ScoringFunctionAggregation(String value) { - this.value = value; - } - - /** - * Parses a serialized value to a ScoringFunctionAggregation instance. - * - * @param value the serialized value to parse. - * @return the parsed ScoringFunctionAggregation object, or null if unable to parse. - */ - public static ScoringFunctionAggregation fromString(String value) { - if (value == null) { - return null; - } - ScoringFunctionAggregation[] items = ScoringFunctionAggregation.values(); - for (ScoringFunctionAggregation item : items) { - if (item.toString().equalsIgnoreCase(value)) { - return item; - } - } - return null; - } - - /** - * {@inheritDoc} - */ - @Override - public String toString() { - return this.value; - } -} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/ScoringFunctionInterpolation.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/ScoringFunctionInterpolation.java deleted file mode 100644 index 43d05697f845..000000000000 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/ScoringFunctionInterpolation.java +++ /dev/null @@ -1,70 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -package com.azure.search.documents.indexes.models; - -/** - * Defines the function used to interpolate score boosting across a range of documents. - */ -public enum ScoringFunctionInterpolation { - /** - * Boosts scores by a linearly decreasing amount. This is the default interpolation for scoring functions. - */ - LINEAR("linear"), - - /** - * Boosts scores by a constant factor. - */ - CONSTANT("constant"), - - /** - * Boosts scores by an amount that decreases quadratically. Boosts decrease slowly for higher scores, and more - * quickly as the scores decrease. This interpolation option is not allowed in tag scoring functions. - */ - QUADRATIC("quadratic"), - - /** - * Boosts scores by an amount that decreases logarithmically. Boosts decrease quickly for higher scores, and more - * slowly as the scores decrease. This interpolation option is not allowed in tag scoring functions. - */ - LOGARITHMIC("logarithmic"); - - /** - * The actual serialized value for a ScoringFunctionInterpolation instance. - */ - private final String value; - - ScoringFunctionInterpolation(String value) { - this.value = value; - } - - /** - * Parses a serialized value to a ScoringFunctionInterpolation instance. - * - * @param value the serialized value to parse. - * @return the parsed ScoringFunctionInterpolation object, or null if unable to parse. - */ - public static ScoringFunctionInterpolation fromString(String value) { - if (value == null) { - return null; - } - ScoringFunctionInterpolation[] items = ScoringFunctionInterpolation.values(); - for (ScoringFunctionInterpolation item : items) { - if (item.toString().equalsIgnoreCase(value)) { - return item; - } - } - return null; - } - - /** - * {@inheritDoc} - */ - @Override - public String toString() { - return this.value; - } -} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/SearchField.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/SearchField.java deleted file mode 100644 index ca321e5c6fb8..000000000000 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/SearchField.java +++ /dev/null @@ -1,785 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. -package com.azure.search.documents.indexes.models; - -import com.azure.core.annotation.Fluent; -import com.azure.json.JsonReader; -import com.azure.json.JsonSerializable; -import com.azure.json.JsonToken; -import com.azure.json.JsonWriter; -import java.io.IOException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -/** - * Represents a field in an index definition, which describes the name, data type, and search behavior of a field. - */ -@Fluent -public final class SearchField implements JsonSerializable { - - /* - * The name of the field, which must be unique within the fields collection of the index or parent field. - */ - private final String name; - - /* - * The data type of the field. - */ - private final SearchFieldDataType type; - - /* - * 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. - */ - private Boolean key; - - /* - * A value indicating whether the field will be returned in a search result. This property must be false for key - * fields, and must be null for complex fields. You can hide a field from search results if you want to use it only - * as a filter, for sorting, or for scoring. This property can also be changed on existing fields and enabling it - * does not cause an increase in index storage requirements. - */ - private Boolean hidden; - - /* - * 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. - */ - private Boolean stored; - - /* - * 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. - */ - private Boolean searchable; - - /* - * 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. - */ - private Boolean filterable; - - /* - * 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. - */ - private Boolean sortable; - - /* - * 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. - */ - private Boolean facetable; - - /* - * 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. - */ - private LexicalAnalyzerName analyzerName; - - /* - * 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. - */ - private LexicalAnalyzerName searchAnalyzerName; - - /* - * 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. - */ - private LexicalAnalyzerName indexAnalyzerName; - - /* - * 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. - */ - private LexicalNormalizerName normalizer; - - /* - * The dimensionality of the vector field. - */ - private Integer vectorSearchDimensions; - - /* - * The name of the vector search profile that specifies the algorithm and vectorizer to use when searching the - * vector field. - */ - private String vectorSearchProfileName; - - /* - * The encoding format to interpret the field contents. - */ - private VectorEncodingFormat vectorEncodingFormat; - - /* - * 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. - */ - private List synonymMapNames; - - /* - * 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. - */ - private List fields; - - /** - * Creates an instance of SearchField class. - * - * @param name the name value to set. - * @param type the type value to set. - */ - public SearchField(String name, SearchFieldDataType type) { - this.name = name; - this.type = type; - } - - /** - * Get the name property: The name of the field, which must be unique within the fields collection of the index or - * parent field. - * - * @return the name value. - */ - public String getName() { - return this.name; - } - - /** - * Get the type property: The data type of the field. - * - * @return the type value. - */ - public SearchFieldDataType getType() { - return this.type; - } - - /** - * Get the key property: 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. - * - * @return the key value. - */ - public Boolean isKey() { - return this.key; - } - - /** - * Set the key property: 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. - * - * @param key the key value to set. - * @return the SearchField object itself. - */ - public SearchField setKey(Boolean key) { - this.key = key; - return this; - } - - /** - * Get the hidden property: A value indicating whether the field will be returned in a search result. This property - * must be false for key fields, and must be null for complex fields. You can hide a field from search results if - * you want to use it only as a filter, for sorting, or for scoring. This property can also be changed on existing - * fields and enabling it does not cause an increase in index storage requirements. - * - * @return the hidden value. - */ - public Boolean isHidden() { - return (this.hidden == null) ? null : !this.hidden; - } - - /** - * Set the hidden property: A value indicating whether the field will be returned in a search result. This property - * must be false for key fields, and must be null for complex fields. You can hide a field from search results if - * you want to use it only as a filter, for sorting, or for scoring. This property can also be changed on existing - * fields and enabling it does not cause an increase in index storage requirements. - * - * @param hidden the hidden value to set. - * @return the SearchField object itself. - */ - public SearchField setHidden(Boolean hidden) { - this.hidden = (hidden == null) ? null : !hidden; - return this; - } - - /** - * Get the stored property: 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. - * - * @return the stored value. - */ - public Boolean isStored() { - return this.stored; - } - - /** - * Set the stored property: 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. - * - * @param stored the stored value to set. - * @return the SearchField object itself. - */ - public SearchField setStored(Boolean stored) { - this.stored = stored; - return this; - } - - /** - * Get the searchable property: 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. - * - * @return the searchable value. - */ - public Boolean isSearchable() { - return this.searchable; - } - - /** - * Set the searchable property: 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. - * - * @param searchable the searchable value to set. - * @return the SearchField object itself. - */ - public SearchField setSearchable(Boolean searchable) { - this.searchable = searchable; - return this; - } - - /** - * Get the filterable property: 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. - * - * @return the filterable value. - */ - public Boolean isFilterable() { - return this.filterable; - } - - /** - * Set the filterable property: 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. - * - * @param filterable the filterable value to set. - * @return the SearchField object itself. - */ - public SearchField setFilterable(Boolean filterable) { - this.filterable = filterable; - return this; - } - - /** - * Get the sortable property: 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. - * - * @return the sortable value. - */ - public Boolean isSortable() { - return this.sortable; - } - - /** - * Set the sortable property: 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. - * - * @param sortable the sortable value to set. - * @return the SearchField object itself. - */ - public SearchField setSortable(Boolean sortable) { - this.sortable = sortable; - return this; - } - - /** - * Get the facetable property: 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. - * - * @return the facetable value. - */ - public Boolean isFacetable() { - return this.facetable; - } - - /** - * Set the facetable property: 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. - * - * @param facetable the facetable value to set. - * @return the SearchField object itself. - */ - public SearchField setFacetable(Boolean facetable) { - this.facetable = facetable; - return this; - } - - /** - * Get the analyzerName property: 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. - * - * @return the analyzerName value. - */ - public LexicalAnalyzerName getAnalyzerName() { - return this.analyzerName; - } - - /** - * Set the analyzerName property: 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. - * - * @param analyzerName the analyzerName value to set. - * @return the SearchField object itself. - */ - public SearchField setAnalyzerName(LexicalAnalyzerName analyzerName) { - this.analyzerName = analyzerName; - return this; - } - - /** - * Get the searchAnalyzerName property: 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. - * - * @return the searchAnalyzerName value. - */ - public LexicalAnalyzerName getSearchAnalyzerName() { - return this.searchAnalyzerName; - } - - /** - * Set the searchAnalyzerName property: 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. - * - * @param searchAnalyzerName the searchAnalyzerName value to set. - * @return the SearchField object itself. - */ - public SearchField setSearchAnalyzerName(LexicalAnalyzerName searchAnalyzerName) { - this.searchAnalyzerName = searchAnalyzerName; - return this; - } - - /** - * Get the indexAnalyzerName property: 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. - * - * @return the indexAnalyzerName value. - */ - public LexicalAnalyzerName getIndexAnalyzerName() { - return this.indexAnalyzerName; - } - - /** - * Set the indexAnalyzerName property: 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. - * - * @param indexAnalyzerName the indexAnalyzerName value to set. - * @return the SearchField object itself. - */ - public SearchField setIndexAnalyzerName(LexicalAnalyzerName indexAnalyzerName) { - this.indexAnalyzerName = indexAnalyzerName; - return this; - } - - /** - * Get the normalizer property: 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. - * - * @return the normalizer value. - */ - public LexicalNormalizerName getNormalizer() { - return this.normalizer; - } - - /** - * Set the normalizer property: 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. - * - * @param normalizer the normalizer value to set. - * @return the SearchField object itself. - */ - public SearchField setNormalizer(LexicalNormalizerName normalizer) { - this.normalizer = normalizer; - return this; - } - - /** - * Get the vectorSearchDimensions property: The dimensionality of the vector field. - * - * @return the vectorSearchDimensions value. - */ - public Integer getVectorSearchDimensions() { - return this.vectorSearchDimensions; - } - - /** - * Set the vectorSearchDimensions property: The dimensionality of the vector field. - * - * @param vectorSearchDimensions the vectorSearchDimensions value to set. - * @return the SearchField object itself. - */ - public SearchField setVectorSearchDimensions(Integer vectorSearchDimensions) { - this.vectorSearchDimensions = vectorSearchDimensions; - return this; - } - - /** - * Get the vectorSearchProfileName property: The name of the vector search profile that specifies the algorithm and - * vectorizer to use when searching the vector field. - * - * @return the vectorSearchProfileName value. - */ - public String getVectorSearchProfileName() { - return this.vectorSearchProfileName; - } - - /** - * Set the vectorSearchProfileName property: The name of the vector search profile that specifies the algorithm and - * vectorizer to use when searching the vector field. - * - * @param vectorSearchProfileName the vectorSearchProfileName value to set. - * @return the SearchField object itself. - */ - public SearchField setVectorSearchProfileName(String vectorSearchProfileName) { - this.vectorSearchProfileName = vectorSearchProfileName; - return this; - } - - /** - * Get the vectorEncodingFormat property: The encoding format to interpret the field contents. - * - * @return the vectorEncodingFormat value. - */ - public VectorEncodingFormat getVectorEncodingFormat() { - return this.vectorEncodingFormat; - } - - /** - * Set the vectorEncodingFormat property: The encoding format to interpret the field contents. - * - * @param vectorEncodingFormat the vectorEncodingFormat value to set. - * @return the SearchField object itself. - */ - public SearchField setVectorEncodingFormat(VectorEncodingFormat vectorEncodingFormat) { - this.vectorEncodingFormat = vectorEncodingFormat; - return this; - } - - /** - * Get the synonymMapNames property: 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. - * - * @return the synonymMapNames value. - */ - public List getSynonymMapNames() { - return this.synonymMapNames; - } - - /** - * Set the synonymMapNames property: 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. - * - * @param synonymMapNames the synonymMapNames value to set. - * @return the SearchField object itself. - */ - public SearchField setSynonymMapNames(List synonymMapNames) { - this.synonymMapNames = synonymMapNames; - return this; - } - - /** - * Get the fields property: 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. - * - * @return the fields value. - */ - public List getFields() { - return this.fields; - } - - /** - * Set the fields property: 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. - * - * @param fields the fields value to set. - * @return the SearchField object itself. - */ - public SearchField setFields(List fields) { - this.fields = fields; - return this; - } - - /** - * {@inheritDoc} - */ - @Override - public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { - jsonWriter.writeStartObject(); - jsonWriter.writeStringField("name", this.name); - jsonWriter.writeStringField("type", this.type == null ? null : this.type.toString()); - jsonWriter.writeBooleanField("key", this.key); - jsonWriter.writeBooleanField("retrievable", this.hidden); - jsonWriter.writeBooleanField("stored", this.stored); - jsonWriter.writeBooleanField("searchable", this.searchable); - jsonWriter.writeBooleanField("filterable", this.filterable); - jsonWriter.writeBooleanField("sortable", this.sortable); - jsonWriter.writeBooleanField("facetable", this.facetable); - jsonWriter.writeStringField("analyzer", this.analyzerName == null ? null : this.analyzerName.toString()); - jsonWriter.writeStringField("searchAnalyzer", - this.searchAnalyzerName == null ? null : this.searchAnalyzerName.toString()); - jsonWriter.writeStringField("indexAnalyzer", - this.indexAnalyzerName == null ? null : this.indexAnalyzerName.toString()); - jsonWriter.writeStringField("normalizer", this.normalizer == null ? null : this.normalizer.toString()); - jsonWriter.writeNumberField("dimensions", this.vectorSearchDimensions); - jsonWriter.writeStringField("vectorSearchProfile", this.vectorSearchProfileName); - jsonWriter.writeStringField("vectorEncoding", - this.vectorEncodingFormat == null ? null : this.vectorEncodingFormat.toString()); - jsonWriter.writeArrayField("synonymMaps", this.synonymMapNames, - (writer, element) -> writer.writeString(element)); - jsonWriter.writeArrayField("fields", this.fields, (writer, element) -> writer.writeJson(element)); - return jsonWriter.writeEndObject(); - } - - /** - * Reads an instance of SearchField from the JsonReader. - * - * @param jsonReader The JsonReader being read. - * @return An instance of SearchField if the JsonReader was pointing to an instance of it, or null if it was - * pointing to JSON null. - * @throws IllegalStateException If the deserialized JSON object was missing any required properties. - * @throws IOException If an error occurs while reading the SearchField. - */ - public static SearchField fromJson(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - boolean nameFound = false; - String name = null; - boolean typeFound = false; - SearchFieldDataType type = null; - Boolean key = null; - Boolean hidden = null; - Boolean stored = null; - Boolean searchable = null; - Boolean filterable = null; - Boolean sortable = null; - Boolean facetable = null; - LexicalAnalyzerName analyzerName = null; - LexicalAnalyzerName searchAnalyzerName = null; - LexicalAnalyzerName indexAnalyzerName = null; - LexicalNormalizerName normalizer = null; - Integer vectorSearchDimensions = null; - String vectorSearchProfileName = null; - VectorEncodingFormat vectorEncodingFormat = null; - List synonymMapNames = null; - List fields = null; - while (reader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = reader.getFieldName(); - reader.nextToken(); - if ("name".equals(fieldName)) { - name = reader.getString(); - nameFound = true; - } else if ("type".equals(fieldName)) { - type = SearchFieldDataType.fromString(reader.getString()); - typeFound = true; - } else if ("key".equals(fieldName)) { - key = reader.getNullable(JsonReader::getBoolean); - } else if ("retrievable".equals(fieldName)) { - hidden = reader.getNullable(JsonReader::getBoolean); - } else if ("stored".equals(fieldName)) { - stored = reader.getNullable(JsonReader::getBoolean); - } else if ("searchable".equals(fieldName)) { - searchable = reader.getNullable(JsonReader::getBoolean); - } else if ("filterable".equals(fieldName)) { - filterable = reader.getNullable(JsonReader::getBoolean); - } else if ("sortable".equals(fieldName)) { - sortable = reader.getNullable(JsonReader::getBoolean); - } else if ("facetable".equals(fieldName)) { - facetable = reader.getNullable(JsonReader::getBoolean); - } else if ("analyzer".equals(fieldName)) { - analyzerName = LexicalAnalyzerName.fromString(reader.getString()); - } else if ("searchAnalyzer".equals(fieldName)) { - searchAnalyzerName = LexicalAnalyzerName.fromString(reader.getString()); - } else if ("indexAnalyzer".equals(fieldName)) { - indexAnalyzerName = LexicalAnalyzerName.fromString(reader.getString()); - } else if ("normalizer".equals(fieldName)) { - normalizer = LexicalNormalizerName.fromString(reader.getString()); - } else if ("dimensions".equals(fieldName)) { - vectorSearchDimensions = reader.getNullable(JsonReader::getInt); - } else if ("vectorSearchProfile".equals(fieldName)) { - vectorSearchProfileName = reader.getString(); - } else if ("vectorEncoding".equals(fieldName)) { - vectorEncodingFormat = VectorEncodingFormat.fromString(reader.getString()); - } else if ("synonymMaps".equals(fieldName)) { - synonymMapNames = reader.readArray(reader1 -> reader1.getString()); - } else if ("fields".equals(fieldName)) { - fields = reader.readArray(reader1 -> SearchField.fromJson(reader1)); - } else { - reader.skipChildren(); - } - } - if (nameFound && typeFound) { - SearchField deserializedSearchField = new SearchField(name, type); - deserializedSearchField.key = key; - deserializedSearchField.hidden = hidden; - deserializedSearchField.stored = stored; - deserializedSearchField.searchable = searchable; - deserializedSearchField.filterable = filterable; - deserializedSearchField.sortable = sortable; - deserializedSearchField.facetable = facetable; - deserializedSearchField.analyzerName = analyzerName; - deserializedSearchField.searchAnalyzerName = searchAnalyzerName; - deserializedSearchField.indexAnalyzerName = indexAnalyzerName; - deserializedSearchField.normalizer = normalizer; - deserializedSearchField.vectorSearchDimensions = vectorSearchDimensions; - deserializedSearchField.vectorSearchProfileName = vectorSearchProfileName; - deserializedSearchField.vectorEncodingFormat = vectorEncodingFormat; - deserializedSearchField.synonymMapNames = synonymMapNames; - deserializedSearchField.fields = fields; - return deserializedSearchField; - } - List missingProperties = new ArrayList<>(); - if (!nameFound) { - missingProperties.add("name"); - } - if (!typeFound) { - missingProperties.add("type"); - } - throw new IllegalStateException( - "Missing required property/properties: " + String.join(", ", missingProperties)); - }); - } - - /** - * Set the fields property: 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. - * - * @param fields the fields value to set. - * @return the SearchField object itself. - */ - public SearchField setFields(SearchField... fields) { - this.fields = (fields == null) ? null : Arrays.asList(fields); - return this; - } - - /** - * Set the synonymMapNames property: 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. - * - * @param synonymMapNames the synonymMapNames value to set. - * @return the SearchField object itself. - */ - public SearchField setSynonymMapNames(String... synonymMapNames) { - this.synonymMapNames = (synonymMapNames == null) ? null : Arrays.asList(synonymMapNames); - return this; - } -} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/SearchIndexerKnowledgeStoreBlobProjectionSelector.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/SearchIndexerKnowledgeStoreBlobProjectionSelector.java deleted file mode 100644 index 8853b70802a8..000000000000 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/SearchIndexerKnowledgeStoreBlobProjectionSelector.java +++ /dev/null @@ -1,102 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -package com.azure.search.documents.indexes.models; - -import com.azure.core.annotation.Fluent; -import com.azure.json.JsonWriter; -import java.io.IOException; -import java.util.List; - -/** - * Abstract class to share properties between concrete selectors. - */ -@Fluent -public class SearchIndexerKnowledgeStoreBlobProjectionSelector extends SearchIndexerKnowledgeStoreProjectionSelector { - /* - * Blob container to store projections in. - */ - private final String storageContainer; - - /** - * Creates an instance of SearchIndexerKnowledgeStoreBlobProjectionSelector class. - * - * @param storageContainer the storageContainer value to set. - */ - public SearchIndexerKnowledgeStoreBlobProjectionSelector(String storageContainer) { - this.storageContainer = storageContainer; - } - - /** - * Get the storageContainer property: Blob container to store projections in. - * - * @return the storageContainer value. - */ - public String getStorageContainer() { - return this.storageContainer; - } - - /** - * {@inheritDoc} - */ - @Override - public SearchIndexerKnowledgeStoreBlobProjectionSelector setReferenceKeyName(String referenceKeyName) { - super.setReferenceKeyName(referenceKeyName); - return this; - } - - /** - * {@inheritDoc} - */ - @Override - public SearchIndexerKnowledgeStoreBlobProjectionSelector setGeneratedKeyName(String generatedKeyName) { - super.setGeneratedKeyName(generatedKeyName); - return this; - } - - /** - * {@inheritDoc} - */ - @Override - public SearchIndexerKnowledgeStoreBlobProjectionSelector setSource(String source) { - super.setSource(source); - return this; - } - - /** - * {@inheritDoc} - */ - @Override - public SearchIndexerKnowledgeStoreBlobProjectionSelector setSourceContext(String sourceContext) { - super.setSourceContext(sourceContext); - return this; - } - - /** - * {@inheritDoc} - */ - @Override - public SearchIndexerKnowledgeStoreBlobProjectionSelector setInputs(List inputs) { - super.setInputs(inputs); - return this; - } - - /** - * {@inheritDoc} - */ - @Override - public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { - jsonWriter.writeStartObject(); - jsonWriter.writeStringField("referenceKeyName", getReferenceKeyName()); - jsonWriter.writeStringField("generatedKeyName", getGeneratedKeyName()); - jsonWriter.writeStringField("source", getSource()); - jsonWriter.writeStringField("sourceContext", getSourceContext()); - jsonWriter.writeArrayField("inputs", getInputs(), (writer, element) -> writer.writeJson(element)); - jsonWriter.writeStringField("storageContainer", this.storageContainer); - return jsonWriter.writeEndObject(); - } - -} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/SearchResourceEncryptionKey.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/SearchResourceEncryptionKey.java deleted file mode 100644 index ef77feab2f17..000000000000 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/SearchResourceEncryptionKey.java +++ /dev/null @@ -1,245 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. -package com.azure.search.documents.indexes.models; - -import com.azure.core.annotation.Fluent; -import com.azure.json.JsonReader; -import com.azure.json.JsonSerializable; -import com.azure.json.JsonToken; -import com.azure.json.JsonWriter; -import com.azure.search.documents.indexes.implementation.models.AzureActiveDirectoryApplicationCredentials; -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; - -/** - * 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. - */ -@Fluent -public final class SearchResourceEncryptionKey implements JsonSerializable { - - /* - * The name of your Azure Key Vault key to be used to encrypt your data at rest. - */ - private final String keyName; - - /* - * The version of your Azure Key Vault key to be used to encrypt your data at rest. - */ - private final String keyVersion; - - /* - * 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`. - */ - private final String vaultUrl; - - /* - * Optional Azure Active Directory credentials used for accessing your Azure Key Vault. Not required if using - * managed identity instead. - */ - private AzureActiveDirectoryApplicationCredentials accessCredentials; - - /* - * 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. - */ - private SearchIndexerDataIdentity identity; - - /** - * Creates an instance of SearchResourceEncryptionKey class. - * - * @param keyName the keyName value to set. - * @param keyVersion the keyVersion value to set. - * @param vaultUrl the vaultUrl value to set. - */ - public SearchResourceEncryptionKey(String keyName, String keyVersion, String vaultUrl) { - this.keyName = keyName; - this.keyVersion = keyVersion; - this.vaultUrl = vaultUrl; - } - - /** - * Get the keyName property: The name of your Azure Key Vault key to be used to encrypt your data at rest. - * - * @return the keyName value. - */ - public String getKeyName() { - return this.keyName; - } - - /** - * Get the keyVersion property: The version of your Azure Key Vault key to be used to encrypt your data at rest. - * - * @return the keyVersion value. - */ - public String getKeyVersion() { - return this.keyVersion; - } - - /** - * Get the vaultUrl property: 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`. - * - * @return the vaultUrl value. - */ - public String getVaultUrl() { - return this.vaultUrl; - } - - /** - * Get the identity property: 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. - * - * @return the identity value. - */ - public SearchIndexerDataIdentity getIdentity() { - return this.identity; - } - - /** - * Set the identity property: 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. - * - * @param identity the identity value to set. - * @return the SearchResourceEncryptionKey object itself. - */ - public SearchResourceEncryptionKey setIdentity(SearchIndexerDataIdentity identity) { - this.identity = identity; - return this; - } - - /** - * {@inheritDoc} - */ - @Override - public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { - jsonWriter.writeStartObject(); - jsonWriter.writeStringField("keyVaultKeyName", this.keyName); - jsonWriter.writeStringField("keyVaultKeyVersion", this.keyVersion); - jsonWriter.writeStringField("keyVaultUri", this.vaultUrl); - jsonWriter.writeJsonField("accessCredentials", this.accessCredentials); - jsonWriter.writeJsonField("identity", this.identity); - return jsonWriter.writeEndObject(); - } - - /** - * Reads an instance of SearchResourceEncryptionKey from the JsonReader. - * - * @param jsonReader The JsonReader being read. - * @return An instance of SearchResourceEncryptionKey if the JsonReader was pointing to an instance of it, or null - * if it was pointing to JSON null. - * @throws IllegalStateException If the deserialized JSON object was missing any required properties. - * @throws IOException If an error occurs while reading the SearchResourceEncryptionKey. - */ - public static SearchResourceEncryptionKey fromJson(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - boolean keyNameFound = false; - String keyName = null; - boolean keyVersionFound = false; - String keyVersion = null; - boolean vaultUrlFound = false; - String vaultUrl = null; - AzureActiveDirectoryApplicationCredentials accessCredentials = null; - SearchIndexerDataIdentity identity = null; - while (reader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = reader.getFieldName(); - reader.nextToken(); - if ("keyVaultKeyName".equals(fieldName)) { - keyName = reader.getString(); - keyNameFound = true; - } else if ("keyVaultKeyVersion".equals(fieldName)) { - keyVersion = reader.getString(); - keyVersionFound = true; - } else if ("keyVaultUri".equals(fieldName)) { - vaultUrl = reader.getString(); - vaultUrlFound = true; - } else if ("accessCredentials".equals(fieldName)) { - accessCredentials = AzureActiveDirectoryApplicationCredentials.fromJson(reader); - } else if ("identity".equals(fieldName)) { - identity = SearchIndexerDataIdentity.fromJson(reader); - } else { - reader.skipChildren(); - } - } - if (keyNameFound && keyVersionFound && vaultUrlFound) { - SearchResourceEncryptionKey deserializedSearchResourceEncryptionKey - = new SearchResourceEncryptionKey(keyName, keyVersion, vaultUrl); - deserializedSearchResourceEncryptionKey.accessCredentials = accessCredentials; - deserializedSearchResourceEncryptionKey.identity = identity; - return deserializedSearchResourceEncryptionKey; - } - List missingProperties = new ArrayList<>(); - if (!keyNameFound) { - missingProperties.add("keyVaultKeyName"); - } - if (!keyVersionFound) { - missingProperties.add("keyVaultKeyVersion"); - } - if (!vaultUrlFound) { - missingProperties.add("keyVaultUri"); - } - throw new IllegalStateException( - "Missing required property/properties: " + String.join(", ", missingProperties)); - }); - } - - /** - * Get the applicationId property: 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. - * - * @return the applicationId value. - */ - public String getApplicationId() { - return (this.accessCredentials == null) ? null : this.accessCredentials.getApplicationId(); - } - - /** - * Set the applicationId property: 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. - * - * @param applicationId the applicationId value to set. - * @return the SearchResourceEncryptionKey object itself. - */ - public SearchResourceEncryptionKey setApplicationId(String applicationId) { - if (this.accessCredentials == null) { - this.accessCredentials = new AzureActiveDirectoryApplicationCredentials(); - } - this.accessCredentials.setApplicationId(applicationId); - return this; - } - - /** - * Get the applicationSecret property: The authentication key of the specified AAD application. - * - * @return the applicationSecret value. - */ - public String getApplicationSecret() { - return (this.accessCredentials == null) ? null : this.accessCredentials.getApplicationSecret(); - } - - /** - * Set the applicationSecret property: The authentication key of the specified AAD application. - * - * @param applicationSecret the applicationSecret value to set. - * @return the SearchResourceEncryptionKey object itself. - */ - public SearchResourceEncryptionKey setApplicationSecret(String applicationSecret) { - if (this.accessCredentials == null) { - this.accessCredentials = new AzureActiveDirectoryApplicationCredentials(); - } - this.accessCredentials.setApplicationSecret(applicationSecret); - return this; - } -} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/SentimentSkill.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/SentimentSkill.java deleted file mode 100644 index fa1a5233864e..000000000000 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/SentimentSkill.java +++ /dev/null @@ -1,212 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.search.documents.indexes.models; - -import com.azure.core.annotation.Fluent; -import com.azure.core.util.logging.ClientLogger; -import com.azure.json.JsonWriter; -import com.azure.search.documents.indexes.implementation.models.SentimentSkillV1; -import com.azure.search.documents.indexes.implementation.models.SentimentSkillV3; - -import java.io.IOException; -import java.util.List; -import java.util.Objects; - -/** Text analytics positive-negative sentiment analysis, scored as a floating point value in a range of zero to 1. */ -@Fluent -public final class SentimentSkill extends SearchIndexerSkill { - - private static final ClientLogger LOGGER = new ClientLogger(SentimentSkill.class); - - /* - * Identifies the concrete type of the skill. - */ - private final SentimentSkillVersion version; - - private final SentimentSkillV1 v1Skill; - private final SentimentSkillV3 v3Skill; - - SentimentSkill(SentimentSkillV1 v1Skill) { - super(v1Skill.getInputs(), v1Skill.getOutputs()); - this.version = SentimentSkillVersion.V1; - this.v1Skill = v1Skill; - this.v3Skill = null; - } - - SentimentSkill(SentimentSkillV3 v3Skill) { - super(v3Skill.getInputs(), v3Skill.getOutputs()); - this.version = SentimentSkillVersion.V3; - this.v1Skill = null; - this.v3Skill = v3Skill; - } - - /** - * Creates an instance of SentimentSkill class. - *

- * The instance of SentimentSkill uses {@link SentimentSkillVersion#V1}, to set the specific version of the skill - * use {@link #SentimentSkill(List, List, SentimentSkillVersion)}. - * - * @param inputs the inputs value to set. - * @param outputs the outputs value to set. - * @deprecated Use {@link #SentimentSkill(List, List, SentimentSkillVersion)} as {@link SentimentSkillVersion#V1} is - * deprecated. See - * skill deprecation for - * more information. - */ - @Deprecated - public SentimentSkill(List inputs, List outputs) { - this(inputs, outputs, SentimentSkillVersion.V1); - } - - /** - * Creates an instance of SentimentSkill class. - * - * @param inputs the inputs value to set. - * @param outputs the outputs value to set. - * @param version the SentimentSkillVersion value to set. - * @throws NullPointerException If {@code version} is null. - */ - public SentimentSkill(List inputs, List outputs, - SentimentSkillVersion version) { - super(inputs, outputs); - this.version = Objects.requireNonNull(version, "'version' cannot be null."); - if (version == SentimentSkillVersion.V1) { - this.v1Skill = new SentimentSkillV1(inputs, outputs); - this.v3Skill = null; - } else { - this.v1Skill = null; - this.v3Skill = new SentimentSkillV3(inputs, outputs); - } - } - - /** - * Gets the version of the {@link SentimentSkill}. - * - * @return The version of the {@link SentimentSkill}. - */ - public SentimentSkillVersion getSkillVersion() { - return this.version; - } - - /** - * Get the defaultLanguageCode property: A value indicating which language code to use. Default is en. - * - * @return the defaultLanguageCode value. - */ - public SentimentSkillLanguage getDefaultLanguageCode() { - return (v1Skill != null) - ? v1Skill.getDefaultLanguageCode() - : SentimentSkillLanguage.fromString(v3Skill.getDefaultLanguageCode()); - } - - /** - * Set the defaultLanguageCode property: A value indicating which language code to use. Default is en. - * - * @param defaultLanguageCode the defaultLanguageCode value to set. - * @return the SentimentSkill object itself. - */ - public SentimentSkill setDefaultLanguageCode(SentimentSkillLanguage defaultLanguageCode) { - if (v1Skill != null) { - v1Skill.setDefaultLanguageCode(defaultLanguageCode); - } else { - v3Skill.setDefaultLanguageCode((defaultLanguageCode == null) ? null : defaultLanguageCode.toString()); - } - - return this; - } - - /** - * Get the includeOpinionMining property: 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. - * - * @return the includeOpinionMining value. - */ - public Boolean isOpinionMiningIncluded() { - return (v1Skill != null) ? null : v3Skill.isIncludeOpinionMining(); - } - - /** - * Set the opinionMiningIncluded property: 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. - * - * @param opinionMiningIncluded the opinionMiningIncluded value to set. - * @return the SentimentSkill object itself. - * @throws IllegalArgumentException If {@code opinionMiningIncluded} is supplied when {@link #getSkillVersion()} is - * {@link SentimentSkillVersion#V1}. - */ - public SentimentSkill setOpinionMiningIncluded(Boolean opinionMiningIncluded) { - if (opinionMiningIncluded != null && version == SentimentSkillVersion.V1) { - throw LOGGER.logExceptionAsError( - new IllegalArgumentException("SentimentSkill using V1 doesn't support 'opinionMiningIncluded'.")); - } - - if (v3Skill != null) { - v3Skill.setIncludeOpinionMining(opinionMiningIncluded); - } - - return this; - } - - /** - * Get the modelVersion property: 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. - * - * @return the modelVersion value. - */ - public String getModelVersion() { - return (v1Skill != null) ? null : v3Skill.getModelVersion(); - } - - /** - * Set the modelVersion property: 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. - * - * @param modelVersion the modelVersion value to set. - * @return the SentimentSkill object itself. - * @throws IllegalArgumentException If {@code modelVersion} is supplied when {@link #getSkillVersion()} is {@link - * SentimentSkillVersion#V1}. - */ - public SentimentSkill setModelVersion(String modelVersion) { - if (modelVersion != null && version == SentimentSkillVersion.V1) { - throw LOGGER.logExceptionAsError( - new IllegalArgumentException("SentimentSkill using V1 doesn't support 'modelVersion'.")); - } - - if (v3Skill != null) { - v3Skill.setModelVersion(modelVersion); - } - - return this; - } - - /** {@inheritDoc} */ - @Override - public SentimentSkill setName(String name) { - super.setName(name); - return this; - } - - /** {@inheritDoc} */ - @Override - public SentimentSkill setDescription(String description) { - super.setDescription(description); - return this; - } - - /** {@inheritDoc} */ - @Override - public SentimentSkill setContext(String context) { - super.setContext(context); - return this; - } - - @Override - public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { - return (v1Skill != null) ? v1Skill.toJson(jsonWriter) : v3Skill.toJson(jsonWriter); - } -} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/SentimentSkillVersion.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/SentimentSkillVersion.java deleted file mode 100644 index f8856e28913b..000000000000 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/SentimentSkillVersion.java +++ /dev/null @@ -1,63 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.search.documents.indexes.models; - -/** - * Represents the version of {@link SentimentSkill}. - */ -public enum SentimentSkillVersion { - /** - * Version 1 of {@link SentimentSkill}. - * - * @deprecated This version of the skill is deprecated, please use {@link #V3}. See - * skill deprecation for - * more information. - */ - @Deprecated - V1("#Microsoft.Skills.Text.SentimentSkill"), - - /** - * Version 3 of {@link SentimentSkill}. - */ - V3("#Microsoft.Skills.Text.V3.SentimentSkill"); - - private final String odataType; - - SentimentSkillVersion(String odataType) { - this.odataType = odataType; - } - - /** - * Gets the latest {@link SentimentSkill} version. - * - * @return The latest {@link SentimentSkill} version. - */ - public static SentimentSkillVersion getLatest() { - return V3; - } - - /** - * Gets the {@link SentimentSkillVersion} from the string {@code value}. - *

- * If the {@code value} doesn't match any version null will be returned. - * - * @param value The value to convert to an {@link SentimentSkillVersion}. - * @return The {@link SentimentSkillVersion} corresponding to the {@code value}, or null if no versions match the - * {@code value}. - */ - public static SentimentSkillVersion fromString(String value) { - if (V1.odataType.equals(value)) { - return V1; - } else if (V3.odataType.equals(value)) { - return V3; - } else { - return null; - } - } - - @Override - public String toString() { - return odataType; - } -} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/SnowballTokenFilterLanguage.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/SnowballTokenFilterLanguage.java deleted file mode 100644 index f0f496cb4f3d..000000000000 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/SnowballTokenFilterLanguage.java +++ /dev/null @@ -1,158 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -package com.azure.search.documents.indexes.models; - -/** - * The language to use for a Snowball token filter. - */ -public enum SnowballTokenFilterLanguage { - /** - * Selects the Lucene Snowball stemming tokenizer for Armenian. - */ - ARMENIAN("armenian"), - - /** - * Selects the Lucene Snowball stemming tokenizer for Basque. - */ - BASQUE("basque"), - - /** - * Selects the Lucene Snowball stemming tokenizer for Catalan. - */ - CATALAN("catalan"), - - /** - * Selects the Lucene Snowball stemming tokenizer for Danish. - */ - DANISH("danish"), - - /** - * Selects the Lucene Snowball stemming tokenizer for Dutch. - */ - DUTCH("dutch"), - - /** - * Selects the Lucene Snowball stemming tokenizer for English. - */ - ENGLISH("english"), - - /** - * Selects the Lucene Snowball stemming tokenizer for Finnish. - */ - FINNISH("finnish"), - - /** - * Selects the Lucene Snowball stemming tokenizer for French. - */ - FRENCH("french"), - - /** - * Selects the Lucene Snowball stemming tokenizer for German. - */ - GERMAN("german"), - - /** - * Selects the Lucene Snowball stemming tokenizer that uses the German variant algorithm. - */ - GERMAN2("german2"), - - /** - * Selects the Lucene Snowball stemming tokenizer for Hungarian. - */ - HUNGARIAN("hungarian"), - - /** - * Selects the Lucene Snowball stemming tokenizer for Italian. - */ - ITALIAN("italian"), - - /** - * Selects the Lucene Snowball stemming tokenizer for Dutch that uses the Kraaij-Pohlmann stemming algorithm. - */ - KP("kp"), - - /** - * Selects the Lucene Snowball stemming tokenizer for English that uses the Lovins stemming algorithm. - */ - LOVINS("lovins"), - - /** - * Selects the Lucene Snowball stemming tokenizer for Norwegian. - */ - NORWEGIAN("norwegian"), - - /** - * Selects the Lucene Snowball stemming tokenizer for English that uses the Porter stemming algorithm. - */ - PORTER("porter"), - - /** - * Selects the Lucene Snowball stemming tokenizer for Portuguese. - */ - PORTUGUESE("portuguese"), - - /** - * Selects the Lucene Snowball stemming tokenizer for Romanian. - */ - ROMANIAN("romanian"), - - /** - * Selects the Lucene Snowball stemming tokenizer for Russian. - */ - RUSSIAN("russian"), - - /** - * Selects the Lucene Snowball stemming tokenizer for Spanish. - */ - SPANISH("spanish"), - - /** - * Selects the Lucene Snowball stemming tokenizer for Swedish. - */ - SWEDISH("swedish"), - - /** - * Selects the Lucene Snowball stemming tokenizer for Turkish. - */ - TURKISH("turkish"); - - /** - * The actual serialized value for a SnowballTokenFilterLanguage instance. - */ - private final String value; - - SnowballTokenFilterLanguage(String value) { - this.value = value; - } - - /** - * Parses a serialized value to a SnowballTokenFilterLanguage instance. - * - * @param value the serialized value to parse. - * @return the parsed SnowballTokenFilterLanguage object, or null if unable to parse. - */ - public static SnowballTokenFilterLanguage fromString(String value) { - if (value == null) { - return null; - } - SnowballTokenFilterLanguage[] items = SnowballTokenFilterLanguage.values(); - for (SnowballTokenFilterLanguage item : items) { - if (item.toString().equalsIgnoreCase(value)) { - return item; - } - } - return null; - } - - /** - * {@inheritDoc} - */ - @Override - public String toString() { - return this.value; - } -} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/StemmerTokenFilterLanguage.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/StemmerTokenFilterLanguage.java deleted file mode 100644 index b87d611325a5..000000000000 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/StemmerTokenFilterLanguage.java +++ /dev/null @@ -1,318 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -package com.azure.search.documents.indexes.models; - -/** - * The language to use for a stemmer token filter. - */ -public enum StemmerTokenFilterLanguage { - /** - * Selects the Lucene stemming tokenizer for Arabic. - */ - ARABIC("arabic"), - - /** - * Selects the Lucene stemming tokenizer for Armenian. - */ - ARMENIAN("armenian"), - - /** - * Selects the Lucene stemming tokenizer for Basque. - */ - BASQUE("basque"), - - /** - * Selects the Lucene stemming tokenizer for Portuguese (Brazil). - */ - BRAZILIAN("brazilian"), - - /** - * Selects the Lucene stemming tokenizer for Bulgarian. - */ - BULGARIAN("bulgarian"), - - /** - * Selects the Lucene stemming tokenizer for Catalan. - */ - CATALAN("catalan"), - - /** - * Selects the Lucene stemming tokenizer for Czech. - */ - CZECH("czech"), - - /** - * Selects the Lucene stemming tokenizer for Danish. - */ - DANISH("danish"), - - /** - * Selects the Lucene stemming tokenizer for Dutch. - */ - DUTCH("dutch"), - - /** - * Selects the Lucene stemming tokenizer for Dutch that uses the Kraaij-Pohlmann stemming algorithm. - */ - DUTCH_KP("dutchKp"), - - /** - * Selects the Lucene stemming tokenizer for English. - */ - ENGLISH("english"), - - /** - * Selects the Lucene stemming tokenizer for English that does light stemming. - */ - LIGHT_ENGLISH("lightEnglish"), - - /** - * Selects the Lucene stemming tokenizer for English that does minimal stemming. - */ - MINIMAL_ENGLISH("minimalEnglish"), - - /** - * Selects the Lucene stemming tokenizer for English that removes trailing possessives from words. - */ - POSSESSIVE_ENGLISH("possessiveEnglish"), - - /** - * Selects the Lucene stemming tokenizer for English that uses the Porter2 stemming algorithm. - */ - PORTER2("porter2"), - - /** - * Selects the Lucene stemming tokenizer for English that uses the Lovins stemming algorithm. - */ - LOVINS("lovins"), - - /** - * Selects the Lucene stemming tokenizer for Finnish. - */ - FINNISH("finnish"), - - /** - * Selects the Lucene stemming tokenizer for Finnish that does light stemming. - */ - LIGHT_FINNISH("lightFinnish"), - - /** - * Selects the Lucene stemming tokenizer for French. - */ - FRENCH("french"), - - /** - * Selects the Lucene stemming tokenizer for French that does light stemming. - */ - LIGHT_FRENCH("lightFrench"), - - /** - * Selects the Lucene stemming tokenizer for French that does minimal stemming. - */ - MINIMAL_FRENCH("minimalFrench"), - - /** - * Selects the Lucene stemming tokenizer for Galician. - */ - GALICIAN("galician"), - - /** - * Selects the Lucene stemming tokenizer for Galician that does minimal stemming. - */ - MINIMAL_GALICIAN("minimalGalician"), - - /** - * Selects the Lucene stemming tokenizer for German. - */ - GERMAN("german"), - - /** - * Selects the Lucene stemming tokenizer that uses the German variant algorithm. - */ - GERMAN2("german2"), - - /** - * Selects the Lucene stemming tokenizer for German that does light stemming. - */ - LIGHT_GERMAN("lightGerman"), - - /** - * Selects the Lucene stemming tokenizer for German that does minimal stemming. - */ - MINIMAL_GERMAN("minimalGerman"), - - /** - * Selects the Lucene stemming tokenizer for Greek. - */ - GREEK("greek"), - - /** - * Selects the Lucene stemming tokenizer for Hindi. - */ - HINDI("hindi"), - - /** - * Selects the Lucene stemming tokenizer for Hungarian. - */ - HUNGARIAN("hungarian"), - - /** - * Selects the Lucene stemming tokenizer for Hungarian that does light stemming. - */ - LIGHT_HUNGARIAN("lightHungarian"), - - /** - * Selects the Lucene stemming tokenizer for Indonesian. - */ - INDONESIAN("indonesian"), - - /** - * Selects the Lucene stemming tokenizer for Irish. - */ - IRISH("irish"), - - /** - * Selects the Lucene stemming tokenizer for Italian. - */ - ITALIAN("italian"), - - /** - * Selects the Lucene stemming tokenizer for Italian that does light stemming. - */ - LIGHT_ITALIAN("lightItalian"), - - /** - * Selects the Lucene stemming tokenizer for Sorani. - */ - SORANI("sorani"), - - /** - * Selects the Lucene stemming tokenizer for Latvian. - */ - LATVIAN("latvian"), - - /** - * Selects the Lucene stemming tokenizer for Norwegian (Bokmål). - */ - NORWEGIAN("norwegian"), - - /** - * Selects the Lucene stemming tokenizer for Norwegian (Bokmål) that does light stemming. - */ - LIGHT_NORWEGIAN("lightNorwegian"), - - /** - * Selects the Lucene stemming tokenizer for Norwegian (Bokmål) that does minimal stemming. - */ - MINIMAL_NORWEGIAN("minimalNorwegian"), - - /** - * Selects the Lucene stemming tokenizer for Norwegian (Nynorsk) that does light stemming. - */ - LIGHT_NYNORSK("lightNynorsk"), - - /** - * Selects the Lucene stemming tokenizer for Norwegian (Nynorsk) that does minimal stemming. - */ - MINIMAL_NYNORSK("minimalNynorsk"), - - /** - * Selects the Lucene stemming tokenizer for Portuguese. - */ - PORTUGUESE("portuguese"), - - /** - * Selects the Lucene stemming tokenizer for Portuguese that does light stemming. - */ - LIGHT_PORTUGUESE("lightPortuguese"), - - /** - * Selects the Lucene stemming tokenizer for Portuguese that does minimal stemming. - */ - MINIMAL_PORTUGUESE("minimalPortuguese"), - - /** - * Selects the Lucene stemming tokenizer for Portuguese that uses the RSLP stemming algorithm. - */ - PORTUGUESE_RSLP("portugueseRslp"), - - /** - * Selects the Lucene stemming tokenizer for Romanian. - */ - ROMANIAN("romanian"), - - /** - * Selects the Lucene stemming tokenizer for Russian. - */ - RUSSIAN("russian"), - - /** - * Selects the Lucene stemming tokenizer for Russian that does light stemming. - */ - LIGHT_RUSSIAN("lightRussian"), - - /** - * Selects the Lucene stemming tokenizer for Spanish. - */ - SPANISH("spanish"), - - /** - * Selects the Lucene stemming tokenizer for Spanish that does light stemming. - */ - LIGHT_SPANISH("lightSpanish"), - - /** - * Selects the Lucene stemming tokenizer for Swedish. - */ - SWEDISH("swedish"), - - /** - * Selects the Lucene stemming tokenizer for Swedish that does light stemming. - */ - LIGHT_SWEDISH("lightSwedish"), - - /** - * Selects the Lucene stemming tokenizer for Turkish. - */ - TURKISH("turkish"); - - /** - * The actual serialized value for a StemmerTokenFilterLanguage instance. - */ - private final String value; - - StemmerTokenFilterLanguage(String value) { - this.value = value; - } - - /** - * Parses a serialized value to a StemmerTokenFilterLanguage instance. - * - * @param value the serialized value to parse. - * @return the parsed StemmerTokenFilterLanguage object, or null if unable to parse. - */ - public static StemmerTokenFilterLanguage fromString(String value) { - if (value == null) { - return null; - } - StemmerTokenFilterLanguage[] items = StemmerTokenFilterLanguage.values(); - for (StemmerTokenFilterLanguage item : items) { - if (item.toString().equalsIgnoreCase(value)) { - return item; - } - } - return null; - } - - /** - * {@inheritDoc} - */ - @Override - public String toString() { - return this.value; - } -} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/StopwordsList.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/StopwordsList.java deleted file mode 100644 index 7ff27e11c54d..000000000000 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/StopwordsList.java +++ /dev/null @@ -1,203 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -package com.azure.search.documents.indexes.models; - -/** - * Identifies a predefined list of language-specific stopwords. - */ -public enum StopwordsList { - /** - * Selects the stopword list for Arabic. - */ - ARABIC("arabic"), - - /** - * Selects the stopword list for Armenian. - */ - ARMENIAN("armenian"), - - /** - * Selects the stopword list for Basque. - */ - BASQUE("basque"), - - /** - * Selects the stopword list for Portuguese (Brazil). - */ - BRAZILIAN("brazilian"), - - /** - * Selects the stopword list for Bulgarian. - */ - BULGARIAN("bulgarian"), - - /** - * Selects the stopword list for Catalan. - */ - CATALAN("catalan"), - - /** - * Selects the stopword list for Czech. - */ - CZECH("czech"), - - /** - * Selects the stopword list for Danish. - */ - DANISH("danish"), - - /** - * Selects the stopword list for Dutch. - */ - DUTCH("dutch"), - - /** - * Selects the stopword list for English. - */ - ENGLISH("english"), - - /** - * Selects the stopword list for Finnish. - */ - FINNISH("finnish"), - - /** - * Selects the stopword list for French. - */ - FRENCH("french"), - - /** - * Selects the stopword list for Galician. - */ - GALICIAN("galician"), - - /** - * Selects the stopword list for German. - */ - GERMAN("german"), - - /** - * Selects the stopword list for Greek. - */ - GREEK("greek"), - - /** - * Selects the stopword list for Hindi. - */ - HINDI("hindi"), - - /** - * Selects the stopword list for Hungarian. - */ - HUNGARIAN("hungarian"), - - /** - * Selects the stopword list for Indonesian. - */ - INDONESIAN("indonesian"), - - /** - * Selects the stopword list for Irish. - */ - IRISH("irish"), - - /** - * Selects the stopword list for Italian. - */ - ITALIAN("italian"), - - /** - * Selects the stopword list for Latvian. - */ - LATVIAN("latvian"), - - /** - * Selects the stopword list for Norwegian. - */ - NORWEGIAN("norwegian"), - - /** - * Selects the stopword list for Persian. - */ - PERSIAN("persian"), - - /** - * Selects the stopword list for Portuguese. - */ - PORTUGUESE("portuguese"), - - /** - * Selects the stopword list for Romanian. - */ - ROMANIAN("romanian"), - - /** - * Selects the stopword list for Russian. - */ - RUSSIAN("russian"), - - /** - * Selects the stopword list for Sorani. - */ - SORANI("sorani"), - - /** - * Selects the stopword list for Spanish. - */ - SPANISH("spanish"), - - /** - * Selects the stopword list for Swedish. - */ - SWEDISH("swedish"), - - /** - * Selects the stopword list for Thai. - */ - THAI("thai"), - - /** - * Selects the stopword list for Turkish. - */ - TURKISH("turkish"); - - /** - * The actual serialized value for a StopwordsList instance. - */ - private final String value; - - StopwordsList(String value) { - this.value = value; - } - - /** - * Parses a serialized value to a StopwordsList instance. - * - * @param value the serialized value to parse. - * @return the parsed StopwordsList object, or null if unable to parse. - */ - public static StopwordsList fromString(String value) { - if (value == null) { - return null; - } - StopwordsList[] items = StopwordsList.values(); - for (StopwordsList item : items) { - if (item.toString().equalsIgnoreCase(value)) { - return item; - } - } - return null; - } - - /** - * {@inheritDoc} - */ - @Override - public String toString() { - return this.value; - } -} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/TokenCharacterKind.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/TokenCharacterKind.java deleted file mode 100644 index 1ab00644e176..000000000000 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/TokenCharacterKind.java +++ /dev/null @@ -1,73 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -package com.azure.search.documents.indexes.models; - -/** - * Represents classes of characters on which a token filter can operate. - */ -public enum TokenCharacterKind { - /** - * Keeps letters in tokens. - */ - LETTER("letter"), - - /** - * Keeps digits in tokens. - */ - DIGIT("digit"), - - /** - * Keeps whitespace in tokens. - */ - WHITESPACE("whitespace"), - - /** - * Keeps punctuation in tokens. - */ - PUNCTUATION("punctuation"), - - /** - * Keeps symbols in tokens. - */ - SYMBOL("symbol"); - - /** - * The actual serialized value for a TokenCharacterKind instance. - */ - private final String value; - - TokenCharacterKind(String value) { - this.value = value; - } - - /** - * Parses a serialized value to a TokenCharacterKind instance. - * - * @param value the serialized value to parse. - * @return the parsed TokenCharacterKind object, or null if unable to parse. - */ - public static TokenCharacterKind fromString(String value) { - if (value == null) { - return null; - } - TokenCharacterKind[] items = TokenCharacterKind.values(); - for (TokenCharacterKind item : items) { - if (item.toString().equalsIgnoreCase(value)) { - return item; - } - } - return null; - } - - /** - * {@inheritDoc} - */ - @Override - public String toString() { - return this.value; - } -} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/package-info.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/package-info.java deleted file mode 100644 index 59602397f637..000000000000 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/package-info.java +++ /dev/null @@ -1,12 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -/** - * Package containing the data models for SearchServiceClient. - * Client that can be used to manage and query indexes and documents, as well as manage other resources, on a search - * service. - */ -package com.azure.search.documents.indexes.models; diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/package-info.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/package-info.java deleted file mode 100644 index 32365d27caa1..000000000000 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/package-info.java +++ /dev/null @@ -1,470 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -/** - *

Azure AI Search, formerly known as "Azure AI Search", provides secure information retrieval at scale over - * user-owned content in traditional and conversational search applications.

- * - *

The Azure AI Search service provides:/p> - * - *

    - *
  • A search engine for vector search, full text, and hybrid search over a search index.
  • - *
  • Rich indexing with integrated data chunking and vectorization (preview), lexical analysis for text, and - * optional AI enrichment for content extraction and transformation.
  • - *
  • Rich query syntax for vector queries, text search, hybrid queries, fuzzy search, autocomplete, geo-search and others.
  • - *
  • Azure scale, security, and reach.
  • - *
  • Azure integration at the data layer, machine learning layer, Azure AI services and Azure OpenAI
  • - *
- * - *

The Azure AI Search service is well suited for the following application scenarios:

- * - *
    - *
  • Consolidate varied content types into a single searchable index. To populate an index, you can push JSON - * documents that contain your content, or if your data is already in Azure, create an indexer to pull in data - * automatically.
  • - *
  • Attach skillsets to an indexer to create searchable content from images and large text documents. A skillset - * leverages AI from Cognitive Services for built-in OCR, entity recognition, key phrase extraction, language - * detection, text translation, and sentiment analysis. You can also add custom skills to integrate external - * processing of your content during data ingestion.
  • - *
  • In a search client application, implement query logic and user experiences similar to commercial web search engines.
  • - *
- * - *

This is the Java client library for Azure AI Search. Azure AI Search service is a search-as-a-service - * cloud solution that gives developers APIs and tools for adding a rich search experience over private, heterogeneous - * content in web, mobile, and enterprise applications.

- * - *

The Azure Search Documents client library allows for Java developers to easily interact with the Azure AI Search - * service from their Java applications. This library provides a set of APIs that abstract the low-level details of working - * with the Azure AI Search service and allows developers to perform common operations such as:

- * - *
    - *
  • Submit queries for simple and advanced query forms that include fuzzy search, wildcard search, regular expressions.
  • - *
  • Implement filtered queries for faceted navigation, geospatial search, or to narrow results based on filter criteria.
  • - *
  • Create and manage search indexes.
  • - *
  • Upload and update documents in the search index.
  • - *
  • Create and manage indexers that pull data from Azure into an index.
  • - *
  • Create and manage skillsets that add AI enrichment to data ingestion.
  • - *
  • Create and manage analyzers for advanced text analysis or multi-lingual content.
  • - *
  • Optimize results through scoring profiles to factor in business logic or freshness.
  • - *
- * - *

Getting Started

- * - *

Prerequisites

- * - *

The client library package requires the following:

- * - * - * - *

To create a new Search service, you can use the - * Azure portal, - * Azure Powershell, - * or the Azure CLI.

- * - * - *

Authenticate the client

- * - *

To interact with the Search service, you'll need to create an instance of the appropriate client class: - * SearchClient for searching indexed documents, SearchIndexClient for managing indexes, or SearchIndexerClient for - * crawling data sources and loading search documents into an index. To instantiate a client object, you'll need an - * endpoint and API key. You can refer to the documentation for more information on - * supported authenticating approaches - * with the Search service.

- * - *

Get an API Key

- * - *

You can get the endpoint and an API key from the Search service in the Azure Portal. - * Please refer the - * documentation for instructions on how to get an API key.

- * - *

The SDK provides three clients.

- * - *
    - *
  • SearchIndexClient for CRUD operations on indexes and synonym maps.
  • - *
  • SearchIndexerClient for CRUD operations on indexers, data sources, and skillsets.
  • - *
  • SearchClient for all document operations.
  • - *
- * - *

Create a SearchIndexClient

- * - *

To create a SearchIndexClient, you will need the values of the Azure AI Search service URL endpoint and - * admin key. The following snippet shows how to create a SearchIndexClient.

- * - * The following sample creates a SearchIndexClient using the endpoint and Azure Key Credential (API Key). - * - * - *
- * SearchIndexClient searchIndexClient = new SearchIndexClientBuilder()
- *     .endpoint("{endpoint}")
- *     .credential(new AzureKeyCredential("{key}"))
- *     .buildClient();
- * 
- * - * - *

Create a SearchIndexerClient

- * - *

To create a SearchIndexerClient, you will need the values of the Azure AI Search - * service URL endpoint and admin key. The following snippet shows how to create a SearchIndexerClient.

- * - *

The following sample creates SearchIndexerClient using an endpoint and Azure Key Credential (API Key).

- * - * - *
- * SearchIndexerClient searchIndexerClient = new SearchIndexerClientBuilder()
- *     .endpoint("{endpoint}")
- *     .credential(new AzureKeyCredential("{key}"))
- *     .buildClient();
- * 
- * - * - * - *

Create a SearchClient

- * - *

To create a SearchClient, you will need the values of the Azure AI Search - * service URL endpoint, admin key, and an index name. The following snippet shows how to create a SearchIndexerClient.

- * - *

The following sample creates a SearchClient

- * - * - *
- * SearchClient searchClient = new SearchClientBuilder()
- *     .endpoint("{endpoint}")
- *     .credential(new AzureKeyCredential("{key}"))
- *     .indexName("{indexName}")
- *     .buildClient();
- * 
- * - * - *

Key Concepts

- * - *

An Azure AI Search service contains one or more indexes that provide persistent storage of searchable data - * in the form of JSON documents. (If you're new to search, you can make a very rough analogy between indexes and - * database tables.) The azure-search-documents client library exposes operations on these resources through two main - * client types.

- * - *

SearchClient helps with:

- * - *

SearchIndexClient allows you to:

- *
    - *
  • Create, delete, update, or configure a search index
  • - *
  • Declare custom synonym maps to expand or rewrite queries
  • - *
  • Most of the SearchServiceClient functionality is not yet available in our current preview
  • - *
- *

SearchIndexerClient allows you to:

- *
    - *
  • Start indexers to automatically crawl data sources
  • - *
  • Define AI powered Skillsets to transform and enrich your data
  • - *
- * - *

Azure AI Search provides two powerful features:

- * - *

Semantic Search

- * - *

Semantic search enhances the quality of search results for text-based queries. By enabling Semantic Search on - * your search service, you can improve the relevance of search results in two ways:

- * - *
    - *
  • It applies secondary ranking to the initial result set, promoting the most semantically relevant results to the top.
  • - *
  • It extracts and returns captions and answers in the response, which can be displayed on a search page to enhance the user's search experience.
  • - *
- * - *

To learn more about Semantic Search, you can refer to the documentation.

- * - *

Vector Search

- * - *

Vector Search is an information retrieval technique that overcomes the limitations of traditional keyword-based - * search. Instead of relying solely on lexical analysis and matching individual query terms, Vector Search utilizes - * machine learning models to capture the contextual meaning of words and phrases. It represents documents and queries - * as vectors in a high-dimensional space called an embedding. By understanding the intent behind the query, - * Vector Search can deliver more relevant results that align with the user's requirements, even if the exact terms are - * not present in the document. Moreover, Vector Search can be applied to various types of content, including images - * and videos, not just text.

- * - *

To learn how to index vector fields and perform vector search, you can refer to the sample. - * This sample provides detailed guidance on indexing vector fields and demonstrates how to perform vector search.

- * - *

Additionally, for more comprehensive information about Vector Search, including its concepts and usage, you can - * refer to the documentation. The documentation provides in-depth explanations and guidance on leveraging the power of - * Vector Search in Azure AI Search.

- * - *

Examples

- * - *

The following examples all use a sample Hotel data set that you can import into your own index from the Azure - * portal. These are just a few of the basics - please check out our Samples for much more.

- * - *

Querying

- * - *

There are two ways to interact with the data returned from a search query.

- * - *
Use SearchDocument like a dictionary for search results
- * - *

SearchDocument is the default type returned from queries when you don't provide your own. The following sample performs the - * search, enumerates over the results, and extracts data using SearchDocument's dictionary indexer.

- * - * - *
- * for (SearchResult result : searchClient.search("luxury")) {
- *     SearchDocument document = result.getDocument(SearchDocument.class);
- *     System.out.printf("Hotel ID: %s%n", document.get("hotelId"));
- *     System.out.printf("Hotel Name: %s%n", document.get("hotelName"));
- * }
- * 
- * - * - *
Use Java model class for search results
- * - *

Define a `Hotel` class.

- * - * - *
- * public static class Hotel {
- *     private String hotelId;
- *     private String hotelName;
- *
- *     @SimpleField(isKey = true)
- *     public String getHotelId() {
- *         return this.hotelId;
- *     }
- *
- *     public String getHotelName() {
- *         return this.hotelName;
- *     }
- *
- *     public Hotel setHotelId(String number) {
- *         this.hotelId = number;
- *         return this;
- *     }
- *
- *     public Hotel setHotelName(String secretPointMotel) {
- *         this.hotelName = secretPointMotel;
- *         return this;
- *     }
- * }
- * 
- * - * - *

Use it in place of SearchDocument when querying.

- * - * - *
- * for (SearchResult result : searchClient.search("luxury")) {
- *     Hotel hotel = result.getDocument(Hotel.class);
- *     System.out.printf("Hotel ID: %s%n", hotel.getHotelId());
- *     System.out.printf("Hotel Name: %s%n", hotel.getHotelName());
- * }
- * 
- * - * - *
Search Options
- * - *

The SearchOptions provide powerful control over the behavior of our queries.

- * - *

The following sample uses SearchOptions to search for the top 5 luxury hotel with a good rating (4 or above).

- * - * - *
- * SearchOptions options = new SearchOptions()
- *     .setFilter("rating gt 4")
- *     .setOrderBy("rating desc")
- *     .setTop(5);
- * SearchPagedIterable searchResultsIterable = searchClient.search("luxury", options, Context.NONE);
- * searchResultsIterable.forEach(result -> {
- *     System.out.printf("Hotel ID: %s%n", result.getDocument(Hotel.class).getHotelId());
- *     System.out.printf("Hotel Name: %s%n", result.getDocument(Hotel.class).getHotelName());
- * });
- * 
- * - * - *

Creating an index

- * - *

You can use the SearchIndexClient to create a search index. Indexes can also define suggesters, lexical analyzers, - * and more.

- * - *

There are multiple ways of preparing search fields for a search index. For basic needs, there is a static helper - * method buildSearchFields in SearchIndexClient and SearchIndexAsyncClient. There are three annotations - * SimpleFieldProperty, SearchFieldProperty and FieldBuilderIgnore to configure the field of model class.

- * - * - *
- * // Create a new search index structure that matches the properties of the Hotel class.
- * List<SearchField> searchFields = SearchIndexClient.buildSearchFields(Hotel.class, null);
- * searchIndexClient.createIndex(new SearchIndex("hotels", searchFields));
- * 
- * - * - *

For advanced scenarios, you can build search fields using SearchField directly. The following sample shows how to - * build search fields with SearchField.

- * - * - *
- * // Create a new search index structure that matches the properties of the Hotel class.
- * List<SearchField> searchFieldList = new ArrayList<>();
- * searchFieldList.add(new SearchField("hotelId", SearchFieldDataType.STRING)
- *         .setKey(true)
- *         .setFilterable(true)
- *         .setSortable(true));
- *
- * searchFieldList.add(new SearchField("hotelName", SearchFieldDataType.STRING)
- *         .setSearchable(true)
- *         .setFilterable(true)
- *         .setSortable(true));
- * searchFieldList.add(new SearchField("description", SearchFieldDataType.STRING)
- *     .setSearchable(true)
- *     .setAnalyzerName(LexicalAnalyzerName.EU_LUCENE));
- * searchFieldList.add(new SearchField("tags", SearchFieldDataType.collection(SearchFieldDataType.STRING))
- *     .setSearchable(true)
- *     .setFilterable(true)
- *     .setFacetable(true));
- * searchFieldList.add(new SearchField("address", SearchFieldDataType.COMPLEX)
- *     .setFields(new SearchField("streetAddress", SearchFieldDataType.STRING).setSearchable(true),
- *         new SearchField("city", SearchFieldDataType.STRING)
- *             .setSearchable(true)
- *             .setFilterable(true)
- *             .setFacetable(true)
- *             .setSortable(true),
- *         new SearchField("stateProvince", SearchFieldDataType.STRING)
- *             .setSearchable(true)
- *             .setFilterable(true)
- *             .setFacetable(true)
- *             .setSortable(true),
- *         new SearchField("country", SearchFieldDataType.STRING)
- *             .setSearchable(true)
- *             .setFilterable(true)
- *             .setFacetable(true)
- *             .setSortable(true),
- *         new SearchField("postalCode", SearchFieldDataType.STRING)
- *             .setSearchable(true)
- *             .setFilterable(true)
- *             .setFacetable(true)
- *             .setSortable(true)
- *     ));
- *
- * // Prepare suggester.
- * SearchSuggester suggester = new SearchSuggester("sg", Collections.singletonList("hotelName"));
- * // Prepare SearchIndex with index name and search fields.
- * SearchIndex index = new SearchIndex("hotels").setFields(searchFieldList).setSuggesters(suggester);
- * // Create an index
- * searchIndexClient.createIndex(index);
- * 
- * - * - *

Retrieving a specific document from your index

- * - *

In addition to querying for documents using keywords and optional filters, you can retrieve a specific document from your index if you already know the key.

- * - *

The following example retrieves a document using the document's key.

- * - * - *
- * Hotel hotel = searchClient.getDocument("1", Hotel.class);
- * System.out.printf("Hotel ID: %s%n", hotel.getHotelId());
- * System.out.printf("Hotel Name: %s%n", hotel.getHotelName());
- * 
- * - * - *

Adding documents to your index

- * - *

You can Upload, Merge, MergeOrUpload, and Delete multiple documents from an index in a single batched request. - * There are a few special rules for merging to be aware of.

- * - *

The following sample shows using a single batch request to perform a document upload and merge in a single request.

- * - * - *
- * IndexDocumentsBatch<Hotel> batch = new IndexDocumentsBatch<Hotel>();
- * batch.addUploadActions(Collections.singletonList(
- *         new Hotel().setHotelId("783").setHotelName("Upload Inn")));
- * batch.addMergeActions(Collections.singletonList(
- *         new Hotel().setHotelId("12").setHotelName("Renovated Ranch")));
- * searchClient.indexDocuments(batch);
- * 
- * - * - *

Async APIs

- * - *

The examples so far have been using synchronous APIs. For asynchronous support and examples, please see our asynchronous clients:

- * - *
    - *
  • SearchIndexAsyncClient
  • - *
  • SearchIndexerAsyncClient
  • - *
  • SearchAsyncClient
  • - *
- * - *

Authenticate in a National Cloud

- * - *

To authenticate a National Cloud, you will need to make the following additions to your client configuration:

- * - *
    - *
  • Set `AuthorityHost` in the credential potions or via the `AZURE_AUTHORITY_HOST` environment variable
  • - *
  • Set the `audience` in SearchClientBuilder, SearchIndexClientBuilder, SearchIndexerClientBuilder
  • - *
- * - * - *
- * SearchClient searchClient = new SearchClientBuilder()
- *     .endpoint("{endpoint}")
- *     .credential(new DefaultAzureCredentialBuilder()
- *         .authorityHost("{national cloud endpoint}")
- *         .build())
- *     .audience(SearchAudience.AZURE_PUBLIC_CLOUD) //set the audience of your cloud
- *     .buildClient();
- * 
- * - * - *

Troubleshooting

- * - *

See our troubleshooting guide for details on how to diagnose various failure scenarios.

- * - *

General

- * - *

When you interact with Azure AI Search using this Java client library, errors returned by the service - * correspond to the same HTTP status codes returned for REST API requests. For example, the service will return a 404 - * error if you try to retrieve a document that doesn't exist in your index.

- * - *

Handling Search Error Response

- * - *

Any Search API operation that fails will throw an HttpResponseException with helpful Status codes. Many of these errors are recoverable.

- * - * - *
- * try {
- *     Iterable<SearchResult> results = searchClient.search("hotel");
- *     results.forEach(result -> {
- *         System.out.println(result.getDocument(Hotel.class).getHotelName());
- *     });
- * } catch (HttpResponseException ex) {
- *     // The exception contains the HTTP status code and the detailed message
- *     // returned from the search service
- *     HttpResponse response = ex.getResponse();
- *     System.out.println("Status Code: " + response.getStatusCode());
- *     System.out.println("Message: " + ex.getMessage());
- * }
- * 
- * - * - * - * @see com.azure.search.documents.SearchClient - * @see com.azure.search.documents.SearchAsyncClient - * @see com.azure.search.documents.SearchClientBuilder - * @see com.azure.search.documents.indexes.SearchIndexClient - * @see com.azure.search.documents.indexes.SearchIndexAsyncClient - * @see com.azure.search.documents.indexes.SearchIndexClientBuilder - * @see com.azure.search.documents.indexes.SearchIndexerClient - * @see com.azure.search.documents.indexes.SearchIndexerAsyncClient - * @see com.azure.search.documents.indexes.SearchIndexerClientBuilder - * @see com.azure.search.documents.models.SearchOptions - * @see com.azure.search.documents.indexes.models.SearchField - * - */ -package com.azure.search.documents.indexes; diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/AIFoundryModelCatalogName.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/AIFoundryModelCatalogName.java new file mode 100644 index 000000000000..c2a28088b8bd --- /dev/null +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/AIFoundryModelCatalogName.java @@ -0,0 +1,87 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.search.documents.models; + +import com.azure.core.annotation.Generated; +import com.azure.core.util.ExpandableStringEnum; +import java.util.Collection; + +/** + * The name of the embedding model from the Azure AI Foundry Catalog that will be + * called. + */ +public final class AIFoundryModelCatalogName extends ExpandableStringEnum { + /** + * OpenAI-CLIP-Image-Text-Embeddings-vit-base-patch32. + */ + @Generated + public static final AIFoundryModelCatalogName OPEN_AICLIPIMAGE_TEXT_EMBEDDINGS_VIT_BASE_PATCH32 + = fromString("OpenAI-CLIP-Image-Text-Embeddings-vit-base-patch32"); + + /** + * OpenAI-CLIP-Image-Text-Embeddings-ViT-Large-Patch14-336. + */ + @Generated + public static final AIFoundryModelCatalogName OPEN_AICLIPIMAGE_TEXT_EMBEDDINGS_VI_TLARGE_PATCH14336 + = fromString("OpenAI-CLIP-Image-Text-Embeddings-ViT-Large-Patch14-336"); + + /** + * Facebook-DinoV2-Image-Embeddings-ViT-Base. + */ + @Generated + public static final AIFoundryModelCatalogName FACEBOOK_DINO_V2IMAGE_EMBEDDINGS_VI_TBASE + = fromString("Facebook-DinoV2-Image-Embeddings-ViT-Base"); + + /** + * Facebook-DinoV2-Image-Embeddings-ViT-Giant. + */ + @Generated + public static final AIFoundryModelCatalogName FACEBOOK_DINO_V2IMAGE_EMBEDDINGS_VI_TGIANT + = fromString("Facebook-DinoV2-Image-Embeddings-ViT-Giant"); + + /** + * Cohere-embed-v3-english. + */ + @Generated + public static final AIFoundryModelCatalogName COHERE_EMBED_V3ENGLISH = fromString("Cohere-embed-v3-english"); + + /** + * Cohere-embed-v3-multilingual. + */ + @Generated + public static final AIFoundryModelCatalogName COHERE_EMBED_V3MULTILINGUAL + = fromString("Cohere-embed-v3-multilingual"); + + /** + * Creates a new instance of AIFoundryModelCatalogName value. + * + * @deprecated Use the {@link #fromString(String)} factory method. + */ + @Generated + @Deprecated + public AIFoundryModelCatalogName() { + } + + /** + * Creates or finds a AIFoundryModelCatalogName from its string representation. + * + * @param name a name to look for. + * @return the corresponding AIFoundryModelCatalogName. + */ + @Generated + public static AIFoundryModelCatalogName fromString(String name) { + return fromString(name, AIFoundryModelCatalogName.class); + } + + /** + * Gets known AIFoundryModelCatalogName values. + * + * @return known AIFoundryModelCatalogName values. + */ + @Generated + public static Collection values() { + return values(AIFoundryModelCatalogName.class); + } +} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/AIServicesAccountIdentity.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/AIServicesAccountIdentity.java similarity index 65% rename from sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/AIServicesAccountIdentity.java rename to sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/AIServicesAccountIdentity.java index 6adbccf16762..b1d7bbd1886a 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/AIServicesAccountIdentity.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/AIServicesAccountIdentity.java @@ -1,58 +1,59 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) TypeSpec Code Generator. -package com.azure.search.documents.indexes.models; +package com.azure.search.documents.models; import com.azure.core.annotation.Fluent; +import com.azure.core.annotation.Generated; import com.azure.json.JsonReader; import com.azure.json.JsonToken; import com.azure.json.JsonWriter; import java.io.IOException; -import java.util.ArrayList; -import java.util.List; /** - * The multi-region account of an Azure AI service resource that's attached to a skillset. + * The multi-region account of an Azure AI service resource that's attached to a + * skillset. */ @Fluent public final class AIServicesAccountIdentity extends CognitiveServicesAccount { /* - * A URI fragment specifying the type of Azure AI service resource attached to a skillset. + * The discriminator for derived types. */ + @Generated private String odataType = "#Microsoft.Azure.Search.AIServicesByIdentity"; /* - * 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. + * 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. */ - private final SearchIndexerDataIdentity identity; + @Generated + private SearchIndexerDataIdentity identity; /* * The subdomain url for the corresponding AI Service. */ + @Generated private final String subdomainUrl; /** * Creates an instance of AIServicesAccountIdentity class. * - * @param identity the identity value to set. * @param subdomainUrl the subdomainUrl value to set. */ - public AIServicesAccountIdentity(SearchIndexerDataIdentity identity, String subdomainUrl) { - this.identity = identity; + @Generated + public AIServicesAccountIdentity(String subdomainUrl) { this.subdomainUrl = subdomainUrl; } /** - * Get the odataType property: A URI fragment specifying the type of Azure AI service resource attached to a - * skillset. + * Get the odataType property: The discriminator for derived types. * * @return the odataType value. */ + @Generated @Override public String getOdataType() { return this.odataType; @@ -60,20 +61,38 @@ public String getOdataType() { /** * Get the identity property: 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. + * 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. * * @return the identity value. */ + @Generated public SearchIndexerDataIdentity getIdentity() { return this.identity; } + /** + * Set the identity property: 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. + * + * @param identity the identity value to set. + * @return the AIServicesAccountIdentity object itself. + */ + @Generated + public AIServicesAccountIdentity setIdentity(SearchIndexerDataIdentity identity) { + this.identity = identity; + return this; + } + /** * Get the subdomainUrl property: The subdomain url for the corresponding AI Service. * * @return the subdomainUrl value. */ + @Generated public String getSubdomainUrl() { return this.subdomainUrl; } @@ -81,6 +100,7 @@ public String getSubdomainUrl() { /** * {@inheritDoc} */ + @Generated @Override public AIServicesAccountIdentity setDescription(String description) { super.setDescription(description); @@ -90,13 +110,14 @@ public AIServicesAccountIdentity setDescription(String description) { /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); jsonWriter.writeStringField("description", getDescription()); - jsonWriter.writeJsonField("identity", this.identity); jsonWriter.writeStringField("subdomainUrl", this.subdomainUrl); jsonWriter.writeStringField("@odata.type", this.odataType); + jsonWriter.writeJsonField("identity", this.identity); return jsonWriter.writeEndObject(); } @@ -109,50 +130,36 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { * @throws IllegalStateException If the deserialized JSON object was missing any required properties. * @throws IOException If an error occurs while reading the AIServicesAccountIdentity. */ + @Generated public static AIServicesAccountIdentity fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { String description = null; - boolean identityFound = false; - SearchIndexerDataIdentity identity = null; - boolean subdomainUrlFound = false; String subdomainUrl = null; String odataType = "#Microsoft.Azure.Search.AIServicesByIdentity"; + SearchIndexerDataIdentity identity = null; while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); if ("description".equals(fieldName)) { description = reader.getString(); - } else if ("identity".equals(fieldName)) { - identity = SearchIndexerDataIdentity.fromJson(reader); - identityFound = true; } else if ("subdomainUrl".equals(fieldName)) { subdomainUrl = reader.getString(); - subdomainUrlFound = true; } else if ("@odata.type".equals(fieldName)) { odataType = reader.getString(); + } else if ("identity".equals(fieldName)) { + identity = SearchIndexerDataIdentity.fromJson(reader); } else { reader.skipChildren(); } } - if (identityFound && subdomainUrlFound) { - AIServicesAccountIdentity deserializedAIServicesAccountIdentity - = new AIServicesAccountIdentity(identity, subdomainUrl); - deserializedAIServicesAccountIdentity.setDescription(description); - deserializedAIServicesAccountIdentity.odataType = odataType; - - return deserializedAIServicesAccountIdentity; - } - List missingProperties = new ArrayList<>(); - if (!identityFound) { - missingProperties.add("identity"); - } - if (!subdomainUrlFound) { - missingProperties.add("subdomainUrl"); - } + AIServicesAccountIdentity deserializedAIServicesAccountIdentity + = new AIServicesAccountIdentity(subdomainUrl); + deserializedAIServicesAccountIdentity.setDescription(description); + deserializedAIServicesAccountIdentity.odataType = odataType; + deserializedAIServicesAccountIdentity.identity = identity; - throw new IllegalStateException( - "Missing required property/properties: " + String.join(", ", missingProperties)); + return deserializedAIServicesAccountIdentity; }); } } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/AIServicesAccountKey.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/AIServicesAccountKey.java similarity index 72% rename from sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/AIServicesAccountKey.java rename to sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/AIServicesAccountKey.java index 181add109ae0..1a7e09c55bd2 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/AIServicesAccountKey.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/AIServicesAccountKey.java @@ -1,38 +1,38 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) TypeSpec Code Generator. -package com.azure.search.documents.indexes.models; +package com.azure.search.documents.models; import com.azure.core.annotation.Fluent; +import com.azure.core.annotation.Generated; import com.azure.json.JsonReader; import com.azure.json.JsonToken; import com.azure.json.JsonWriter; import java.io.IOException; -import java.util.ArrayList; -import java.util.List; /** - * The account key of an Azure AI service resource that's attached to a skillset, to be used with the resource's - * subdomain. + * The account key of an Azure AI service resource that's attached to a skillset, + * to be used with the resource's subdomain. */ @Fluent public final class AIServicesAccountKey extends CognitiveServicesAccount { /* - * A URI fragment specifying the type of Azure AI service resource attached to a skillset. + * The discriminator for derived types. */ + @Generated private String odataType = "#Microsoft.Azure.Search.AIServicesByKey"; /* * The key used to provision the Azure AI service resource attached to a skillset. */ + @Generated private final String key; /* * The subdomain url for the corresponding AI Service. */ + @Generated private final String subdomainUrl; /** @@ -41,17 +41,18 @@ public final class AIServicesAccountKey extends CognitiveServicesAccount { * @param key the key value to set. * @param subdomainUrl the subdomainUrl value to set. */ + @Generated public AIServicesAccountKey(String key, String subdomainUrl) { this.key = key; this.subdomainUrl = subdomainUrl; } /** - * Get the odataType property: A URI fragment specifying the type of Azure AI service resource attached to a - * skillset. + * Get the odataType property: The discriminator for derived types. * * @return the odataType value. */ + @Generated @Override public String getOdataType() { return this.odataType; @@ -62,6 +63,7 @@ public String getOdataType() { * * @return the key value. */ + @Generated public String getKey() { return this.key; } @@ -71,6 +73,7 @@ public String getKey() { * * @return the subdomainUrl value. */ + @Generated public String getSubdomainUrl() { return this.subdomainUrl; } @@ -78,6 +81,7 @@ public String getSubdomainUrl() { /** * {@inheritDoc} */ + @Generated @Override public AIServicesAccountKey setDescription(String description) { super.setDescription(description); @@ -87,6 +91,7 @@ public AIServicesAccountKey setDescription(String description) { /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); @@ -106,12 +111,11 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { * @throws IllegalStateException If the deserialized JSON object was missing any required properties. * @throws IOException If an error occurs while reading the AIServicesAccountKey. */ + @Generated public static AIServicesAccountKey fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { String description = null; - boolean keyFound = false; String key = null; - boolean subdomainUrlFound = false; String subdomainUrl = null; String odataType = "#Microsoft.Azure.Search.AIServicesByKey"; while (reader.nextToken() != JsonToken.END_OBJECT) { @@ -122,33 +126,19 @@ public static AIServicesAccountKey fromJson(JsonReader jsonReader) throws IOExce description = reader.getString(); } else if ("key".equals(fieldName)) { key = reader.getString(); - keyFound = true; } else if ("subdomainUrl".equals(fieldName)) { subdomainUrl = reader.getString(); - subdomainUrlFound = true; } else if ("@odata.type".equals(fieldName)) { odataType = reader.getString(); } else { reader.skipChildren(); } } - if (keyFound && subdomainUrlFound) { - AIServicesAccountKey deserializedAIServicesAccountKey = new AIServicesAccountKey(key, subdomainUrl); - deserializedAIServicesAccountKey.setDescription(description); - deserializedAIServicesAccountKey.odataType = odataType; + AIServicesAccountKey deserializedAIServicesAccountKey = new AIServicesAccountKey(key, subdomainUrl); + deserializedAIServicesAccountKey.setDescription(description); + deserializedAIServicesAccountKey.odataType = odataType; - return deserializedAIServicesAccountKey; - } - List missingProperties = new ArrayList<>(); - if (!keyFound) { - missingProperties.add("key"); - } - if (!subdomainUrlFound) { - missingProperties.add("subdomainUrl"); - } - - throw new IllegalStateException( - "Missing required property/properties: " + String.join(", ", missingProperties)); + return deserializedAIServicesAccountKey; }); } } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/AIServicesVisionParameters.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/AIServicesVisionParameters.java similarity index 71% rename from sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/AIServicesVisionParameters.java rename to sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/AIServicesVisionParameters.java index b5ca72d1ff3b..b7079e1d5445 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/AIServicesVisionParameters.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/AIServicesVisionParameters.java @@ -1,46 +1,50 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) TypeSpec Code Generator. -package com.azure.search.documents.indexes.models; +package com.azure.search.documents.models; import com.azure.core.annotation.Fluent; +import com.azure.core.annotation.Generated; import com.azure.json.JsonReader; import com.azure.json.JsonSerializable; import com.azure.json.JsonToken; import com.azure.json.JsonWriter; import java.io.IOException; -import java.util.ArrayList; -import java.util.List; /** - * Specifies the AI Services Vision parameters for vectorizing a query image or text. + * Specifies the AI Services Vision parameters for vectorizing a query image or + * text. */ @Fluent public final class AIServicesVisionParameters implements JsonSerializable { /* - * The version of the model to use when calling the AI Services Vision service. It will default to the latest - * available when not specified. + * The version of the model to use when calling the AI Services Vision service. It + * will default to the latest available when not specified. */ + @Generated private final String modelVersion; /* * The resource URI of the AI Services resource. */ + @Generated private final String resourceUri; /* * API key of the designated AI Services resource. */ + @Generated private String apiKey; /* - * 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. + * 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. */ + @Generated private SearchIndexerDataIdentity authIdentity; /** @@ -49,6 +53,7 @@ public final class AIServicesVisionParameters implements JsonSerializable { - boolean modelVersionFound = false; String modelVersion = null; - boolean resourceUriFound = false; String resourceUri = null; String apiKey = null; SearchIndexerDataIdentity authIdentity = null; @@ -155,10 +168,8 @@ public static AIServicesVisionParameters fromJson(JsonReader jsonReader) throws if ("modelVersion".equals(fieldName)) { modelVersion = reader.getString(); - modelVersionFound = true; } else if ("resourceUri".equals(fieldName)) { resourceUri = reader.getString(); - resourceUriFound = true; } else if ("apiKey".equals(fieldName)) { apiKey = reader.getString(); } else if ("authIdentity".equals(fieldName)) { @@ -167,24 +178,12 @@ public static AIServicesVisionParameters fromJson(JsonReader jsonReader) throws reader.skipChildren(); } } - if (modelVersionFound && resourceUriFound) { - AIServicesVisionParameters deserializedAIServicesVisionParameters - = new AIServicesVisionParameters(modelVersion, resourceUri); - deserializedAIServicesVisionParameters.apiKey = apiKey; - deserializedAIServicesVisionParameters.authIdentity = authIdentity; - - return deserializedAIServicesVisionParameters; - } - List missingProperties = new ArrayList<>(); - if (!modelVersionFound) { - missingProperties.add("modelVersion"); - } - if (!resourceUriFound) { - missingProperties.add("resourceUri"); - } + AIServicesVisionParameters deserializedAIServicesVisionParameters + = new AIServicesVisionParameters(modelVersion, resourceUri); + deserializedAIServicesVisionParameters.apiKey = apiKey; + deserializedAIServicesVisionParameters.authIdentity = authIdentity; - throw new IllegalStateException( - "Missing required property/properties: " + String.join(", ", missingProperties)); + return deserializedAIServicesVisionParameters; }); } } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/AIServicesVisionVectorizer.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/AIServicesVisionVectorizer.java similarity index 75% rename from sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/AIServicesVisionVectorizer.java rename to sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/AIServicesVisionVectorizer.java index 70514b51bc59..ad9079e0cf36 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/AIServicesVisionVectorizer.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/AIServicesVisionVectorizer.java @@ -1,30 +1,31 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) TypeSpec Code Generator. -package com.azure.search.documents.indexes.models; +package com.azure.search.documents.models; import com.azure.core.annotation.Fluent; +import com.azure.core.annotation.Generated; import com.azure.json.JsonReader; import com.azure.json.JsonToken; import com.azure.json.JsonWriter; import java.io.IOException; /** - * Specifies the AI Services Vision parameters for vectorizing a query image or text. + * Clears the identity property of a datasource. */ @Fluent public final class AIServicesVisionVectorizer extends VectorSearchVectorizer { /* - * The name of the kind of vectorization method being configured for use with vector search. + * Type of VectorSearchVectorizer. */ + @Generated private VectorSearchVectorizerKind kind = VectorSearchVectorizerKind.AISERVICES_VISION; /* * Contains the parameters specific to AI Services Vision embedding vectorization. */ + @Generated private AIServicesVisionParameters aIServicesVisionParameters; /** @@ -32,15 +33,17 @@ public final class AIServicesVisionVectorizer extends VectorSearchVectorizer { * * @param vectorizerName the vectorizerName value to set. */ + @Generated public AIServicesVisionVectorizer(String vectorizerName) { super(vectorizerName); } /** - * Get the kind property: The name of the kind of vectorization method being configured for use with vector search. + * Get the kind property: Type of VectorSearchVectorizer. * * @return the kind value. */ + @Generated @Override public VectorSearchVectorizerKind getKind() { return this.kind; @@ -52,6 +55,7 @@ public VectorSearchVectorizerKind getKind() { * * @return the aIServicesVisionParameters value. */ + @Generated public AIServicesVisionParameters getAIServicesVisionParameters() { return this.aIServicesVisionParameters; } @@ -63,6 +67,7 @@ public AIServicesVisionParameters getAIServicesVisionParameters() { * @param aIServicesVisionParameters the aIServicesVisionParameters value to set. * @return the AIServicesVisionVectorizer object itself. */ + @Generated public AIServicesVisionVectorizer setAIServicesVisionParameters(AIServicesVisionParameters aIServicesVisionParameters) { this.aIServicesVisionParameters = aIServicesVisionParameters; @@ -72,12 +77,13 @@ public AIServicesVisionParameters getAIServicesVisionParameters() { /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); jsonWriter.writeStringField("name", getVectorizerName()); jsonWriter.writeStringField("kind", this.kind == null ? null : this.kind.toString()); - jsonWriter.writeJsonField("aiServicesVisionParameters", this.aIServicesVisionParameters); + jsonWriter.writeJsonField("AIServicesVisionParameters", this.aIServicesVisionParameters); return jsonWriter.writeEndObject(); } @@ -90,9 +96,9 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { * @throws IllegalStateException If the deserialized JSON object was missing any required properties. * @throws IOException If an error occurs while reading the AIServicesVisionVectorizer. */ + @Generated public static AIServicesVisionVectorizer fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { - boolean vectorizerNameFound = false; String vectorizerName = null; VectorSearchVectorizerKind kind = VectorSearchVectorizerKind.AISERVICES_VISION; AIServicesVisionParameters aIServicesVisionParameters = null; @@ -102,24 +108,20 @@ public static AIServicesVisionVectorizer fromJson(JsonReader jsonReader) throws if ("name".equals(fieldName)) { vectorizerName = reader.getString(); - vectorizerNameFound = true; } else if ("kind".equals(fieldName)) { kind = VectorSearchVectorizerKind.fromString(reader.getString()); - } else if ("aiServicesVisionParameters".equals(fieldName)) { + } else if ("AIServicesVisionParameters".equals(fieldName)) { aIServicesVisionParameters = AIServicesVisionParameters.fromJson(reader); } else { reader.skipChildren(); } } - if (vectorizerNameFound) { - AIServicesVisionVectorizer deserializedAIServicesVisionVectorizer - = new AIServicesVisionVectorizer(vectorizerName); - deserializedAIServicesVisionVectorizer.kind = kind; - deserializedAIServicesVisionVectorizer.aIServicesVisionParameters = aIServicesVisionParameters; + AIServicesVisionVectorizer deserializedAIServicesVisionVectorizer + = new AIServicesVisionVectorizer(vectorizerName); + deserializedAIServicesVisionVectorizer.kind = kind; + deserializedAIServicesVisionVectorizer.aIServicesVisionParameters = aIServicesVisionParameters; - return deserializedAIServicesVisionVectorizer; - } - throw new IllegalStateException("Missing required property: name"); + return deserializedAIServicesVisionVectorizer; }); } } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/implementation/models/AnalyzeRequest.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/AnalyzeRequest.java similarity index 76% rename from sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/implementation/models/AnalyzeRequest.java rename to sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/AnalyzeRequest.java index 98fdcca52dfe..5465ea373a97 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/implementation/models/AnalyzeRequest.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/AnalyzeRequest.java @@ -1,21 +1,15 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) TypeSpec Code Generator. -package com.azure.search.documents.indexes.implementation.models; +package com.azure.search.documents.models; import com.azure.core.annotation.Fluent; +import com.azure.core.annotation.Generated; import com.azure.json.JsonReader; import com.azure.json.JsonSerializable; import com.azure.json.JsonToken; import com.azure.json.JsonWriter; -import com.azure.search.documents.indexes.models.CharFilterName; -import com.azure.search.documents.indexes.models.LexicalAnalyzerName; -import com.azure.search.documents.indexes.models.LexicalNormalizerName; -import com.azure.search.documents.indexes.models.LexicalTokenizerName; -import com.azure.search.documents.indexes.models.TokenFilterName; import java.io.IOException; import java.util.List; @@ -27,35 +21,43 @@ public final class AnalyzeRequest implements JsonSerializable { /* * The text to break into tokens. */ + @Generated private final String text; /* - * 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. + * 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. */ + @Generated private LexicalAnalyzerName analyzer; /* - * 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. + * 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. */ + @Generated private LexicalTokenizerName tokenizer; /* * The name of the normalizer to use to normalize the given text. */ + @Generated private LexicalNormalizerName normalizer; /* - * An optional list of token filters to use when breaking the given text. This parameter can only be set when using - * the tokenizer parameter. + * An optional list of token filters to use when breaking the given text. This + * parameter can only be set when using the tokenizer parameter. */ + @Generated private List tokenFilters; /* - * An optional list of character filters to use when breaking the given text. This parameter can only be set when - * using the tokenizer parameter. + * An optional list of character filters to use when breaking the given text. This + * parameter can only be set when using the tokenizer parameter. */ + @Generated private List charFilters; /** @@ -63,6 +65,7 @@ public final class AnalyzeRequest implements JsonSerializable { * * @param text the text value to set. */ + @Generated public AnalyzeRequest(String text) { this.text = text; } @@ -72,49 +75,58 @@ public AnalyzeRequest(String text) { * * @return the text value. */ + @Generated public String getText() { return this.text; } /** - * Get the analyzer property: 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. + * Get the analyzer property: 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. * * @return the analyzer value. */ + @Generated public LexicalAnalyzerName getAnalyzer() { return this.analyzer; } /** - * Set the analyzer property: 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. + * Set the analyzer property: 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. * * @param analyzer the analyzer value to set. * @return the AnalyzeRequest object itself. */ + @Generated public AnalyzeRequest setAnalyzer(LexicalAnalyzerName analyzer) { this.analyzer = analyzer; return this; } /** - * Get the tokenizer property: 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. + * Get the tokenizer property: 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. * * @return the tokenizer value. */ + @Generated public LexicalTokenizerName getTokenizer() { return this.tokenizer; } /** - * Set the tokenizer property: 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. + * Set the tokenizer property: 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. * * @param tokenizer the tokenizer value to set. * @return the AnalyzeRequest object itself. */ + @Generated public AnalyzeRequest setTokenizer(LexicalTokenizerName tokenizer) { this.tokenizer = tokenizer; return this; @@ -125,6 +137,7 @@ public AnalyzeRequest setTokenizer(LexicalTokenizerName tokenizer) { * * @return the normalizer value. */ + @Generated public LexicalNormalizerName getNormalizer() { return this.normalizer; } @@ -135,6 +148,7 @@ public LexicalNormalizerName getNormalizer() { * @param normalizer the normalizer value to set. * @return the AnalyzeRequest object itself. */ + @Generated public AnalyzeRequest setNormalizer(LexicalNormalizerName normalizer) { this.normalizer = normalizer; return this; @@ -146,6 +160,7 @@ public AnalyzeRequest setNormalizer(LexicalNormalizerName normalizer) { * * @return the tokenFilters value. */ + @Generated public List getTokenFilters() { return this.tokenFilters; } @@ -157,6 +172,7 @@ public List getTokenFilters() { * @param tokenFilters the tokenFilters value to set. * @return the AnalyzeRequest object itself. */ + @Generated public AnalyzeRequest setTokenFilters(List tokenFilters) { this.tokenFilters = tokenFilters; return this; @@ -168,6 +184,7 @@ public AnalyzeRequest setTokenFilters(List tokenFilters) { * * @return the charFilters value. */ + @Generated public List getCharFilters() { return this.charFilters; } @@ -179,6 +196,7 @@ public List getCharFilters() { * @param charFilters the charFilters value to set. * @return the AnalyzeRequest object itself. */ + @Generated public AnalyzeRequest setCharFilters(List charFilters) { this.charFilters = charFilters; return this; @@ -187,6 +205,7 @@ public AnalyzeRequest setCharFilters(List charFilters) { /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); @@ -210,9 +229,9 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { * @throws IllegalStateException If the deserialized JSON object was missing any required properties. * @throws IOException If an error occurs while reading the AnalyzeRequest. */ + @Generated public static AnalyzeRequest fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { - boolean textFound = false; String text = null; LexicalAnalyzerName analyzer = null; LexicalTokenizerName tokenizer = null; @@ -225,7 +244,6 @@ public static AnalyzeRequest fromJson(JsonReader jsonReader) throws IOException if ("text".equals(fieldName)) { text = reader.getString(); - textFound = true; } else if ("analyzer".equals(fieldName)) { analyzer = LexicalAnalyzerName.fromString(reader.getString()); } else if ("tokenizer".equals(fieldName)) { @@ -240,17 +258,14 @@ public static AnalyzeRequest fromJson(JsonReader jsonReader) throws IOException reader.skipChildren(); } } - if (textFound) { - AnalyzeRequest deserializedAnalyzeRequest = new AnalyzeRequest(text); - deserializedAnalyzeRequest.analyzer = analyzer; - deserializedAnalyzeRequest.tokenizer = tokenizer; - deserializedAnalyzeRequest.normalizer = normalizer; - deserializedAnalyzeRequest.tokenFilters = tokenFilters; - deserializedAnalyzeRequest.charFilters = charFilters; + AnalyzeRequest deserializedAnalyzeRequest = new AnalyzeRequest(text); + deserializedAnalyzeRequest.analyzer = analyzer; + deserializedAnalyzeRequest.tokenizer = tokenizer; + deserializedAnalyzeRequest.normalizer = normalizer; + deserializedAnalyzeRequest.tokenFilters = tokenFilters; + deserializedAnalyzeRequest.charFilters = charFilters; - return deserializedAnalyzeRequest; - } - throw new IllegalStateException("Missing required property: text"); + return deserializedAnalyzeRequest; }); } } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/implementation/models/AnalyzeResult.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/AnalyzeResult.java similarity index 80% rename from sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/implementation/models/AnalyzeResult.java rename to sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/AnalyzeResult.java index 1c23926a8d3f..919f77334746 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/implementation/models/AnalyzeResult.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/AnalyzeResult.java @@ -1,17 +1,15 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) TypeSpec Code Generator. -package com.azure.search.documents.indexes.implementation.models; +package com.azure.search.documents.models; +import com.azure.core.annotation.Generated; import com.azure.core.annotation.Immutable; import com.azure.json.JsonReader; import com.azure.json.JsonSerializable; import com.azure.json.JsonToken; import com.azure.json.JsonWriter; -import com.azure.search.documents.indexes.models.AnalyzedTokenInfo; import java.io.IOException; import java.util.List; @@ -23,6 +21,7 @@ public final class AnalyzeResult implements JsonSerializable { /* * The list of tokens returned by the analyzer specified in the request. */ + @Generated private final List tokens; /** @@ -30,7 +29,8 @@ public final class AnalyzeResult implements JsonSerializable { * * @param tokens the tokens value to set. */ - public AnalyzeResult(List tokens) { + @Generated + private AnalyzeResult(List tokens) { this.tokens = tokens; } @@ -39,6 +39,7 @@ public AnalyzeResult(List tokens) { * * @return the tokens value. */ + @Generated public List getTokens() { return this.tokens; } @@ -46,6 +47,7 @@ public List getTokens() { /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); @@ -62,9 +64,9 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { * @throws IllegalStateException If the deserialized JSON object was missing any required properties. * @throws IOException If an error occurs while reading the AnalyzeResult. */ + @Generated public static AnalyzeResult fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { - boolean tokensFound = false; List tokens = null; while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); @@ -72,15 +74,11 @@ public static AnalyzeResult fromJson(JsonReader jsonReader) throws IOException { if ("tokens".equals(fieldName)) { tokens = reader.readArray(reader1 -> AnalyzedTokenInfo.fromJson(reader1)); - tokensFound = true; } else { reader.skipChildren(); } } - if (tokensFound) { - return new AnalyzeResult(tokens); - } - throw new IllegalStateException("Missing required property: tokens"); + return new AnalyzeResult(tokens); }); } } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/AnalyzedTokenInfo.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/AnalyzedTokenInfo.java similarity index 66% rename from sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/AnalyzedTokenInfo.java rename to sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/AnalyzedTokenInfo.java index 396d8e8be4f1..bd6f7df64311 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/AnalyzedTokenInfo.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/AnalyzedTokenInfo.java @@ -1,19 +1,16 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) TypeSpec Code Generator. -package com.azure.search.documents.indexes.models; +package com.azure.search.documents.models; +import com.azure.core.annotation.Generated; import com.azure.core.annotation.Immutable; import com.azure.json.JsonReader; import com.azure.json.JsonSerializable; import com.azure.json.JsonToken; import com.azure.json.JsonWriter; import java.io.IOException; -import java.util.ArrayList; -import java.util.List; /** * Information about a token returned by an analyzer. @@ -23,23 +20,28 @@ public final class AnalyzedTokenInfo implements JsonSerializable { - boolean tokenFound = false; String token = null; - boolean startOffsetFound = false; int startOffset = 0; - boolean endOffsetFound = false; int endOffset = 0; - boolean positionFound = false; int position = 0; while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); @@ -129,39 +139,17 @@ public static AnalyzedTokenInfo fromJson(JsonReader jsonReader) throws IOExcepti if ("token".equals(fieldName)) { token = reader.getString(); - tokenFound = true; } else if ("startOffset".equals(fieldName)) { startOffset = reader.getInt(); - startOffsetFound = true; } else if ("endOffset".equals(fieldName)) { endOffset = reader.getInt(); - endOffsetFound = true; } else if ("position".equals(fieldName)) { position = reader.getInt(); - positionFound = true; } else { reader.skipChildren(); } } - if (tokenFound && startOffsetFound && endOffsetFound && positionFound) { - return new AnalyzedTokenInfo(token, startOffset, endOffset, position); - } - List missingProperties = new ArrayList<>(); - if (!tokenFound) { - missingProperties.add("token"); - } - if (!startOffsetFound) { - missingProperties.add("startOffset"); - } - if (!endOffsetFound) { - missingProperties.add("endOffset"); - } - if (!positionFound) { - missingProperties.add("position"); - } - - throw new IllegalStateException( - "Missing required property/properties: " + String.join(", ", missingProperties)); + return new AnalyzedTokenInfo(token, startOffset, endOffset, position); }); } } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/AsciiFoldingTokenFilter.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/AsciiFoldingTokenFilter.java similarity index 76% rename from sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/AsciiFoldingTokenFilter.java rename to sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/AsciiFoldingTokenFilter.java index 5f7d63d1f053..9fe30b08fa57 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/AsciiFoldingTokenFilter.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/AsciiFoldingTokenFilter.java @@ -1,32 +1,34 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) TypeSpec Code Generator. -package com.azure.search.documents.indexes.models; +package com.azure.search.documents.models; import com.azure.core.annotation.Fluent; +import com.azure.core.annotation.Generated; import com.azure.json.JsonReader; import com.azure.json.JsonToken; import com.azure.json.JsonWriter; import java.io.IOException; /** - * 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. + * 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. */ @Fluent public final class AsciiFoldingTokenFilter extends TokenFilter { /* - * A URI fragment specifying the type of token filter. + * The discriminator for derived types. */ + @Generated private String odataType = "#Microsoft.Azure.Search.AsciiFoldingTokenFilter"; /* * A value indicating whether the original token will be kept. Default is false. */ + @Generated private Boolean preserveOriginal; /** @@ -34,15 +36,17 @@ public final class AsciiFoldingTokenFilter extends TokenFilter { * * @param name the name value to set. */ + @Generated public AsciiFoldingTokenFilter(String name) { super(name); } /** - * Get the odataType property: A URI fragment specifying the type of token filter. + * Get the odataType property: The discriminator for derived types. * * @return the odataType value. */ + @Generated @Override public String getOdataType() { return this.odataType; @@ -53,6 +57,7 @@ public String getOdataType() { * * @return the preserveOriginal value. */ + @Generated public Boolean isPreserveOriginal() { return this.preserveOriginal; } @@ -63,6 +68,7 @@ public Boolean isPreserveOriginal() { * @param preserveOriginal the preserveOriginal value to set. * @return the AsciiFoldingTokenFilter object itself. */ + @Generated public AsciiFoldingTokenFilter setPreserveOriginal(Boolean preserveOriginal) { this.preserveOriginal = preserveOriginal; return this; @@ -71,6 +77,7 @@ public AsciiFoldingTokenFilter setPreserveOriginal(Boolean preserveOriginal) { /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); @@ -89,9 +96,9 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { * @throws IllegalStateException If the deserialized JSON object was missing any required properties. * @throws IOException If an error occurs while reading the AsciiFoldingTokenFilter. */ + @Generated public static AsciiFoldingTokenFilter fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { - boolean nameFound = false; String name = null; String odataType = "#Microsoft.Azure.Search.AsciiFoldingTokenFilter"; Boolean preserveOriginal = null; @@ -101,7 +108,6 @@ public static AsciiFoldingTokenFilter fromJson(JsonReader jsonReader) throws IOE if ("name".equals(fieldName)) { name = reader.getString(); - nameFound = true; } else if ("@odata.type".equals(fieldName)) { odataType = reader.getString(); } else if ("preserveOriginal".equals(fieldName)) { @@ -110,14 +116,11 @@ public static AsciiFoldingTokenFilter fromJson(JsonReader jsonReader) throws IOE reader.skipChildren(); } } - if (nameFound) { - AsciiFoldingTokenFilter deserializedAsciiFoldingTokenFilter = new AsciiFoldingTokenFilter(name); - deserializedAsciiFoldingTokenFilter.odataType = odataType; - deserializedAsciiFoldingTokenFilter.preserveOriginal = preserveOriginal; + AsciiFoldingTokenFilter deserializedAsciiFoldingTokenFilter = new AsciiFoldingTokenFilter(name); + deserializedAsciiFoldingTokenFilter.odataType = odataType; + deserializedAsciiFoldingTokenFilter.preserveOriginal = preserveOriginal; - return deserializedAsciiFoldingTokenFilter; - } - throw new IllegalStateException("Missing required property: name"); + return deserializedAsciiFoldingTokenFilter; }); } } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/AutocompleteItem.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/AutocompleteItem.java index 0bacc4bcd200..b3969439ff4b 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/AutocompleteItem.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/AutocompleteItem.java @@ -1,19 +1,16 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.search.documents.models; +import com.azure.core.annotation.Generated; import com.azure.core.annotation.Immutable; import com.azure.json.JsonReader; import com.azure.json.JsonSerializable; import com.azure.json.JsonToken; import com.azure.json.JsonWriter; import java.io.IOException; -import java.util.ArrayList; -import java.util.List; /** * The result of Autocomplete requests. @@ -23,11 +20,13 @@ public final class AutocompleteItem implements JsonSerializable { - boolean textFound = false; String text = null; - boolean queryPlusTextFound = false; String queryPlusText = null; while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); @@ -89,27 +93,13 @@ public static AutocompleteItem fromJson(JsonReader jsonReader) throws IOExceptio if ("text".equals(fieldName)) { text = reader.getString(); - textFound = true; } else if ("queryPlusText".equals(fieldName)) { queryPlusText = reader.getString(); - queryPlusTextFound = true; } else { reader.skipChildren(); } } - if (textFound && queryPlusTextFound) { - return new AutocompleteItem(text, queryPlusText); - } - List missingProperties = new ArrayList<>(); - if (!textFound) { - missingProperties.add("text"); - } - if (!queryPlusTextFound) { - missingProperties.add("queryPlusText"); - } - - throw new IllegalStateException( - "Missing required property/properties: " + String.join(", ", missingProperties)); + return new AutocompleteItem(text, queryPlusText); }); } } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/AutocompleteMode.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/AutocompleteMode.java index 2612bb5ceeea..ee082da923c7 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/AutocompleteMode.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/AutocompleteMode.java @@ -1,68 +1,70 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.search.documents.models; +import com.azure.core.annotation.Generated; +import com.azure.core.util.ExpandableStringEnum; +import java.util.Collection; + /** - * Specifies the mode for Autocomplete. The default is 'oneTerm'. Use 'twoTerms' to get shingles and - * 'oneTermWithContext' to use the current context in producing autocomplete terms. + * Specifies the mode for Autocomplete. The default is 'oneTerm'. Use 'twoTerms' + * to get shingles and 'oneTermWithContext' to use the current context in + * producing autocomplete terms. */ -public enum AutocompleteMode { +public final class AutocompleteMode extends ExpandableStringEnum { /** - * Only one term is suggested. If the query has two terms, only the last term is completed. For example, if the - * input is 'washington medic', the suggested terms could include 'medicaid', 'medicare', and 'medicine'. + * Only one term is suggested. If the query has two terms, only the last term is + * completed. For example, if the input is 'washington medic', the suggested terms + * could include 'medicaid', 'medicare', and 'medicine'. */ - ONE_TERM("oneTerm"), + @Generated + public static final AutocompleteMode ONE_TERM = fromString("oneTerm"); /** - * Matching two-term phrases in the index will be suggested. For example, if the input is 'medic', the suggested - * terms could include 'medicare coverage' and 'medical assistant'. + * Matching two-term phrases in the index will be suggested. For example, if the + * input is 'medic', the suggested terms could include 'medicare coverage' and 'medical assistant'. */ - TWO_TERMS("twoTerms"), + @Generated + public static final AutocompleteMode TWO_TERMS = fromString("twoTerms"); /** - * Completes the last term in a query with two or more terms, where the last two terms are a phrase that exists in - * the index. For example, if the input is 'washington medic', the suggested terms could include 'washington - * medicaid' and 'washington medical'. + * Completes the last term in a query with two or more terms, where the last two + * terms are a phrase that exists in the index. For example, if the input is 'washington medic', the suggested terms + * could include 'washington medicaid' and 'washington medical'. */ - ONE_TERM_WITH_CONTEXT("oneTermWithContext"); + @Generated + public static final AutocompleteMode ONE_TERM_WITH_CONTEXT = fromString("oneTermWithContext"); /** - * The actual serialized value for a AutocompleteMode instance. + * Creates a new instance of AutocompleteMode value. + * + * @deprecated Use the {@link #fromString(String)} factory method. */ - private final String value; - - AutocompleteMode(String value) { - this.value = value; + @Generated + @Deprecated + public AutocompleteMode() { } /** - * Parses a serialized value to a AutocompleteMode instance. + * Creates or finds a AutocompleteMode from its string representation. * - * @param value the serialized value to parse. - * @return the parsed AutocompleteMode object, or null if unable to parse. + * @param name a name to look for. + * @return the corresponding AutocompleteMode. */ - public static AutocompleteMode fromString(String value) { - if (value == null) { - return null; - } - AutocompleteMode[] items = AutocompleteMode.values(); - for (AutocompleteMode item : items) { - if (item.toString().equalsIgnoreCase(value)) { - return item; - } - } - return null; + @Generated + public static AutocompleteMode fromString(String name) { + return fromString(name, AutocompleteMode.class); } /** - * {@inheritDoc} + * Gets known AutocompleteMode values. + * + * @return known AutocompleteMode values. */ - @Override - public String toString() { - return this.value; + @Generated + public static Collection values() { + return values(AutocompleteMode.class); } } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/AutocompleteOptions.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/AutocompleteOptions.java deleted file mode 100644 index beda9e5280e6..000000000000 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/AutocompleteOptions.java +++ /dev/null @@ -1,328 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. -package com.azure.search.documents.models; - -import com.azure.core.annotation.Fluent; -import com.azure.json.JsonReader; -import com.azure.json.JsonSerializable; -import com.azure.json.JsonToken; -import com.azure.json.JsonWriter; -import java.io.IOException; -import java.util.Arrays; -import java.util.List; - -/** - * Parameter group. - */ -@Fluent -public final class AutocompleteOptions implements JsonSerializable { - - /* - * 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. - */ - private AutocompleteMode autocompleteMode; - - /* - * An OData expression that filters the documents used to produce completed terms for the Autocomplete result. - */ - private String filter; - - /* - * 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. - */ - private Boolean useFuzzyMatching; - - /* - * A string tag that is appended to hit highlights. Must be set with highlightPreTag. If omitted, hit highlighting - * is disabled. - */ - private String highlightPostTag; - - /* - * A string tag that is prepended to hit highlights. Must be set with highlightPostTag. If omitted, hit highlighting - * is disabled. - */ - private String highlightPreTag; - - /* - * 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. - */ - private Double minimumCoverage; - - /* - * The list of field names to consider when querying for auto-completed terms. Target fields must be included in the - * specified suggester. - */ - private List searchFields; - - /* - * The number of auto-completed terms to retrieve. This must be a value between 1 and 100. The default is 5. - */ - private Integer top; - - /** - * Creates an instance of AutocompleteOptions class. - */ - public AutocompleteOptions() { - } - - /** - * Get the autocompleteMode property: 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. - * - * @return the autocompleteMode value. - */ - public AutocompleteMode getAutocompleteMode() { - return this.autocompleteMode; - } - - /** - * Set the autocompleteMode property: 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. - * - * @param autocompleteMode the autocompleteMode value to set. - * @return the AutocompleteOptions object itself. - */ - public AutocompleteOptions setAutocompleteMode(AutocompleteMode autocompleteMode) { - this.autocompleteMode = autocompleteMode; - return this; - } - - /** - * Get the filter property: An OData expression that filters the documents used to produce completed terms for the - * Autocomplete result. - * - * @return the filter value. - */ - public String getFilter() { - return this.filter; - } - - /** - * Set the filter property: An OData expression that filters the documents used to produce completed terms for the - * Autocomplete result. - * - * @param filter the filter value to set. - * @return the AutocompleteOptions object itself. - */ - public AutocompleteOptions setFilter(String filter) { - this.filter = filter; - return this; - } - - /** - * Get the useFuzzyMatching property: 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. - * - * @return the useFuzzyMatching value. - */ - public Boolean useFuzzyMatching() { - return this.useFuzzyMatching; - } - - /** - * Set the useFuzzyMatching property: 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. - * - * @param useFuzzyMatching the useFuzzyMatching value to set. - * @return the AutocompleteOptions object itself. - */ - public AutocompleteOptions setUseFuzzyMatching(Boolean useFuzzyMatching) { - this.useFuzzyMatching = useFuzzyMatching; - return this; - } - - /** - * Get the highlightPostTag property: A string tag that is appended to hit highlights. Must be set with - * highlightPreTag. If omitted, hit highlighting is disabled. - * - * @return the highlightPostTag value. - */ - public String getHighlightPostTag() { - return this.highlightPostTag; - } - - /** - * Set the highlightPostTag property: A string tag that is appended to hit highlights. Must be set with - * highlightPreTag. If omitted, hit highlighting is disabled. - * - * @param highlightPostTag the highlightPostTag value to set. - * @return the AutocompleteOptions object itself. - */ - public AutocompleteOptions setHighlightPostTag(String highlightPostTag) { - this.highlightPostTag = highlightPostTag; - return this; - } - - /** - * Get the highlightPreTag property: A string tag that is prepended to hit highlights. Must be set with - * highlightPostTag. If omitted, hit highlighting is disabled. - * - * @return the highlightPreTag value. - */ - public String getHighlightPreTag() { - return this.highlightPreTag; - } - - /** - * Set the highlightPreTag property: A string tag that is prepended to hit highlights. Must be set with - * highlightPostTag. If omitted, hit highlighting is disabled. - * - * @param highlightPreTag the highlightPreTag value to set. - * @return the AutocompleteOptions object itself. - */ - public AutocompleteOptions setHighlightPreTag(String highlightPreTag) { - this.highlightPreTag = highlightPreTag; - return this; - } - - /** - * Get the minimumCoverage property: 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. - * - * @return the minimumCoverage value. - */ - public Double getMinimumCoverage() { - return this.minimumCoverage; - } - - /** - * Set the minimumCoverage property: 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. - * - * @param minimumCoverage the minimumCoverage value to set. - * @return the AutocompleteOptions object itself. - */ - public AutocompleteOptions setMinimumCoverage(Double minimumCoverage) { - this.minimumCoverage = minimumCoverage; - return this; - } - - /** - * Get the searchFields property: The list of field names to consider when querying for auto-completed terms. Target - * fields must be included in the specified suggester. - * - * @return the searchFields value. - */ - public List getSearchFields() { - return this.searchFields; - } - - /** - * Set the searchFields property: The list of field names to consider when querying for auto-completed terms. Target - * fields must be included in the specified suggester. - * - * @param searchFields the searchFields value to set. - * @return the AutocompleteOptions object itself. - */ - public AutocompleteOptions setSearchFields(List searchFields) { - this.searchFields = searchFields; - return this; - } - - /** - * Get the top property: The number of auto-completed terms to retrieve. This must be a value between 1 and 100. The - * default is 5. - * - * @return the top value. - */ - public Integer getTop() { - return this.top; - } - - /** - * Set the top property: The number of auto-completed terms to retrieve. This must be a value between 1 and 100. The - * default is 5. - * - * @param top the top value to set. - * @return the AutocompleteOptions object itself. - */ - public AutocompleteOptions setTop(Integer top) { - this.top = top; - return this; - } - - /** - * Set the searchFields property: The list of field names to consider when querying for auto-completed terms. Target - * fields must be included in the specified suggester. - * - * @param searchFields the searchFields value to set. - * @return the AutocompleteOptions object itself. - */ - public AutocompleteOptions setSearchFields(String... searchFields) { - this.searchFields = (searchFields == null) ? null : Arrays.asList(searchFields); - return this; - } - - /** - * {@inheritDoc} - */ - @Override - public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { - jsonWriter.writeStartObject(); - jsonWriter.writeStringField("autocompleteMode", - this.autocompleteMode == null ? null : this.autocompleteMode.toString()); - jsonWriter.writeStringField("$filter", this.filter); - jsonWriter.writeBooleanField("UseFuzzyMatching", this.useFuzzyMatching); - jsonWriter.writeStringField("highlightPostTag", this.highlightPostTag); - jsonWriter.writeStringField("highlightPreTag", this.highlightPreTag); - jsonWriter.writeNumberField("minimumCoverage", this.minimumCoverage); - jsonWriter.writeArrayField("searchFields", this.searchFields, (writer, element) -> writer.writeString(element)); - jsonWriter.writeNumberField("$top", this.top); - return jsonWriter.writeEndObject(); - } - - /** - * Reads an instance of AutocompleteOptions from the JsonReader. - * - * @param jsonReader The JsonReader being read. - * @return An instance of AutocompleteOptions if the JsonReader was pointing to an instance of it, or null if it was - * pointing to JSON null. - * @throws IOException If an error occurs while reading the AutocompleteOptions. - */ - public static AutocompleteOptions fromJson(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - AutocompleteOptions deserializedAutocompleteOptions = new AutocompleteOptions(); - while (reader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = reader.getFieldName(); - reader.nextToken(); - if ("autocompleteMode".equals(fieldName)) { - deserializedAutocompleteOptions.autocompleteMode = AutocompleteMode.fromString(reader.getString()); - } else if ("$filter".equals(fieldName)) { - deserializedAutocompleteOptions.filter = reader.getString(); - } else if ("UseFuzzyMatching".equals(fieldName)) { - deserializedAutocompleteOptions.useFuzzyMatching = reader.getNullable(JsonReader::getBoolean); - } else if ("highlightPostTag".equals(fieldName)) { - deserializedAutocompleteOptions.highlightPostTag = reader.getString(); - } else if ("highlightPreTag".equals(fieldName)) { - deserializedAutocompleteOptions.highlightPreTag = reader.getString(); - } else if ("minimumCoverage".equals(fieldName)) { - deserializedAutocompleteOptions.minimumCoverage = reader.getNullable(JsonReader::getDouble); - } else if ("searchFields".equals(fieldName)) { - List searchFields = reader.readArray(reader1 -> reader1.getString()); - deserializedAutocompleteOptions.searchFields = searchFields; - } else if ("$top".equals(fieldName)) { - deserializedAutocompleteOptions.top = reader.getNullable(JsonReader::getInt); - } else { - reader.skipChildren(); - } - } - return deserializedAutocompleteOptions; - }); - } -} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/implementation/models/AutocompleteRequest.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/AutocompleteRequest.java similarity index 73% rename from sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/implementation/models/AutocompleteRequest.java rename to sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/AutocompleteRequest.java index 7776146b811c..1cb41f36fe63 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/implementation/models/AutocompleteRequest.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/AutocompleteRequest.java @@ -1,20 +1,16 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) TypeSpec Code Generator. -package com.azure.search.documents.implementation.models; +package com.azure.search.documents.models; import com.azure.core.annotation.Fluent; +import com.azure.core.annotation.Generated; import com.azure.json.JsonReader; import com.azure.json.JsonSerializable; import com.azure.json.JsonToken; import com.azure.json.JsonWriter; -import com.azure.search.documents.models.AutocompleteMode; import java.io.IOException; -import java.util.ArrayList; -import java.util.List; /** * Parameters for fuzzy matching, and other autocomplete query behaviors. @@ -24,60 +20,77 @@ public final class AutocompleteRequest implements JsonSerializable { - boolean searchTextFound = false; String searchText = null; - boolean suggesterNameFound = false; String suggesterName = null; AutocompleteMode autocompleteMode = null; String filter = null; @@ -341,10 +381,8 @@ public static AutocompleteRequest fromJson(JsonReader jsonReader) throws IOExcep if ("search".equals(fieldName)) { searchText = reader.getString(); - searchTextFound = true; } else if ("suggesterName".equals(fieldName)) { suggesterName = reader.getString(); - suggesterNameFound = true; } else if ("autocompleteMode".equals(fieldName)) { autocompleteMode = AutocompleteMode.fromString(reader.getString()); } else if ("filter".equals(fieldName)) { @@ -365,30 +403,17 @@ public static AutocompleteRequest fromJson(JsonReader jsonReader) throws IOExcep reader.skipChildren(); } } - if (searchTextFound && suggesterNameFound) { - AutocompleteRequest deserializedAutocompleteRequest - = new AutocompleteRequest(searchText, suggesterName); - deserializedAutocompleteRequest.autocompleteMode = autocompleteMode; - deserializedAutocompleteRequest.filter = filter; - deserializedAutocompleteRequest.useFuzzyMatching = useFuzzyMatching; - deserializedAutocompleteRequest.highlightPostTag = highlightPostTag; - deserializedAutocompleteRequest.highlightPreTag = highlightPreTag; - deserializedAutocompleteRequest.minimumCoverage = minimumCoverage; - deserializedAutocompleteRequest.searchFields = searchFields; - deserializedAutocompleteRequest.top = top; - - return deserializedAutocompleteRequest; - } - List missingProperties = new ArrayList<>(); - if (!searchTextFound) { - missingProperties.add("search"); - } - if (!suggesterNameFound) { - missingProperties.add("suggesterName"); - } - - throw new IllegalStateException( - "Missing required property/properties: " + String.join(", ", missingProperties)); + AutocompleteRequest deserializedAutocompleteRequest = new AutocompleteRequest(searchText, suggesterName); + deserializedAutocompleteRequest.autocompleteMode = autocompleteMode; + deserializedAutocompleteRequest.filter = filter; + deserializedAutocompleteRequest.useFuzzyMatching = useFuzzyMatching; + deserializedAutocompleteRequest.highlightPostTag = highlightPostTag; + deserializedAutocompleteRequest.highlightPreTag = highlightPreTag; + deserializedAutocompleteRequest.minimumCoverage = minimumCoverage; + deserializedAutocompleteRequest.searchFields = searchFields; + deserializedAutocompleteRequest.top = top; + + return deserializedAutocompleteRequest; }); } } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/AutocompleteResult.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/AutocompleteResult.java index f12bb08d5a02..f209c19e98df 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/AutocompleteResult.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/AutocompleteResult.java @@ -1,11 +1,10 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.search.documents.models; +import com.azure.core.annotation.Generated; import com.azure.core.annotation.Immutable; import com.azure.json.JsonReader; import com.azure.json.JsonSerializable; @@ -20,14 +19,17 @@ @Immutable public final class AutocompleteResult implements JsonSerializable { /* - * 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. + * 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. */ + @Generated private Double coverage; /* * The list of returned Autocompleted items. */ + @Generated private final List results; /** @@ -35,16 +37,19 @@ public final class AutocompleteResult implements JsonSerializable results) { + @Generated + private AutocompleteResult(List results) { this.results = results; } /** - * Get the coverage property: 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. + * Get the coverage property: 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. * * @return the coverage value. */ + @Generated public Double getCoverage() { return this.coverage; } @@ -54,6 +59,7 @@ public Double getCoverage() { * * @return the results value. */ + @Generated public List getResults() { return this.results; } @@ -61,9 +67,12 @@ public List getResults() { /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); + jsonWriter.writeArrayField("value", this.results, (writer, element) -> writer.writeJson(element)); + jsonWriter.writeNumberField("@search.coverage", this.coverage); return jsonWriter.writeEndObject(); } @@ -76,9 +85,9 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { * @throws IllegalStateException If the deserialized JSON object was missing any required properties. * @throws IOException If an error occurs while reading the AutocompleteResult. */ + @Generated public static AutocompleteResult fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { - boolean resultsFound = false; List results = null; Double coverage = null; while (reader.nextToken() != JsonToken.END_OBJECT) { @@ -87,20 +96,16 @@ public static AutocompleteResult fromJson(JsonReader jsonReader) throws IOExcept if ("value".equals(fieldName)) { results = reader.readArray(reader1 -> AutocompleteItem.fromJson(reader1)); - resultsFound = true; } else if ("@search.coverage".equals(fieldName)) { coverage = reader.getNullable(JsonReader::getDouble); } else { reader.skipChildren(); } } - if (resultsFound) { - AutocompleteResult deserializedAutocompleteResult = new AutocompleteResult(results); - deserializedAutocompleteResult.coverage = coverage; + AutocompleteResult deserializedAutocompleteResult = new AutocompleteResult(results); + deserializedAutocompleteResult.coverage = coverage; - return deserializedAutocompleteResult; - } - throw new IllegalStateException("Missing required property: value"); + return deserializedAutocompleteResult; }); } } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/implementation/models/AzureActiveDirectoryApplicationCredentials.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/AzureActiveDirectoryApplicationCredentials.java similarity index 73% rename from sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/implementation/models/AzureActiveDirectoryApplicationCredentials.java rename to sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/AzureActiveDirectoryApplicationCredentials.java index e827d24f3167..75f58913a798 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/implementation/models/AzureActiveDirectoryApplicationCredentials.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/AzureActiveDirectoryApplicationCredentials.java @@ -1,12 +1,11 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) TypeSpec Code Generator. -package com.azure.search.documents.indexes.implementation.models; +package com.azure.search.documents.models; import com.azure.core.annotation.Fluent; +import com.azure.core.annotation.Generated; import com.azure.json.JsonReader; import com.azure.json.JsonSerializable; import com.azure.json.JsonToken; @@ -14,59 +13,56 @@ import java.io.IOException; /** - * Credentials of a registered application created for your search service, used for authenticated access to the - * encryption keys stored in Azure Key Vault. + * Credentials of a registered application created for your search service, used + * for authenticated access to the encryption keys stored in Azure Key Vault. */ @Fluent public final class AzureActiveDirectoryApplicationCredentials implements JsonSerializable { /* - * 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 + * 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. */ - private String applicationId; + @Generated + private final String applicationId; /* * The authentication key of the specified AAD application. */ + @Generated private String applicationSecret; /** * Creates an instance of AzureActiveDirectoryApplicationCredentials class. + * + * @param applicationId the applicationId value to set. */ - public AzureActiveDirectoryApplicationCredentials() { + @Generated + public AzureActiveDirectoryApplicationCredentials(String applicationId) { + this.applicationId = applicationId; } /** * Get the applicationId property: 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. + * 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. * * @return the applicationId value. */ + @Generated public String getApplicationId() { return this.applicationId; } - /** - * Set the applicationId property: 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. - * - * @param applicationId the applicationId value to set. - * @return the AzureActiveDirectoryApplicationCredentials object itself. - */ - public AzureActiveDirectoryApplicationCredentials setApplicationId(String applicationId) { - this.applicationId = applicationId; - return this; - } - /** * Get the applicationSecret property: The authentication key of the specified AAD application. * * @return the applicationSecret value. */ + @Generated public String getApplicationSecret() { return this.applicationSecret; } @@ -77,6 +73,7 @@ public String getApplicationSecret() { * @param applicationSecret the applicationSecret value to set. * @return the AzureActiveDirectoryApplicationCredentials object itself. */ + @Generated public AzureActiveDirectoryApplicationCredentials setApplicationSecret(String applicationSecret) { this.applicationSecret = applicationSecret; return this; @@ -85,6 +82,7 @@ public AzureActiveDirectoryApplicationCredentials setApplicationSecret(String ap /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); @@ -99,24 +97,29 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { * @param jsonReader The JsonReader being read. * @return An instance of AzureActiveDirectoryApplicationCredentials if the JsonReader was pointing to an instance * of it, or null if it was pointing to JSON null. + * @throws IllegalStateException If the deserialized JSON object was missing any required properties. * @throws IOException If an error occurs while reading the AzureActiveDirectoryApplicationCredentials. */ + @Generated public static AzureActiveDirectoryApplicationCredentials fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { - AzureActiveDirectoryApplicationCredentials deserializedAzureActiveDirectoryApplicationCredentials - = new AzureActiveDirectoryApplicationCredentials(); + String applicationId = null; + String applicationSecret = null; while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); if ("applicationId".equals(fieldName)) { - deserializedAzureActiveDirectoryApplicationCredentials.applicationId = reader.getString(); + applicationId = reader.getString(); } else if ("applicationSecret".equals(fieldName)) { - deserializedAzureActiveDirectoryApplicationCredentials.applicationSecret = reader.getString(); + applicationSecret = reader.getString(); } else { reader.skipChildren(); } } + AzureActiveDirectoryApplicationCredentials deserializedAzureActiveDirectoryApplicationCredentials + = new AzureActiveDirectoryApplicationCredentials(applicationId); + deserializedAzureActiveDirectoryApplicationCredentials.applicationSecret = applicationSecret; return deserializedAzureActiveDirectoryApplicationCredentials; }); diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/AzureMachineLearningParameters.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/AzureMachineLearningParameters.java similarity index 75% rename from sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/AzureMachineLearningParameters.java rename to sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/AzureMachineLearningParameters.java index f467cebea260..e8783d7d029a 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/AzureMachineLearningParameters.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/AzureMachineLearningParameters.java @@ -1,12 +1,11 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) TypeSpec Code Generator. -package com.azure.search.documents.indexes.models; +package com.azure.search.documents.models; import com.azure.core.annotation.Fluent; +import com.azure.core.annotation.Generated; import com.azure.core.util.CoreUtils; import com.azure.json.JsonReader; import com.azure.json.JsonSerializable; @@ -21,54 +20,66 @@ @Fluent public final class AzureMachineLearningParameters implements JsonSerializable { /* - * (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 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. */ + @Generated private final String scoringUri; /* * (Required for key authentication) The key for the AML service. */ + @Generated private String authenticationKey; /* - * (Required for token authentication). The Azure Resource Manager resource ID of the AML service. It should be in - * the format + * (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}. */ + @Generated private String resourceId; /* - * (Optional) When specified, indicates the timeout for the http client making the API call. + * (Optional) When specified, indicates the timeout for the http client making the + * API call. */ + @Generated private Duration timeout; /* * (Optional for token authentication). The region the AML service is deployed in. */ + @Generated private String region; /* - * The name of the embedding model from the Azure AI Studio Catalog that is deployed at the provided endpoint. + * The name of the embedding model from the Azure AI Foundry Catalog that is + * deployed at the provided endpoint. */ - private AIStudioModelCatalogName modelName; + @Generated + private AIFoundryModelCatalogName modelName; /** * Creates an instance of AzureMachineLearningParameters class. * * @param scoringUri the scoringUri value to set. */ + @Generated public AzureMachineLearningParameters(String scoringUri) { this.scoringUri = scoringUri; } /** - * Get the scoringUri property: (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. + * Get the scoringUri property: (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. * * @return the scoringUri value. */ + @Generated public String getScoringUri() { return this.scoringUri; } @@ -78,6 +89,7 @@ public String getScoringUri() { * * @return the authenticationKey value. */ + @Generated public String getAuthenticationKey() { return this.authenticationKey; } @@ -88,52 +100,57 @@ public String getAuthenticationKey() { * @param authenticationKey the authenticationKey value to set. * @return the AzureMachineLearningParameters object itself. */ + @Generated public AzureMachineLearningParameters setAuthenticationKey(String authenticationKey) { this.authenticationKey = authenticationKey; return this; } /** - * Get the resourceId property: (Required for token authentication). The Azure Resource Manager resource ID of the - * AML service. It should be in the format + * Get the resourceId property: (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}. * * @return the resourceId value. */ + @Generated public String getResourceId() { return this.resourceId; } /** - * Set the resourceId property: (Required for token authentication). The Azure Resource Manager resource ID of the - * AML service. It should be in the format + * Set the resourceId property: (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}. * * @param resourceId the resourceId value to set. * @return the AzureMachineLearningParameters object itself. */ + @Generated public AzureMachineLearningParameters setResourceId(String resourceId) { this.resourceId = resourceId; return this; } /** - * Get the timeout property: (Optional) When specified, indicates the timeout for the http client making the API - * call. + * Get the timeout property: (Optional) When specified, indicates the timeout for the http client making the + * API call. * * @return the timeout value. */ + @Generated public Duration getTimeout() { return this.timeout; } /** - * Set the timeout property: (Optional) When specified, indicates the timeout for the http client making the API - * call. + * Set the timeout property: (Optional) When specified, indicates the timeout for the http client making the + * API call. * * @param timeout the timeout value to set. * @return the AzureMachineLearningParameters object itself. */ + @Generated public AzureMachineLearningParameters setTimeout(Duration timeout) { this.timeout = timeout; return this; @@ -144,6 +161,7 @@ public AzureMachineLearningParameters setTimeout(Duration timeout) { * * @return the region value. */ + @Generated public String getRegion() { return this.region; } @@ -154,29 +172,32 @@ public String getRegion() { * @param region the region value to set. * @return the AzureMachineLearningParameters object itself. */ + @Generated public AzureMachineLearningParameters setRegion(String region) { this.region = region; return this; } /** - * Get the modelName property: The name of the embedding model from the Azure AI Studio Catalog that is deployed at - * the provided endpoint. + * Get the modelName property: The name of the embedding model from the Azure AI Foundry Catalog that is + * deployed at the provided endpoint. * * @return the modelName value. */ - public AIStudioModelCatalogName getModelName() { + @Generated + public AIFoundryModelCatalogName getModelName() { return this.modelName; } /** - * Set the modelName property: The name of the embedding model from the Azure AI Studio Catalog that is deployed at - * the provided endpoint. + * Set the modelName property: The name of the embedding model from the Azure AI Foundry Catalog that is + * deployed at the provided endpoint. * * @param modelName the modelName value to set. * @return the AzureMachineLearningParameters object itself. */ - public AzureMachineLearningParameters setModelName(AIStudioModelCatalogName modelName) { + @Generated + public AzureMachineLearningParameters setModelName(AIFoundryModelCatalogName modelName) { this.modelName = modelName; return this; } @@ -184,6 +205,7 @@ public AzureMachineLearningParameters setModelName(AIStudioModelCatalogName mode /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); @@ -205,22 +227,21 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { * @throws IllegalStateException If the deserialized JSON object was missing any required properties. * @throws IOException If an error occurs while reading the AzureMachineLearningParameters. */ + @Generated public static AzureMachineLearningParameters fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { - boolean scoringUriFound = false; String scoringUri = null; String authenticationKey = null; String resourceId = null; Duration timeout = null; String region = null; - AIStudioModelCatalogName modelName = null; + AIFoundryModelCatalogName modelName = null; while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); if ("uri".equals(fieldName)) { scoringUri = reader.getString(); - scoringUriFound = true; } else if ("key".equals(fieldName)) { authenticationKey = reader.getString(); } else if ("resourceId".equals(fieldName)) { @@ -230,23 +251,20 @@ public static AzureMachineLearningParameters fromJson(JsonReader jsonReader) thr } else if ("region".equals(fieldName)) { region = reader.getString(); } else if ("modelName".equals(fieldName)) { - modelName = AIStudioModelCatalogName.fromString(reader.getString()); + modelName = AIFoundryModelCatalogName.fromString(reader.getString()); } else { reader.skipChildren(); } } - if (scoringUriFound) { - AzureMachineLearningParameters deserializedAzureMachineLearningParameters - = new AzureMachineLearningParameters(scoringUri); - deserializedAzureMachineLearningParameters.authenticationKey = authenticationKey; - deserializedAzureMachineLearningParameters.resourceId = resourceId; - deserializedAzureMachineLearningParameters.timeout = timeout; - deserializedAzureMachineLearningParameters.region = region; - deserializedAzureMachineLearningParameters.modelName = modelName; - - return deserializedAzureMachineLearningParameters; - } - throw new IllegalStateException("Missing required property: uri"); + AzureMachineLearningParameters deserializedAzureMachineLearningParameters + = new AzureMachineLearningParameters(scoringUri); + deserializedAzureMachineLearningParameters.authenticationKey = authenticationKey; + deserializedAzureMachineLearningParameters.resourceId = resourceId; + deserializedAzureMachineLearningParameters.timeout = timeout; + deserializedAzureMachineLearningParameters.region = region; + deserializedAzureMachineLearningParameters.modelName = modelName; + + return deserializedAzureMachineLearningParameters; }); } } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/AzureMachineLearningSkill.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/AzureMachineLearningSkill.java similarity index 71% rename from sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/AzureMachineLearningSkill.java rename to sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/AzureMachineLearningSkill.java index a2ed91f89a9c..1f8ffb451c3a 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/AzureMachineLearningSkill.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/AzureMachineLearningSkill.java @@ -1,68 +1,77 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) TypeSpec Code Generator. -package com.azure.search.documents.indexes.models; +package com.azure.search.documents.models; import com.azure.core.annotation.Fluent; +import com.azure.core.annotation.Generated; import com.azure.core.util.CoreUtils; import com.azure.json.JsonReader; import com.azure.json.JsonToken; import com.azure.json.JsonWriter; import java.io.IOException; import java.time.Duration; -import java.util.ArrayList; import java.util.List; /** - * 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. + * 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. */ @Fluent public final class AzureMachineLearningSkill extends SearchIndexerSkill { /* - * A URI fragment specifying the type of skill. + * The discriminator for derived types. */ + @Generated private String odataType = "#Microsoft.Skills.Custom.AmlSkill"; /* - * (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 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. */ + @Generated private String scoringUri; /* * (Required for key authentication) The key for the AML service. */ + @Generated private String authenticationKey; /* - * (Required for token authentication). The Azure Resource Manager resource ID of the AML service. It should be in - * the format + * (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}. */ + @Generated private String resourceId; /* - * (Optional) When specified, indicates the timeout for the http client making the API call. + * (Optional) When specified, indicates the timeout for the http client making the + * API call. */ + @Generated private Duration timeout; /* * (Optional for token authentication). The region the AML service is deployed in. */ + @Generated private String region; /* - * (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. + * (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. */ + @Generated private Integer degreeOfParallelism; /** @@ -71,37 +80,43 @@ public final class AzureMachineLearningSkill extends SearchIndexerSkill { * @param inputs the inputs value to set. * @param outputs the outputs value to set. */ + @Generated public AzureMachineLearningSkill(List inputs, List outputs) { super(inputs, outputs); } /** - * Get the odataType property: A URI fragment specifying the type of skill. + * Get the odataType property: The discriminator for derived types. * * @return the odataType value. */ + @Generated @Override public String getOdataType() { return this.odataType; } /** - * Get the scoringUri property: (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. + * Get the scoringUri property: (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. * * @return the scoringUri value. */ + @Generated public String getScoringUri() { return this.scoringUri; } /** - * Set the scoringUri property: (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. + * Set the scoringUri property: (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. * * @param scoringUri the scoringUri value to set. * @return the AzureMachineLearningSkill object itself. */ + @Generated public AzureMachineLearningSkill setScoringUri(String scoringUri) { this.scoringUri = scoringUri; return this; @@ -112,6 +127,7 @@ public AzureMachineLearningSkill setScoringUri(String scoringUri) { * * @return the authenticationKey value. */ + @Generated public String getAuthenticationKey() { return this.authenticationKey; } @@ -122,52 +138,57 @@ public String getAuthenticationKey() { * @param authenticationKey the authenticationKey value to set. * @return the AzureMachineLearningSkill object itself. */ + @Generated public AzureMachineLearningSkill setAuthenticationKey(String authenticationKey) { this.authenticationKey = authenticationKey; return this; } /** - * Get the resourceId property: (Required for token authentication). The Azure Resource Manager resource ID of the - * AML service. It should be in the format + * Get the resourceId property: (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}. * * @return the resourceId value. */ + @Generated public String getResourceId() { return this.resourceId; } /** - * Set the resourceId property: (Required for token authentication). The Azure Resource Manager resource ID of the - * AML service. It should be in the format + * Set the resourceId property: (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}. * * @param resourceId the resourceId value to set. * @return the AzureMachineLearningSkill object itself. */ + @Generated public AzureMachineLearningSkill setResourceId(String resourceId) { this.resourceId = resourceId; return this; } /** - * Get the timeout property: (Optional) When specified, indicates the timeout for the http client making the API - * call. + * Get the timeout property: (Optional) When specified, indicates the timeout for the http client making the + * API call. * * @return the timeout value. */ + @Generated public Duration getTimeout() { return this.timeout; } /** - * Set the timeout property: (Optional) When specified, indicates the timeout for the http client making the API - * call. + * Set the timeout property: (Optional) When specified, indicates the timeout for the http client making the + * API call. * * @param timeout the timeout value to set. * @return the AzureMachineLearningSkill object itself. */ + @Generated public AzureMachineLearningSkill setTimeout(Duration timeout) { this.timeout = timeout; return this; @@ -178,6 +199,7 @@ public AzureMachineLearningSkill setTimeout(Duration timeout) { * * @return the region value. */ + @Generated public String getRegion() { return this.region; } @@ -188,6 +210,7 @@ public String getRegion() { * @param region the region value to set. * @return the AzureMachineLearningSkill object itself. */ + @Generated public AzureMachineLearningSkill setRegion(String region) { this.region = region; return this; @@ -195,27 +218,33 @@ public AzureMachineLearningSkill setRegion(String region) { /** * Get the degreeOfParallelism property: (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. + * 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. * * @return the degreeOfParallelism value. */ + @Generated public Integer getDegreeOfParallelism() { return this.degreeOfParallelism; } /** * Set the degreeOfParallelism property: (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. + * 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. * * @param degreeOfParallelism the degreeOfParallelism value to set. * @return the AzureMachineLearningSkill object itself. */ + @Generated public AzureMachineLearningSkill setDegreeOfParallelism(Integer degreeOfParallelism) { this.degreeOfParallelism = degreeOfParallelism; return this; @@ -224,6 +253,7 @@ public AzureMachineLearningSkill setDegreeOfParallelism(Integer degreeOfParallel /** * {@inheritDoc} */ + @Generated @Override public AzureMachineLearningSkill setName(String name) { super.setName(name); @@ -233,6 +263,7 @@ public AzureMachineLearningSkill setName(String name) { /** * {@inheritDoc} */ + @Generated @Override public AzureMachineLearningSkill setDescription(String description) { super.setDescription(description); @@ -242,6 +273,7 @@ public AzureMachineLearningSkill setDescription(String description) { /** * {@inheritDoc} */ + @Generated @Override public AzureMachineLearningSkill setContext(String context) { super.setContext(context); @@ -251,6 +283,7 @@ public AzureMachineLearningSkill setContext(String context) { /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); @@ -278,11 +311,10 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { * @throws IllegalStateException If the deserialized JSON object was missing any required properties. * @throws IOException If an error occurs while reading the AzureMachineLearningSkill. */ + @Generated public static AzureMachineLearningSkill fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { - boolean inputsFound = false; List inputs = null; - boolean outputsFound = false; List outputs = null; String name = null; String description = null; @@ -300,10 +332,8 @@ public static AzureMachineLearningSkill fromJson(JsonReader jsonReader) throws I if ("inputs".equals(fieldName)) { inputs = reader.readArray(reader1 -> InputFieldMappingEntry.fromJson(reader1)); - inputsFound = true; } else if ("outputs".equals(fieldName)) { outputs = reader.readArray(reader1 -> OutputFieldMappingEntry.fromJson(reader1)); - outputsFound = true; } else if ("name".equals(fieldName)) { name = reader.getString(); } else if ("description".equals(fieldName)) { @@ -328,32 +358,20 @@ public static AzureMachineLearningSkill fromJson(JsonReader jsonReader) throws I reader.skipChildren(); } } - if (inputsFound && outputsFound) { - AzureMachineLearningSkill deserializedAzureMachineLearningSkill - = new AzureMachineLearningSkill(inputs, outputs); - deserializedAzureMachineLearningSkill.setName(name); - deserializedAzureMachineLearningSkill.setDescription(description); - deserializedAzureMachineLearningSkill.setContext(context); - deserializedAzureMachineLearningSkill.odataType = odataType; - deserializedAzureMachineLearningSkill.scoringUri = scoringUri; - deserializedAzureMachineLearningSkill.authenticationKey = authenticationKey; - deserializedAzureMachineLearningSkill.resourceId = resourceId; - deserializedAzureMachineLearningSkill.timeout = timeout; - deserializedAzureMachineLearningSkill.region = region; - deserializedAzureMachineLearningSkill.degreeOfParallelism = degreeOfParallelism; + AzureMachineLearningSkill deserializedAzureMachineLearningSkill + = new AzureMachineLearningSkill(inputs, outputs); + deserializedAzureMachineLearningSkill.setName(name); + deserializedAzureMachineLearningSkill.setDescription(description); + deserializedAzureMachineLearningSkill.setContext(context); + deserializedAzureMachineLearningSkill.odataType = odataType; + deserializedAzureMachineLearningSkill.scoringUri = scoringUri; + deserializedAzureMachineLearningSkill.authenticationKey = authenticationKey; + deserializedAzureMachineLearningSkill.resourceId = resourceId; + deserializedAzureMachineLearningSkill.timeout = timeout; + deserializedAzureMachineLearningSkill.region = region; + deserializedAzureMachineLearningSkill.degreeOfParallelism = degreeOfParallelism; - return deserializedAzureMachineLearningSkill; - } - List missingProperties = new ArrayList<>(); - if (!inputsFound) { - missingProperties.add("inputs"); - } - if (!outputsFound) { - missingProperties.add("outputs"); - } - - throw new IllegalStateException( - "Missing required property/properties: " + String.join(", ", missingProperties)); + return deserializedAzureMachineLearningSkill; }); } } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/AzureMachineLearningVectorizer.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/AzureMachineLearningVectorizer.java similarity index 76% rename from sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/AzureMachineLearningVectorizer.java rename to sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/AzureMachineLearningVectorizer.java index 37230623731f..a2d0d20f109f 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/AzureMachineLearningVectorizer.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/AzureMachineLearningVectorizer.java @@ -1,31 +1,32 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) TypeSpec Code Generator. -package com.azure.search.documents.indexes.models; +package com.azure.search.documents.models; import com.azure.core.annotation.Fluent; +import com.azure.core.annotation.Generated; import com.azure.json.JsonReader; import com.azure.json.JsonToken; import com.azure.json.JsonWriter; import java.io.IOException; /** - * Specifies an Azure Machine Learning endpoint deployed via the Azure AI Studio Model Catalog for generating the vector - * embedding of a query string. + * Specifies an Azure Machine Learning endpoint deployed via the Azure AI Foundry + * Model Catalog for generating the vector embedding of a query string. */ @Fluent public final class AzureMachineLearningVectorizer extends VectorSearchVectorizer { /* - * The name of the kind of vectorization method being configured for use with vector search. + * Type of VectorSearchVectorizer. */ + @Generated private VectorSearchVectorizerKind kind = VectorSearchVectorizerKind.AML; /* * Specifies the properties of the AML vectorizer. */ + @Generated private AzureMachineLearningParameters aMLParameters; /** @@ -33,15 +34,17 @@ public final class AzureMachineLearningVectorizer extends VectorSearchVectorizer * * @param vectorizerName the vectorizerName value to set. */ + @Generated public AzureMachineLearningVectorizer(String vectorizerName) { super(vectorizerName); } /** - * Get the kind property: The name of the kind of vectorization method being configured for use with vector search. + * Get the kind property: Type of VectorSearchVectorizer. * * @return the kind value. */ + @Generated @Override public VectorSearchVectorizerKind getKind() { return this.kind; @@ -52,6 +55,7 @@ public VectorSearchVectorizerKind getKind() { * * @return the aMLParameters value. */ + @Generated public AzureMachineLearningParameters getAMLParameters() { return this.aMLParameters; } @@ -62,6 +66,7 @@ public AzureMachineLearningParameters getAMLParameters() { * @param aMLParameters the aMLParameters value to set. * @return the AzureMachineLearningVectorizer object itself. */ + @Generated public AzureMachineLearningVectorizer setAMLParameters(AzureMachineLearningParameters aMLParameters) { this.aMLParameters = aMLParameters; return this; @@ -70,6 +75,7 @@ public AzureMachineLearningVectorizer setAMLParameters(AzureMachineLearningParam /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); @@ -88,9 +94,9 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { * @throws IllegalStateException If the deserialized JSON object was missing any required properties. * @throws IOException If an error occurs while reading the AzureMachineLearningVectorizer. */ + @Generated public static AzureMachineLearningVectorizer fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { - boolean vectorizerNameFound = false; String vectorizerName = null; VectorSearchVectorizerKind kind = VectorSearchVectorizerKind.AML; AzureMachineLearningParameters aMLParameters = null; @@ -100,7 +106,6 @@ public static AzureMachineLearningVectorizer fromJson(JsonReader jsonReader) thr if ("name".equals(fieldName)) { vectorizerName = reader.getString(); - vectorizerNameFound = true; } else if ("kind".equals(fieldName)) { kind = VectorSearchVectorizerKind.fromString(reader.getString()); } else if ("amlParameters".equals(fieldName)) { @@ -109,15 +114,12 @@ public static AzureMachineLearningVectorizer fromJson(JsonReader jsonReader) thr reader.skipChildren(); } } - if (vectorizerNameFound) { - AzureMachineLearningVectorizer deserializedAzureMachineLearningVectorizer - = new AzureMachineLearningVectorizer(vectorizerName); - deserializedAzureMachineLearningVectorizer.kind = kind; - deserializedAzureMachineLearningVectorizer.aMLParameters = aMLParameters; + AzureMachineLearningVectorizer deserializedAzureMachineLearningVectorizer + = new AzureMachineLearningVectorizer(vectorizerName); + deserializedAzureMachineLearningVectorizer.kind = kind; + deserializedAzureMachineLearningVectorizer.aMLParameters = aMLParameters; - return deserializedAzureMachineLearningVectorizer; - } - throw new IllegalStateException("Missing required property: name"); + return deserializedAzureMachineLearningVectorizer; }); } } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/AzureOpenAIEmbeddingSkill.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/AzureOpenAIEmbeddingSkill.java similarity index 80% rename from sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/AzureOpenAIEmbeddingSkill.java rename to sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/AzureOpenAIEmbeddingSkill.java index b4e20e60f799..7904ab3d589a 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/AzureOpenAIEmbeddingSkill.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/AzureOpenAIEmbeddingSkill.java @@ -1,107 +1,95 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) TypeSpec Code Generator. -package com.azure.search.documents.indexes.models; +package com.azure.search.documents.models; import com.azure.core.annotation.Fluent; +import com.azure.core.annotation.Generated; import com.azure.json.JsonReader; import com.azure.json.JsonToken; import com.azure.json.JsonWriter; import java.io.IOException; -import java.util.ArrayList; import java.util.List; /** - * Allows you to generate a vector embedding for a given text input using the Azure OpenAI resource. + * Allows you to generate a vector embedding for a given text input using the + * Azure OpenAI resource. */ @Fluent public final class AzureOpenAIEmbeddingSkill extends SearchIndexerSkill { /* - * A URI fragment specifying the type of skill. + * The discriminator for derived types. */ + @Generated private String odataType = "#Microsoft.Skills.Text.AzureOpenAIEmbeddingSkill"; - /* - * The number of dimensions the resulting output embeddings should have. Only supported in text-embedding-3 and - * later models. - */ - private Integer dimensions; - /* * The resource URI of the Azure OpenAI resource. */ + @Generated private String resourceUrl; /* * ID of the Azure OpenAI model deployment on the designated resource. */ + @Generated private String deploymentName; /* * API key of the designated Azure OpenAI resource. */ + @Generated private String apiKey; /* * The user-assigned managed identity used for outbound connections. */ + @Generated private SearchIndexerDataIdentity authIdentity; /* - * The name of the embedding model that is deployed at the provided deploymentId path. + * The name of the embedding model that is deployed at the provided deploymentId + * path. */ + @Generated private AzureOpenAIModelName modelName; + /* + * The number of dimensions the resulting output embeddings should have. Only + * supported in text-embedding-3 and later models. + */ + @Generated + private Integer dimensions; + /** * Creates an instance of AzureOpenAIEmbeddingSkill class. * * @param inputs the inputs value to set. * @param outputs the outputs value to set. */ + @Generated public AzureOpenAIEmbeddingSkill(List inputs, List outputs) { super(inputs, outputs); } /** - * Get the odataType property: A URI fragment specifying the type of skill. + * Get the odataType property: The discriminator for derived types. * * @return the odataType value. */ + @Generated @Override public String getOdataType() { return this.odataType; } - /** - * Get the dimensions property: The number of dimensions the resulting output embeddings should have. Only supported - * in text-embedding-3 and later models. - * - * @return the dimensions value. - */ - public Integer getDimensions() { - return this.dimensions; - } - - /** - * Set the dimensions property: The number of dimensions the resulting output embeddings should have. Only supported - * in text-embedding-3 and later models. - * - * @param dimensions the dimensions value to set. - * @return the AzureOpenAIEmbeddingSkill object itself. - */ - public AzureOpenAIEmbeddingSkill setDimensions(Integer dimensions) { - this.dimensions = dimensions; - return this; - } - /** * Get the resourceUrl property: The resource URI of the Azure OpenAI resource. * * @return the resourceUrl value. */ + @Generated public String getResourceUrl() { return this.resourceUrl; } @@ -112,6 +100,7 @@ public String getResourceUrl() { * @param resourceUrl the resourceUrl value to set. * @return the AzureOpenAIEmbeddingSkill object itself. */ + @Generated public AzureOpenAIEmbeddingSkill setResourceUrl(String resourceUrl) { this.resourceUrl = resourceUrl; return this; @@ -122,6 +111,7 @@ public AzureOpenAIEmbeddingSkill setResourceUrl(String resourceUrl) { * * @return the deploymentName value. */ + @Generated public String getDeploymentName() { return this.deploymentName; } @@ -132,6 +122,7 @@ public String getDeploymentName() { * @param deploymentName the deploymentName value to set. * @return the AzureOpenAIEmbeddingSkill object itself. */ + @Generated public AzureOpenAIEmbeddingSkill setDeploymentName(String deploymentName) { this.deploymentName = deploymentName; return this; @@ -142,6 +133,7 @@ public AzureOpenAIEmbeddingSkill setDeploymentName(String deploymentName) { * * @return the apiKey value. */ + @Generated public String getApiKey() { return this.apiKey; } @@ -152,6 +144,7 @@ public String getApiKey() { * @param apiKey the apiKey value to set. * @return the AzureOpenAIEmbeddingSkill object itself. */ + @Generated public AzureOpenAIEmbeddingSkill setApiKey(String apiKey) { this.apiKey = apiKey; return this; @@ -162,6 +155,7 @@ public AzureOpenAIEmbeddingSkill setApiKey(String apiKey) { * * @return the authIdentity value. */ + @Generated public SearchIndexerDataIdentity getAuthIdentity() { return this.authIdentity; } @@ -172,34 +166,64 @@ public SearchIndexerDataIdentity getAuthIdentity() { * @param authIdentity the authIdentity value to set. * @return the AzureOpenAIEmbeddingSkill object itself. */ + @Generated public AzureOpenAIEmbeddingSkill setAuthIdentity(SearchIndexerDataIdentity authIdentity) { this.authIdentity = authIdentity; return this; } /** - * Get the modelName property: The name of the embedding model that is deployed at the provided deploymentId path. + * Get the modelName property: The name of the embedding model that is deployed at the provided deploymentId + * path. * * @return the modelName value. */ + @Generated public AzureOpenAIModelName getModelName() { return this.modelName; } /** - * Set the modelName property: The name of the embedding model that is deployed at the provided deploymentId path. + * Set the modelName property: The name of the embedding model that is deployed at the provided deploymentId + * path. * * @param modelName the modelName value to set. * @return the AzureOpenAIEmbeddingSkill object itself. */ + @Generated public AzureOpenAIEmbeddingSkill setModelName(AzureOpenAIModelName modelName) { this.modelName = modelName; return this; } + /** + * Get the dimensions property: The number of dimensions the resulting output embeddings should have. Only + * supported in text-embedding-3 and later models. + * + * @return the dimensions value. + */ + @Generated + public Integer getDimensions() { + return this.dimensions; + } + + /** + * Set the dimensions property: The number of dimensions the resulting output embeddings should have. Only + * supported in text-embedding-3 and later models. + * + * @param dimensions the dimensions value to set. + * @return the AzureOpenAIEmbeddingSkill object itself. + */ + @Generated + public AzureOpenAIEmbeddingSkill setDimensions(Integer dimensions) { + this.dimensions = dimensions; + return this; + } + /** * {@inheritDoc} */ + @Generated @Override public AzureOpenAIEmbeddingSkill setName(String name) { super.setName(name); @@ -209,6 +233,7 @@ public AzureOpenAIEmbeddingSkill setName(String name) { /** * {@inheritDoc} */ + @Generated @Override public AzureOpenAIEmbeddingSkill setDescription(String description) { super.setDescription(description); @@ -218,6 +243,7 @@ public AzureOpenAIEmbeddingSkill setDescription(String description) { /** * {@inheritDoc} */ + @Generated @Override public AzureOpenAIEmbeddingSkill setContext(String context) { super.setContext(context); @@ -227,6 +253,7 @@ public AzureOpenAIEmbeddingSkill setContext(String context) { /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); @@ -236,12 +263,12 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStringField("description", getDescription()); jsonWriter.writeStringField("context", getContext()); jsonWriter.writeStringField("@odata.type", this.odataType); - jsonWriter.writeNumberField("dimensions", this.dimensions); jsonWriter.writeStringField("resourceUri", this.resourceUrl); jsonWriter.writeStringField("deploymentId", this.deploymentName); jsonWriter.writeStringField("apiKey", this.apiKey); jsonWriter.writeJsonField("authIdentity", this.authIdentity); jsonWriter.writeStringField("modelName", this.modelName == null ? null : this.modelName.toString()); + jsonWriter.writeNumberField("dimensions", this.dimensions); return jsonWriter.writeEndObject(); } @@ -254,32 +281,29 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { * @throws IllegalStateException If the deserialized JSON object was missing any required properties. * @throws IOException If an error occurs while reading the AzureOpenAIEmbeddingSkill. */ + @Generated public static AzureOpenAIEmbeddingSkill fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { - boolean inputsFound = false; List inputs = null; - boolean outputsFound = false; List outputs = null; String name = null; String description = null; String context = null; String odataType = "#Microsoft.Skills.Text.AzureOpenAIEmbeddingSkill"; - Integer dimensions = null; String resourceUrl = null; String deploymentName = null; String apiKey = null; SearchIndexerDataIdentity authIdentity = null; AzureOpenAIModelName modelName = null; + Integer dimensions = null; while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); if ("inputs".equals(fieldName)) { inputs = reader.readArray(reader1 -> InputFieldMappingEntry.fromJson(reader1)); - inputsFound = true; } else if ("outputs".equals(fieldName)) { outputs = reader.readArray(reader1 -> OutputFieldMappingEntry.fromJson(reader1)); - outputsFound = true; } else if ("name".equals(fieldName)) { name = reader.getString(); } else if ("description".equals(fieldName)) { @@ -288,8 +312,6 @@ public static AzureOpenAIEmbeddingSkill fromJson(JsonReader jsonReader) throws I context = reader.getString(); } else if ("@odata.type".equals(fieldName)) { odataType = reader.getString(); - } else if ("dimensions".equals(fieldName)) { - dimensions = reader.getNullable(JsonReader::getInt); } else if ("resourceUri".equals(fieldName)) { resourceUrl = reader.getString(); } else if ("deploymentId".equals(fieldName)) { @@ -300,36 +322,26 @@ public static AzureOpenAIEmbeddingSkill fromJson(JsonReader jsonReader) throws I authIdentity = SearchIndexerDataIdentity.fromJson(reader); } else if ("modelName".equals(fieldName)) { modelName = AzureOpenAIModelName.fromString(reader.getString()); + } else if ("dimensions".equals(fieldName)) { + dimensions = reader.getNullable(JsonReader::getInt); } else { reader.skipChildren(); } } - if (inputsFound && outputsFound) { - AzureOpenAIEmbeddingSkill deserializedAzureOpenAIEmbeddingSkill - = new AzureOpenAIEmbeddingSkill(inputs, outputs); - deserializedAzureOpenAIEmbeddingSkill.setName(name); - deserializedAzureOpenAIEmbeddingSkill.setDescription(description); - deserializedAzureOpenAIEmbeddingSkill.setContext(context); - deserializedAzureOpenAIEmbeddingSkill.odataType = odataType; - deserializedAzureOpenAIEmbeddingSkill.dimensions = dimensions; - deserializedAzureOpenAIEmbeddingSkill.resourceUrl = resourceUrl; - deserializedAzureOpenAIEmbeddingSkill.deploymentName = deploymentName; - deserializedAzureOpenAIEmbeddingSkill.apiKey = apiKey; - deserializedAzureOpenAIEmbeddingSkill.authIdentity = authIdentity; - deserializedAzureOpenAIEmbeddingSkill.modelName = modelName; - - return deserializedAzureOpenAIEmbeddingSkill; - } - List missingProperties = new ArrayList<>(); - if (!inputsFound) { - missingProperties.add("inputs"); - } - if (!outputsFound) { - missingProperties.add("outputs"); - } + AzureOpenAIEmbeddingSkill deserializedAzureOpenAIEmbeddingSkill + = new AzureOpenAIEmbeddingSkill(inputs, outputs); + deserializedAzureOpenAIEmbeddingSkill.setName(name); + deserializedAzureOpenAIEmbeddingSkill.setDescription(description); + deserializedAzureOpenAIEmbeddingSkill.setContext(context); + deserializedAzureOpenAIEmbeddingSkill.odataType = odataType; + deserializedAzureOpenAIEmbeddingSkill.resourceUrl = resourceUrl; + deserializedAzureOpenAIEmbeddingSkill.deploymentName = deploymentName; + deserializedAzureOpenAIEmbeddingSkill.apiKey = apiKey; + deserializedAzureOpenAIEmbeddingSkill.authIdentity = authIdentity; + deserializedAzureOpenAIEmbeddingSkill.modelName = modelName; + deserializedAzureOpenAIEmbeddingSkill.dimensions = dimensions; - throw new IllegalStateException( - "Missing required property/properties: " + String.join(", ", missingProperties)); + return deserializedAzureOpenAIEmbeddingSkill; }); } } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/AzureOpenAIModelName.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/AzureOpenAIModelName.java similarity index 60% rename from sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/AzureOpenAIModelName.java rename to sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/AzureOpenAIModelName.java index e2623a01453a..05573c29217b 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/AzureOpenAIModelName.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/AzureOpenAIModelName.java @@ -1,10 +1,10 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. -package com.azure.search.documents.indexes.models; +// Code generated by Microsoft (R) TypeSpec Code Generator. +package com.azure.search.documents.models; + +import com.azure.core.annotation.Generated; import com.azure.core.util.ExpandableStringEnum; import java.util.Collection; @@ -12,46 +12,51 @@ * The Azure Open AI model name that will be called. */ public final class AzureOpenAIModelName extends ExpandableStringEnum { - /** - * Static value text-embedding-ada-002 for AzureOpenAIModelName. + * TextEmbeddingAda002 model. */ - public static final AzureOpenAIModelName TEXT_EMBEDDING_ADA_002 = fromString("text-embedding-ada-002"); + @Generated + public static final AzureOpenAIModelName TEXT_EMBEDDING_ADA002 = fromString("text-embedding-ada-002"); /** - * Static value text-embedding-3-large for AzureOpenAIModelName. + * TextEmbedding3Large model. */ - public static final AzureOpenAIModelName TEXT_EMBEDDING_3_LARGE = fromString("text-embedding-3-large"); + @Generated + public static final AzureOpenAIModelName TEXT_EMBEDDING3LARGE = fromString("text-embedding-3-large"); /** - * Static value text-embedding-3-small for AzureOpenAIModelName. + * TextEmbedding3Small model. */ - public static final AzureOpenAIModelName TEXT_EMBEDDING_3_SMALL = fromString("text-embedding-3-small"); + @Generated + public static final AzureOpenAIModelName TEXT_EMBEDDING3SMALL = fromString("text-embedding-3-small"); /** * Creates a new instance of AzureOpenAIModelName value. - * + * * @deprecated Use the {@link #fromString(String)} factory method. */ + @Generated @Deprecated public AzureOpenAIModelName() { } /** * Creates or finds a AzureOpenAIModelName from its string representation. - * + * * @param name a name to look for. * @return the corresponding AzureOpenAIModelName. */ + @Generated public static AzureOpenAIModelName fromString(String name) { return fromString(name, AzureOpenAIModelName.class); } /** * Gets known AzureOpenAIModelName values. - * + * * @return known AzureOpenAIModelName values. */ + @Generated public static Collection values() { return values(AzureOpenAIModelName.class); } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/AzureOpenAITokenizerParameters.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/AzureOpenAITokenizerParameters.java similarity index 85% rename from sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/AzureOpenAITokenizerParameters.java rename to sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/AzureOpenAITokenizerParameters.java index 1edf3e0bcaf5..1b74a4660525 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/AzureOpenAITokenizerParameters.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/AzureOpenAITokenizerParameters.java @@ -1,12 +1,11 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) TypeSpec Code Generator. -package com.azure.search.documents.indexes.models; +package com.azure.search.documents.models; import com.azure.core.annotation.Fluent; +import com.azure.core.annotation.Generated; import com.azure.json.JsonReader; import com.azure.json.JsonSerializable; import com.azure.json.JsonToken; @@ -15,25 +14,29 @@ import java.util.List; /** - * The AzureOpenAITokenizerParameters model. + * Azure OpenAI Tokenizer parameters. */ @Fluent public final class AzureOpenAITokenizerParameters implements JsonSerializable { /* - * 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'. + * 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'. */ + @Generated private SplitSkillEncoderModelName encoderModelName; /* - * (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. + * (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. */ + @Generated private List allowedSpecialTokens; /** * Creates an instance of AzureOpenAITokenizerParameters class. */ + @Generated public AzureOpenAITokenizerParameters() { } @@ -43,6 +46,7 @@ public AzureOpenAITokenizerParameters() { * * @return the encoderModelName value. */ + @Generated public SplitSkillEncoderModelName getEncoderModelName() { return this.encoderModelName; } @@ -54,6 +58,7 @@ public SplitSkillEncoderModelName getEncoderModelName() { * @param encoderModelName the encoderModelName value to set. * @return the AzureOpenAITokenizerParameters object itself. */ + @Generated public AzureOpenAITokenizerParameters setEncoderModelName(SplitSkillEncoderModelName encoderModelName) { this.encoderModelName = encoderModelName; return this; @@ -61,21 +66,27 @@ public AzureOpenAITokenizerParameters setEncoderModelName(SplitSkillEncoderModel /** * Get the allowedSpecialTokens property: (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. + * parameter + * defines a collection of special tokens that are permitted within the + * tokenization process. * * @return the allowedSpecialTokens value. */ + @Generated public List getAllowedSpecialTokens() { return this.allowedSpecialTokens; } /** * Set the allowedSpecialTokens property: (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. + * parameter + * defines a collection of special tokens that are permitted within the + * tokenization process. * * @param allowedSpecialTokens the allowedSpecialTokens value to set. * @return the AzureOpenAITokenizerParameters object itself. */ + @Generated public AzureOpenAITokenizerParameters setAllowedSpecialTokens(List allowedSpecialTokens) { this.allowedSpecialTokens = allowedSpecialTokens; return this; @@ -84,6 +95,7 @@ public AzureOpenAITokenizerParameters setAllowedSpecialTokens(List allow /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); @@ -102,6 +114,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { * null if it was pointing to JSON null. * @throws IOException If an error occurs while reading the AzureOpenAITokenizerParameters. */ + @Generated public static AzureOpenAITokenizerParameters fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { AzureOpenAITokenizerParameters deserializedAzureOpenAITokenizerParameters diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/AzureOpenAIVectorizer.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/AzureOpenAIVectorizer.java similarity index 79% rename from sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/AzureOpenAIVectorizer.java rename to sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/AzureOpenAIVectorizer.java index 95456cd06edf..792dbc3d8a4d 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/AzureOpenAIVectorizer.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/AzureOpenAIVectorizer.java @@ -1,12 +1,11 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) TypeSpec Code Generator. -package com.azure.search.documents.indexes.models; +package com.azure.search.documents.models; import com.azure.core.annotation.Fluent; +import com.azure.core.annotation.Generated; import com.azure.json.JsonReader; import com.azure.json.JsonToken; import com.azure.json.JsonWriter; @@ -18,13 +17,15 @@ @Fluent public final class AzureOpenAIVectorizer extends VectorSearchVectorizer { /* - * The name of the kind of vectorization method being configured for use with vector search. + * Type of VectorSearchVectorizer. */ + @Generated private VectorSearchVectorizerKind kind = VectorSearchVectorizerKind.AZURE_OPEN_AI; /* * Contains the parameters specific to Azure OpenAI embedding vectorization. */ + @Generated private AzureOpenAIVectorizerParameters parameters; /** @@ -32,15 +33,17 @@ public final class AzureOpenAIVectorizer extends VectorSearchVectorizer { * * @param vectorizerName the vectorizerName value to set. */ + @Generated public AzureOpenAIVectorizer(String vectorizerName) { super(vectorizerName); } /** - * Get the kind property: The name of the kind of vectorization method being configured for use with vector search. + * Get the kind property: Type of VectorSearchVectorizer. * * @return the kind value. */ + @Generated @Override public VectorSearchVectorizerKind getKind() { return this.kind; @@ -51,6 +54,7 @@ public VectorSearchVectorizerKind getKind() { * * @return the parameters value. */ + @Generated public AzureOpenAIVectorizerParameters getParameters() { return this.parameters; } @@ -61,6 +65,7 @@ public AzureOpenAIVectorizerParameters getParameters() { * @param parameters the parameters value to set. * @return the AzureOpenAIVectorizer object itself. */ + @Generated public AzureOpenAIVectorizer setParameters(AzureOpenAIVectorizerParameters parameters) { this.parameters = parameters; return this; @@ -69,6 +74,7 @@ public AzureOpenAIVectorizer setParameters(AzureOpenAIVectorizerParameters param /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); @@ -87,9 +93,9 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { * @throws IllegalStateException If the deserialized JSON object was missing any required properties. * @throws IOException If an error occurs while reading the AzureOpenAIVectorizer. */ + @Generated public static AzureOpenAIVectorizer fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { - boolean vectorizerNameFound = false; String vectorizerName = null; VectorSearchVectorizerKind kind = VectorSearchVectorizerKind.AZURE_OPEN_AI; AzureOpenAIVectorizerParameters parameters = null; @@ -99,7 +105,6 @@ public static AzureOpenAIVectorizer fromJson(JsonReader jsonReader) throws IOExc if ("name".equals(fieldName)) { vectorizerName = reader.getString(); - vectorizerNameFound = true; } else if ("kind".equals(fieldName)) { kind = VectorSearchVectorizerKind.fromString(reader.getString()); } else if ("azureOpenAIParameters".equals(fieldName)) { @@ -108,14 +113,11 @@ public static AzureOpenAIVectorizer fromJson(JsonReader jsonReader) throws IOExc reader.skipChildren(); } } - if (vectorizerNameFound) { - AzureOpenAIVectorizer deserializedAzureOpenAIVectorizer = new AzureOpenAIVectorizer(vectorizerName); - deserializedAzureOpenAIVectorizer.kind = kind; - deserializedAzureOpenAIVectorizer.parameters = parameters; + AzureOpenAIVectorizer deserializedAzureOpenAIVectorizer = new AzureOpenAIVectorizer(vectorizerName); + deserializedAzureOpenAIVectorizer.kind = kind; + deserializedAzureOpenAIVectorizer.parameters = parameters; - return deserializedAzureOpenAIVectorizer; - } - throw new IllegalStateException("Missing required property: name"); + return deserializedAzureOpenAIVectorizer; }); } } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/AzureOpenAIVectorizerParameters.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/AzureOpenAIVectorizerParameters.java similarity index 90% rename from sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/AzureOpenAIVectorizerParameters.java rename to sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/AzureOpenAIVectorizerParameters.java index cf21b58fd3c8..d8e92a373dcd 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/AzureOpenAIVectorizerParameters.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/AzureOpenAIVectorizerParameters.java @@ -1,12 +1,11 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) TypeSpec Code Generator. -package com.azure.search.documents.indexes.models; +package com.azure.search.documents.models; import com.azure.core.annotation.Fluent; +import com.azure.core.annotation.Generated; import com.azure.json.JsonReader; import com.azure.json.JsonSerializable; import com.azure.json.JsonToken; @@ -17,35 +16,42 @@ * Specifies the parameters for connecting to the Azure OpenAI resource. */ @Fluent -public class AzureOpenAIVectorizerParameters implements JsonSerializable { +public final class AzureOpenAIVectorizerParameters implements JsonSerializable { /* * The resource URI of the Azure OpenAI resource. */ + @Generated private String resourceUrl; /* * ID of the Azure OpenAI model deployment on the designated resource. */ + @Generated private String deploymentName; /* * API key of the designated Azure OpenAI resource. */ + @Generated private String apiKey; /* * The user-assigned managed identity used for outbound connections. */ + @Generated private SearchIndexerDataIdentity authIdentity; /* - * The name of the embedding model that is deployed at the provided deploymentId path. + * The name of the embedding model that is deployed at the provided deploymentId + * path. */ + @Generated private AzureOpenAIModelName modelName; /** * Creates an instance of AzureOpenAIVectorizerParameters class. */ + @Generated public AzureOpenAIVectorizerParameters() { } @@ -54,6 +60,7 @@ public AzureOpenAIVectorizerParameters() { * * @return the resourceUrl value. */ + @Generated public String getResourceUrl() { return this.resourceUrl; } @@ -64,6 +71,7 @@ public String getResourceUrl() { * @param resourceUrl the resourceUrl value to set. * @return the AzureOpenAIVectorizerParameters object itself. */ + @Generated public AzureOpenAIVectorizerParameters setResourceUrl(String resourceUrl) { this.resourceUrl = resourceUrl; return this; @@ -74,6 +82,7 @@ public AzureOpenAIVectorizerParameters setResourceUrl(String resourceUrl) { * * @return the deploymentName value. */ + @Generated public String getDeploymentName() { return this.deploymentName; } @@ -84,6 +93,7 @@ public String getDeploymentName() { * @param deploymentName the deploymentName value to set. * @return the AzureOpenAIVectorizerParameters object itself. */ + @Generated public AzureOpenAIVectorizerParameters setDeploymentName(String deploymentName) { this.deploymentName = deploymentName; return this; @@ -94,6 +104,7 @@ public AzureOpenAIVectorizerParameters setDeploymentName(String deploymentName) * * @return the apiKey value. */ + @Generated public String getApiKey() { return this.apiKey; } @@ -104,6 +115,7 @@ public String getApiKey() { * @param apiKey the apiKey value to set. * @return the AzureOpenAIVectorizerParameters object itself. */ + @Generated public AzureOpenAIVectorizerParameters setApiKey(String apiKey) { this.apiKey = apiKey; return this; @@ -114,6 +126,7 @@ public AzureOpenAIVectorizerParameters setApiKey(String apiKey) { * * @return the authIdentity value. */ + @Generated public SearchIndexerDataIdentity getAuthIdentity() { return this.authIdentity; } @@ -124,26 +137,31 @@ public SearchIndexerDataIdentity getAuthIdentity() { * @param authIdentity the authIdentity value to set. * @return the AzureOpenAIVectorizerParameters object itself. */ + @Generated public AzureOpenAIVectorizerParameters setAuthIdentity(SearchIndexerDataIdentity authIdentity) { this.authIdentity = authIdentity; return this; } /** - * Get the modelName property: The name of the embedding model that is deployed at the provided deploymentId path. + * Get the modelName property: The name of the embedding model that is deployed at the provided deploymentId + * path. * * @return the modelName value. */ + @Generated public AzureOpenAIModelName getModelName() { return this.modelName; } /** - * Set the modelName property: The name of the embedding model that is deployed at the provided deploymentId path. + * Set the modelName property: The name of the embedding model that is deployed at the provided deploymentId + * path. * * @param modelName the modelName value to set. * @return the AzureOpenAIVectorizerParameters object itself. */ + @Generated public AzureOpenAIVectorizerParameters setModelName(AzureOpenAIModelName modelName) { this.modelName = modelName; return this; @@ -152,6 +170,7 @@ public AzureOpenAIVectorizerParameters setModelName(AzureOpenAIModelName modelNa /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); @@ -171,6 +190,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { * null if it was pointing to JSON null. * @throws IOException If an error occurs while reading the AzureOpenAIVectorizerParameters. */ + @Generated public static AzureOpenAIVectorizerParameters fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { AzureOpenAIVectorizerParameters deserializedAzureOpenAIVectorizerParameters diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/BM25SimilarityAlgorithm.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/BM25SimilarityAlgorithm.java similarity index 65% rename from sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/BM25SimilarityAlgorithm.java rename to sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/BM25SimilarityAlgorithm.java index 8cbf04bfb2a0..1996d99f18a1 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/BM25SimilarityAlgorithm.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/BM25SimilarityAlgorithm.java @@ -1,102 +1,117 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) TypeSpec Code Generator. -package com.azure.search.documents.indexes.models; +package com.azure.search.documents.models; import com.azure.core.annotation.Fluent; +import com.azure.core.annotation.Generated; import com.azure.json.JsonReader; import com.azure.json.JsonToken; import com.azure.json.JsonWriter; import java.io.IOException; /** - * 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' + * 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). */ @Fluent public final class BM25SimilarityAlgorithm extends SimilarityAlgorithm { /* - * The @odata.type property. + * The discriminator for derived types. */ + @Generated private String odataType = "#Microsoft.Azure.Search.BM25Similarity"; /* - * 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. + * 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. */ + @Generated private Double k1; /* - * 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 + * 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. */ + @Generated private Double b; /** * Creates an instance of BM25SimilarityAlgorithm class. */ + @Generated public BM25SimilarityAlgorithm() { } /** - * Get the odataType property: The @odata.type property. + * Get the odataType property: The discriminator for derived types. * * @return the odataType value. */ + @Generated @Override public String getOdataType() { return this.odataType; } /** - * Get the k1 property: 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. + * Get the k1 property: 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. * * @return the k1 value. */ + @Generated public Double getK1() { return this.k1; } /** - * Set the k1 property: 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. + * Set the k1 property: 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. * * @param k1 the k1 value to set. * @return the BM25SimilarityAlgorithm object itself. */ + @Generated public BM25SimilarityAlgorithm setK1(Double k1) { this.k1 = k1; return this; } /** - * Get the b property: 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. + * Get the b property: 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. * * @return the b value. */ + @Generated public Double getB() { return this.b; } /** - * Set the b property: 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. + * Set the b property: 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. * * @param b the b value to set. * @return the BM25SimilarityAlgorithm object itself. */ + @Generated public BM25SimilarityAlgorithm setB(Double b) { this.b = b; return this; @@ -105,6 +120,7 @@ public BM25SimilarityAlgorithm setB(Double b) { /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); @@ -122,6 +138,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { * was pointing to JSON null. * @throws IOException If an error occurs while reading the BM25SimilarityAlgorithm. */ + @Generated public static BM25SimilarityAlgorithm fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { BM25SimilarityAlgorithm deserializedBM25SimilarityAlgorithm = new BM25SimilarityAlgorithm(); diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/BinaryQuantizationCompression.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/BinaryQuantizationCompression.java similarity index 77% rename from sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/BinaryQuantizationCompression.java rename to sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/BinaryQuantizationCompression.java index 49ca70778f8c..db54e6db598c 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/BinaryQuantizationCompression.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/BinaryQuantizationCompression.java @@ -1,26 +1,26 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) TypeSpec Code Generator. -package com.azure.search.documents.indexes.models; +package com.azure.search.documents.models; import com.azure.core.annotation.Fluent; +import com.azure.core.annotation.Generated; import com.azure.json.JsonReader; import com.azure.json.JsonToken; import com.azure.json.JsonWriter; import java.io.IOException; /** - * Contains configuration options specific to the binary quantization compression method used during indexing and - * querying. + * Contains configuration options specific to the binary quantization compression + * method used during indexing and querying. */ @Fluent public final class BinaryQuantizationCompression extends VectorSearchCompression { /* - * The name of the kind of compression method being configured for use with vector search. + * Type of VectorSearchCompression. */ + @Generated private VectorSearchCompressionKind kind = VectorSearchCompressionKind.BINARY_QUANTIZATION; /** @@ -28,15 +28,17 @@ public final class BinaryQuantizationCompression extends VectorSearchCompression * * @param compressionName the compressionName value to set. */ + @Generated public BinaryQuantizationCompression(String compressionName) { super(compressionName); } /** - * Get the kind property: The name of the kind of compression method being configured for use with vector search. + * Get the kind property: Type of VectorSearchCompression. * * @return the kind value. */ + @Generated @Override public VectorSearchCompressionKind getKind() { return this.kind; @@ -45,6 +47,7 @@ public VectorSearchCompressionKind getKind() { /** * {@inheritDoc} */ + @Generated @Override public BinaryQuantizationCompression setRerankWithOriginalVectors(Boolean rerankWithOriginalVectors) { super.setRerankWithOriginalVectors(rerankWithOriginalVectors); @@ -54,6 +57,7 @@ public BinaryQuantizationCompression setRerankWithOriginalVectors(Boolean rerank /** * {@inheritDoc} */ + @Generated @Override public BinaryQuantizationCompression setDefaultOversampling(Double defaultOversampling) { super.setDefaultOversampling(defaultOversampling); @@ -63,6 +67,7 @@ public BinaryQuantizationCompression setDefaultOversampling(Double defaultOversa /** * {@inheritDoc} */ + @Generated @Override public BinaryQuantizationCompression setRescoringOptions(RescoringOptions rescoringOptions) { super.setRescoringOptions(rescoringOptions); @@ -72,6 +77,7 @@ public BinaryQuantizationCompression setRescoringOptions(RescoringOptions rescor /** * {@inheritDoc} */ + @Generated @Override public BinaryQuantizationCompression setTruncationDimension(Integer truncationDimension) { super.setTruncationDimension(truncationDimension); @@ -81,6 +87,7 @@ public BinaryQuantizationCompression setTruncationDimension(Integer truncationDi /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); @@ -102,9 +109,9 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { * @throws IllegalStateException If the deserialized JSON object was missing any required properties. * @throws IOException If an error occurs while reading the BinaryQuantizationCompression. */ + @Generated public static BinaryQuantizationCompression fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { - boolean compressionNameFound = false; String compressionName = null; Boolean rerankWithOriginalVectors = null; Double defaultOversampling = null; @@ -117,7 +124,6 @@ public static BinaryQuantizationCompression fromJson(JsonReader jsonReader) thro if ("name".equals(fieldName)) { compressionName = reader.getString(); - compressionNameFound = true; } else if ("rerankWithOriginalVectors".equals(fieldName)) { rerankWithOriginalVectors = reader.getNullable(JsonReader::getBoolean); } else if ("defaultOversampling".equals(fieldName)) { @@ -132,18 +138,15 @@ public static BinaryQuantizationCompression fromJson(JsonReader jsonReader) thro reader.skipChildren(); } } - if (compressionNameFound) { - BinaryQuantizationCompression deserializedBinaryQuantizationCompression - = new BinaryQuantizationCompression(compressionName); - deserializedBinaryQuantizationCompression.setRerankWithOriginalVectors(rerankWithOriginalVectors); - deserializedBinaryQuantizationCompression.setDefaultOversampling(defaultOversampling); - deserializedBinaryQuantizationCompression.setRescoringOptions(rescoringOptions); - deserializedBinaryQuantizationCompression.setTruncationDimension(truncationDimension); - deserializedBinaryQuantizationCompression.kind = kind; + BinaryQuantizationCompression deserializedBinaryQuantizationCompression + = new BinaryQuantizationCompression(compressionName); + deserializedBinaryQuantizationCompression.setRerankWithOriginalVectors(rerankWithOriginalVectors); + deserializedBinaryQuantizationCompression.setDefaultOversampling(defaultOversampling); + deserializedBinaryQuantizationCompression.setRescoringOptions(rescoringOptions); + deserializedBinaryQuantizationCompression.setTruncationDimension(truncationDimension); + deserializedBinaryQuantizationCompression.kind = kind; - return deserializedBinaryQuantizationCompression; - } - throw new IllegalStateException("Missing required property: name"); + return deserializedBinaryQuantizationCompression; }); } } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/BlobIndexerDataToExtract.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/BlobIndexerDataToExtract.java similarity index 77% rename from sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/BlobIndexerDataToExtract.java rename to sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/BlobIndexerDataToExtract.java index 76e22a4af880..dbc8734b0156 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/BlobIndexerDataToExtract.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/BlobIndexerDataToExtract.java @@ -1,34 +1,38 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) TypeSpec Code Generator. -package com.azure.search.documents.indexes.models; +package com.azure.search.documents.models; +import com.azure.core.annotation.Generated; import com.azure.core.util.ExpandableStringEnum; import java.util.Collection; /** - * 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 + * 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. */ public final class BlobIndexerDataToExtract extends ExpandableStringEnum { /** * Indexes just the standard blob properties and user-specified metadata. */ + @Generated public static final BlobIndexerDataToExtract STORAGE_METADATA = fromString("storageMetadata"); /** - * Extracts metadata provided by the Azure blob storage subsystem and the content-type specific metadata (for - * example, metadata unique to just .png files are indexed). + * Extracts metadata provided by the Azure blob storage subsystem and the + * content-type specific metadata (for example, metadata unique to just .png files + * are indexed). */ + @Generated public static final BlobIndexerDataToExtract ALL_METADATA = fromString("allMetadata"); /** * Extracts all metadata and textual content from each blob. */ + @Generated public static final BlobIndexerDataToExtract CONTENT_AND_METADATA = fromString("contentAndMetadata"); /** @@ -36,6 +40,7 @@ public final class BlobIndexerDataToExtract extends ExpandableStringEnum values() { return values(BlobIndexerDataToExtract.class); } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/BlobIndexerImageAction.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/BlobIndexerImageAction.java similarity index 62% rename from sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/BlobIndexerImageAction.java rename to sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/BlobIndexerImageAction.java index 4c24765fa999..26c654520675 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/BlobIndexerImageAction.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/BlobIndexerImageAction.java @@ -1,39 +1,44 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) TypeSpec Code Generator. -package com.azure.search.documents.indexes.models; +package com.azure.search.documents.models; +import com.azure.core.annotation.Generated; import com.azure.core.util.ExpandableStringEnum; import java.util.Collection; /** - * 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. + * 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. */ public final class BlobIndexerImageAction extends ExpandableStringEnum { /** * Ignores embedded images or image files in the data set. This is the default. */ + @Generated public static final BlobIndexerImageAction NONE = fromString("none"); /** - * Extracts text from images (for example, the word "STOP" from a traffic stop sign), and embeds it into the content - * field. This action requires that "dataToExtract" is set to "contentAndMetadata". A normalized image refers to - * additional processing resulting in uniform image output, sized and rotated to promote consistent rendering when - * you include images in visual search results. This information is generated for each image when you use this - * option. + * Extracts text from images (for example, the word "STOP" from a traffic stop + * sign), and embeds it into the content field. This action requires that + * "dataToExtract" is set to "contentAndMetadata". A normalized image refers to + * additional processing resulting in uniform image output, sized and rotated to + * promote consistent rendering when you include images in visual search results. + * This information is generated for each image when you use this option. */ + @Generated public static final BlobIndexerImageAction GENERATE_NORMALIZED_IMAGES = fromString("generateNormalizedImages"); /** - * Extracts text from images (for example, the word "STOP" from a traffic stop sign), and embeds it into the content - * field, but treats PDF files differently in that each page will be rendered as an image and normalized - * accordingly, instead of extracting embedded images. Non-PDF file types will be treated the same as if - * "generateNormalizedImages" was set. + * Extracts text from images (for example, the word "STOP" from a traffic stop + * sign), and embeds it into the content field, but treats PDF files differently + * in that each page will be rendered as an image and normalized accordingly, + * instead of extracting embedded images. Non-PDF file types will be treated the + * same as if "generateNormalizedImages" was set. */ + @Generated public static final BlobIndexerImageAction GENERATE_NORMALIZED_IMAGE_PER_PAGE = fromString("generateNormalizedImagePerPage"); @@ -42,6 +47,7 @@ public final class BlobIndexerImageAction extends ExpandableStringEnum values() { return values(BlobIndexerImageAction.class); } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/BlobIndexerPDFTextRotationAlgorithm.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/BlobIndexerPDFTextRotationAlgorithm.java new file mode 100644 index 000000000000..4f8185a80212 --- /dev/null +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/BlobIndexerPDFTextRotationAlgorithm.java @@ -0,0 +1,62 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.search.documents.models; + +import com.azure.core.annotation.Generated; +import com.azure.core.util.ExpandableStringEnum; +import java.util.Collection; + +/** + * Determines algorithm for text extraction from PDF files in Azure blob storage. + */ +public final class BlobIndexerPDFTextRotationAlgorithm + extends ExpandableStringEnum { + /** + * Leverages normal text extraction. This is the default. + */ + @Generated + public static final BlobIndexerPDFTextRotationAlgorithm NONE = fromString("none"); + + /** + * May produce better and more readable text extraction from PDF files that have + * rotated text within them. Note that there may be a small performance speed + * impact when this parameter is used. This parameter only applies to PDF files, + * and only to PDFs with embedded text. If the rotated text appears within an + * embedded image in the PDF, this parameter does not apply. + */ + @Generated + public static final BlobIndexerPDFTextRotationAlgorithm DETECT_ANGLES = fromString("detectAngles"); + + /** + * Creates a new instance of BlobIndexerPDFTextRotationAlgorithm value. + * + * @deprecated Use the {@link #fromString(String)} factory method. + */ + @Generated + @Deprecated + public BlobIndexerPDFTextRotationAlgorithm() { + } + + /** + * Creates or finds a BlobIndexerPDFTextRotationAlgorithm from its string representation. + * + * @param name a name to look for. + * @return the corresponding BlobIndexerPDFTextRotationAlgorithm. + */ + @Generated + public static BlobIndexerPDFTextRotationAlgorithm fromString(String name) { + return fromString(name, BlobIndexerPDFTextRotationAlgorithm.class); + } + + /** + * Gets known BlobIndexerPDFTextRotationAlgorithm values. + * + * @return known BlobIndexerPDFTextRotationAlgorithm values. + */ + @Generated + public static Collection values() { + return values(BlobIndexerPDFTextRotationAlgorithm.class); + } +} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/BlobIndexerParsingMode.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/BlobIndexerParsingMode.java similarity index 85% rename from sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/BlobIndexerParsingMode.java rename to sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/BlobIndexerParsingMode.java index c4af2d592b78..5dd46a260461 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/BlobIndexerParsingMode.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/BlobIndexerParsingMode.java @@ -1,11 +1,10 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) TypeSpec Code Generator. -package com.azure.search.documents.indexes.models; +package com.azure.search.documents.models; +import com.azure.core.annotation.Generated; import com.azure.core.util.ExpandableStringEnum; import java.util.Collection; @@ -16,36 +15,45 @@ public final class BlobIndexerParsingMode extends ExpandableStringEnum values() { return values(BlobIndexerParsingMode.class); } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/CharFilter.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/CharFilter.java similarity index 79% rename from sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/CharFilter.java rename to sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/CharFilter.java index a65d28e7909e..2056fcf28319 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/CharFilter.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/CharFilter.java @@ -1,11 +1,10 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) TypeSpec Code Generator. -package com.azure.search.documents.indexes.models; +package com.azure.search.documents.models; +import com.azure.core.annotation.Generated; import com.azure.core.annotation.Immutable; import com.azure.json.JsonReader; import com.azure.json.JsonSerializable; @@ -19,14 +18,17 @@ @Immutable public class CharFilter implements JsonSerializable { /* - * A URI fragment specifying the type of char filter. + * The discriminator for derived types. */ + @Generated private String odataType = "CharFilter"; /* - * 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. + * 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. */ + @Generated private final String name; /** @@ -34,25 +36,29 @@ public class CharFilter implements JsonSerializable { * * @param name the name value to set. */ + @Generated public CharFilter(String name) { this.name = name; } /** - * Get the odataType property: A URI fragment specifying the type of char filter. + * Get the odataType property: The discriminator for derived types. * * @return the odataType value. */ + @Generated public String getOdataType() { return this.odataType; } /** - * Get the name property: 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. + * Get the name property: 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. * * @return the name value. */ + @Generated public String getName() { return this.name; } @@ -60,6 +66,7 @@ public String getName() { /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); @@ -77,6 +84,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { * @throws IllegalStateException If the deserialized JSON object was missing any required properties. * @throws IOException If an error occurs while reading the CharFilter. */ + @Generated public static CharFilter fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { String discriminatorValue = null; @@ -104,9 +112,9 @@ public static CharFilter fromJson(JsonReader jsonReader) throws IOException { }); } + @Generated static CharFilter fromJsonKnownDiscriminator(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { - boolean nameFound = false; String name = null; String odataType = null; while (reader.nextToken() != JsonToken.END_OBJECT) { @@ -115,20 +123,16 @@ static CharFilter fromJsonKnownDiscriminator(JsonReader jsonReader) throws IOExc if ("name".equals(fieldName)) { name = reader.getString(); - nameFound = true; } else if ("@odata.type".equals(fieldName)) { odataType = reader.getString(); } else { reader.skipChildren(); } } - if (nameFound) { - CharFilter deserializedCharFilter = new CharFilter(name); - deserializedCharFilter.odataType = odataType; + CharFilter deserializedCharFilter = new CharFilter(name); + deserializedCharFilter.odataType = odataType; - return deserializedCharFilter; - } - throw new IllegalStateException("Missing required property: name"); + return deserializedCharFilter; }); } } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/CharFilterName.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/CharFilterName.java similarity index 86% rename from sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/CharFilterName.java rename to sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/CharFilterName.java index d03dbb631ee3..deeaee1ee285 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/CharFilterName.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/CharFilterName.java @@ -1,11 +1,10 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) TypeSpec Code Generator. -package com.azure.search.documents.indexes.models; +package com.azure.search.documents.models; +import com.azure.core.annotation.Generated; import com.azure.core.util.ExpandableStringEnum; import java.util.Collection; @@ -17,6 +16,7 @@ public final class CharFilterName extends ExpandableStringEnum { * 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. */ + @Generated public static final CharFilterName HTML_STRIP = fromString("html_strip"); /** @@ -24,6 +24,7 @@ public final class CharFilterName extends ExpandableStringEnum { * * @deprecated Use the {@link #fromString(String)} factory method. */ + @Generated @Deprecated public CharFilterName() { } @@ -34,6 +35,7 @@ public CharFilterName() { * @param name a name to look for. * @return the corresponding CharFilterName. */ + @Generated public static CharFilterName fromString(String name) { return fromString(name, CharFilterName.class); } @@ -43,6 +45,7 @@ public static CharFilterName fromString(String name) { * * @return known CharFilterName values. */ + @Generated public static Collection values() { return values(CharFilterName.class); } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/CjkBigramTokenFilter.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/CjkBigramTokenFilter.java similarity index 74% rename from sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/CjkBigramTokenFilter.java rename to sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/CjkBigramTokenFilter.java index bed44dc90b15..0aa5d01e1b60 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/CjkBigramTokenFilter.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/CjkBigramTokenFilter.java @@ -1,55 +1,58 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. -package com.azure.search.documents.indexes.models; +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.search.documents.models; import com.azure.core.annotation.Fluent; +import com.azure.core.annotation.Generated; import com.azure.json.JsonReader; import com.azure.json.JsonToken; import com.azure.json.JsonWriter; import java.io.IOException; -import java.util.Arrays; import java.util.List; /** - * Forms bigrams of CJK terms that are generated from the standard tokenizer. This token filter is implemented using - * Apache Lucene. + * Forms bigrams of CJK terms that are generated from the standard tokenizer. This + * token filter is implemented using Apache Lucene. */ @Fluent public final class CjkBigramTokenFilter extends TokenFilter { - /* - * A URI fragment specifying the type of token filter. + * The discriminator for derived types. */ + @Generated private String odataType = "#Microsoft.Azure.Search.CjkBigramTokenFilter"; /* * The scripts to ignore. */ + @Generated private List ignoreScripts; /* - * A value indicating whether to output both unigrams and bigrams (if true), or just bigrams (if false). Default is - * false. + * A value indicating whether to output both unigrams and bigrams (if true), or + * just bigrams (if false). Default is false. */ + @Generated private Boolean outputUnigrams; /** * Creates an instance of CjkBigramTokenFilter class. - * + * * @param name the name value to set. */ + @Generated public CjkBigramTokenFilter(String name) { super(name); } /** - * Get the odataType property: A URI fragment specifying the type of token filter. - * + * Get the odataType property: The discriminator for derived types. + * * @return the odataType value. */ + @Generated @Override public String getOdataType() { return this.odataType; @@ -57,19 +60,21 @@ public String getOdataType() { /** * Get the ignoreScripts property: The scripts to ignore. - * + * * @return the ignoreScripts value. */ + @Generated public List getIgnoreScripts() { return this.ignoreScripts; } /** * Set the ignoreScripts property: The scripts to ignore. - * + * * @param ignoreScripts the ignoreScripts value to set. * @return the CjkBigramTokenFilter object itself. */ + @Generated public CjkBigramTokenFilter setIgnoreScripts(List ignoreScripts) { this.ignoreScripts = ignoreScripts; return this; @@ -78,20 +83,22 @@ public CjkBigramTokenFilter setIgnoreScripts(List i /** * Get the outputUnigrams property: A value indicating whether to output both unigrams and bigrams (if true), or * just bigrams (if false). Default is false. - * + * * @return the outputUnigrams value. */ - public Boolean areOutputUnigrams() { + @Generated + public Boolean isOutputUnigrams() { return this.outputUnigrams; } /** * Set the outputUnigrams property: A value indicating whether to output both unigrams and bigrams (if true), or * just bigrams (if false). Default is false. - * + * * @param outputUnigrams the outputUnigrams value to set. * @return the CjkBigramTokenFilter object itself. */ + @Generated public CjkBigramTokenFilter setOutputUnigrams(Boolean outputUnigrams) { this.outputUnigrams = outputUnigrams; return this; @@ -100,6 +107,7 @@ public CjkBigramTokenFilter setOutputUnigrams(Boolean outputUnigrams) { /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); @@ -113,16 +121,16 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of CjkBigramTokenFilter from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of CjkBigramTokenFilter if the JsonReader was pointing to an instance of it, or null if it * was pointing to JSON null. * @throws IllegalStateException If the deserialized JSON object was missing any required properties. * @throws IOException If an error occurs while reading the CjkBigramTokenFilter. */ + @Generated public static CjkBigramTokenFilter fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { - boolean nameFound = false; String name = null; String odataType = "#Microsoft.Azure.Search.CjkBigramTokenFilter"; List ignoreScripts = null; @@ -130,9 +138,9 @@ public static CjkBigramTokenFilter fromJson(JsonReader jsonReader) throws IOExce while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); + if ("name".equals(fieldName)) { name = reader.getString(); - nameFound = true; } else if ("@odata.type".equals(fieldName)) { odataType = reader.getString(); } else if ("ignoreScripts".equals(fieldName)) { @@ -144,25 +152,12 @@ public static CjkBigramTokenFilter fromJson(JsonReader jsonReader) throws IOExce reader.skipChildren(); } } - if (nameFound) { - CjkBigramTokenFilter deserializedCjkBigramTokenFilter = new CjkBigramTokenFilter(name); - deserializedCjkBigramTokenFilter.odataType = odataType; - deserializedCjkBigramTokenFilter.ignoreScripts = ignoreScripts; - deserializedCjkBigramTokenFilter.outputUnigrams = outputUnigrams; - return deserializedCjkBigramTokenFilter; - } - throw new IllegalStateException("Missing required property: name"); - }); - } + CjkBigramTokenFilter deserializedCjkBigramTokenFilter = new CjkBigramTokenFilter(name); + deserializedCjkBigramTokenFilter.odataType = odataType; + deserializedCjkBigramTokenFilter.ignoreScripts = ignoreScripts; + deserializedCjkBigramTokenFilter.outputUnigrams = outputUnigrams; - /** - * Set the ignoreScripts property: The scripts to ignore. - * - * @param ignoreScripts the ignoreScripts value to set. - * @return the CjkBigramTokenFilter object itself. - */ - public CjkBigramTokenFilter setIgnoreScripts(CjkBigramTokenFilterScripts... ignoreScripts) { - this.ignoreScripts = (ignoreScripts == null) ? null : Arrays.asList(ignoreScripts); - return this; + return deserializedCjkBigramTokenFilter; + }); } } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/CjkBigramTokenFilterScripts.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/CjkBigramTokenFilterScripts.java new file mode 100644 index 000000000000..68f4eb22fa7e --- /dev/null +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/CjkBigramTokenFilterScripts.java @@ -0,0 +1,69 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.search.documents.models; + +import com.azure.core.annotation.Generated; +import com.azure.core.util.ExpandableStringEnum; +import java.util.Collection; + +/** + * Scripts that can be ignored by CjkBigramTokenFilter. + */ +public final class CjkBigramTokenFilterScripts extends ExpandableStringEnum { + /** + * Ignore Han script when forming bigrams of CJK terms. + */ + @Generated + public static final CjkBigramTokenFilterScripts HAN = fromString("han"); + + /** + * Ignore Hiragana script when forming bigrams of CJK terms. + */ + @Generated + public static final CjkBigramTokenFilterScripts HIRAGANA = fromString("hiragana"); + + /** + * Ignore Katakana script when forming bigrams of CJK terms. + */ + @Generated + public static final CjkBigramTokenFilterScripts KATAKANA = fromString("katakana"); + + /** + * Ignore Hangul script when forming bigrams of CJK terms. + */ + @Generated + public static final CjkBigramTokenFilterScripts HANGUL = fromString("hangul"); + + /** + * Creates a new instance of CjkBigramTokenFilterScripts value. + * + * @deprecated Use the {@link #fromString(String)} factory method. + */ + @Generated + @Deprecated + public CjkBigramTokenFilterScripts() { + } + + /** + * Creates or finds a CjkBigramTokenFilterScripts from its string representation. + * + * @param name a name to look for. + * @return the corresponding CjkBigramTokenFilterScripts. + */ + @Generated + public static CjkBigramTokenFilterScripts fromString(String name) { + return fromString(name, CjkBigramTokenFilterScripts.class); + } + + /** + * Gets known CjkBigramTokenFilterScripts values. + * + * @return known CjkBigramTokenFilterScripts values. + */ + @Generated + public static Collection values() { + return values(CjkBigramTokenFilterScripts.class); + } +} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/ClassicSimilarityAlgorithm.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/ClassicSimilarityAlgorithm.java similarity index 80% rename from sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/ClassicSimilarityAlgorithm.java rename to sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/ClassicSimilarityAlgorithm.java index aaf4bbfef93c..5fb13c0b2b76 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/ClassicSimilarityAlgorithm.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/ClassicSimilarityAlgorithm.java @@ -1,11 +1,10 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) TypeSpec Code Generator. -package com.azure.search.documents.indexes.models; +package com.azure.search.documents.models; +import com.azure.core.annotation.Generated; import com.azure.core.annotation.Immutable; import com.azure.json.JsonReader; import com.azure.json.JsonToken; @@ -13,28 +12,32 @@ import java.io.IOException; /** - * 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. + * 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. */ @Immutable public final class ClassicSimilarityAlgorithm extends SimilarityAlgorithm { /* - * The @odata.type property. + * The discriminator for derived types. */ + @Generated private String odataType = "#Microsoft.Azure.Search.ClassicSimilarity"; /** * Creates an instance of ClassicSimilarityAlgorithm class. */ + @Generated public ClassicSimilarityAlgorithm() { } /** - * Get the odataType property: The @odata.type property. + * Get the odataType property: The discriminator for derived types. * * @return the odataType value. */ + @Generated @Override public String getOdataType() { return this.odataType; @@ -43,6 +46,7 @@ public String getOdataType() { /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); @@ -58,6 +62,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { * it was pointing to JSON null. * @throws IOException If an error occurs while reading the ClassicSimilarityAlgorithm. */ + @Generated public static ClassicSimilarityAlgorithm fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { ClassicSimilarityAlgorithm deserializedClassicSimilarityAlgorithm = new ClassicSimilarityAlgorithm(); diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/ClassicTokenizer.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/ClassicTokenizer.java similarity index 77% rename from sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/ClassicTokenizer.java rename to sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/ClassicTokenizer.java index f06c779504d7..02eaccfa13bc 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/ClassicTokenizer.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/ClassicTokenizer.java @@ -1,32 +1,33 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) TypeSpec Code Generator. -package com.azure.search.documents.indexes.models; +package com.azure.search.documents.models; import com.azure.core.annotation.Fluent; +import com.azure.core.annotation.Generated; import com.azure.json.JsonReader; import com.azure.json.JsonToken; import com.azure.json.JsonWriter; import java.io.IOException; /** - * Grammar-based tokenizer that is suitable for processing most European-language documents. This tokenizer is - * implemented using Apache Lucene. + * Grammar-based tokenizer that is suitable for processing most European-language + * documents. This tokenizer is implemented using Apache Lucene. */ @Fluent public final class ClassicTokenizer extends LexicalTokenizer { /* - * A URI fragment specifying the type of tokenizer. + * The discriminator for derived types. */ + @Generated private String odataType = "#Microsoft.Azure.Search.ClassicTokenizer"; /* - * 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. + * 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. */ + @Generated private Integer maxTokenLength; /** @@ -34,15 +35,17 @@ public final class ClassicTokenizer extends LexicalTokenizer { * * @param name the name value to set. */ + @Generated public ClassicTokenizer(String name) { super(name); } /** - * Get the odataType property: A URI fragment specifying the type of tokenizer. + * Get the odataType property: The discriminator for derived types. * * @return the odataType value. */ + @Generated @Override public String getOdataType() { return this.odataType; @@ -54,6 +57,7 @@ public String getOdataType() { * * @return the maxTokenLength value. */ + @Generated public Integer getMaxTokenLength() { return this.maxTokenLength; } @@ -65,6 +69,7 @@ public Integer getMaxTokenLength() { * @param maxTokenLength the maxTokenLength value to set. * @return the ClassicTokenizer object itself. */ + @Generated public ClassicTokenizer setMaxTokenLength(Integer maxTokenLength) { this.maxTokenLength = maxTokenLength; return this; @@ -73,6 +78,7 @@ public ClassicTokenizer setMaxTokenLength(Integer maxTokenLength) { /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); @@ -91,9 +97,9 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { * @throws IllegalStateException If the deserialized JSON object was missing any required properties. * @throws IOException If an error occurs while reading the ClassicTokenizer. */ + @Generated public static ClassicTokenizer fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { - boolean nameFound = false; String name = null; String odataType = "#Microsoft.Azure.Search.ClassicTokenizer"; Integer maxTokenLength = null; @@ -103,7 +109,6 @@ public static ClassicTokenizer fromJson(JsonReader jsonReader) throws IOExceptio if ("name".equals(fieldName)) { name = reader.getString(); - nameFound = true; } else if ("@odata.type".equals(fieldName)) { odataType = reader.getString(); } else if ("maxTokenLength".equals(fieldName)) { @@ -112,14 +117,11 @@ public static ClassicTokenizer fromJson(JsonReader jsonReader) throws IOExceptio reader.skipChildren(); } } - if (nameFound) { - ClassicTokenizer deserializedClassicTokenizer = new ClassicTokenizer(name); - deserializedClassicTokenizer.odataType = odataType; - deserializedClassicTokenizer.maxTokenLength = maxTokenLength; + ClassicTokenizer deserializedClassicTokenizer = new ClassicTokenizer(name); + deserializedClassicTokenizer.odataType = odataType; + deserializedClassicTokenizer.maxTokenLength = maxTokenLength; - return deserializedClassicTokenizer; - } - throw new IllegalStateException("Missing required property: name"); + return deserializedClassicTokenizer; }); } } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/CognitiveServicesAccount.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/CognitiveServicesAccount.java similarity index 92% rename from sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/CognitiveServicesAccount.java rename to sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/CognitiveServicesAccount.java index c705e8b96a8b..33c23ff665e2 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/CognitiveServicesAccount.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/CognitiveServicesAccount.java @@ -1,12 +1,11 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) TypeSpec Code Generator. -package com.azure.search.documents.indexes.models; +package com.azure.search.documents.models; import com.azure.core.annotation.Fluent; +import com.azure.core.annotation.Generated; import com.azure.json.JsonReader; import com.azure.json.JsonSerializable; import com.azure.json.JsonToken; @@ -19,27 +18,30 @@ @Fluent public class CognitiveServicesAccount implements JsonSerializable { /* - * A URI fragment specifying the type of Azure AI service resource attached to a skillset. + * The discriminator for derived types. */ + @Generated private String odataType = "CognitiveServicesAccount"; /* * Description of the Azure AI service resource attached to a skillset. */ + @Generated private String description; /** * Creates an instance of CognitiveServicesAccount class. */ + @Generated public CognitiveServicesAccount() { } /** - * Get the odataType property: A URI fragment specifying the type of Azure AI service resource attached to a - * skillset. + * Get the odataType property: The discriminator for derived types. * * @return the odataType value. */ + @Generated public String getOdataType() { return this.odataType; } @@ -49,6 +51,7 @@ public String getOdataType() { * * @return the description value. */ + @Generated public String getDescription() { return this.description; } @@ -59,6 +62,7 @@ public String getDescription() { * @param description the description value to set. * @return the CognitiveServicesAccount object itself. */ + @Generated public CognitiveServicesAccount setDescription(String description) { this.description = description; return this; @@ -67,6 +71,7 @@ public CognitiveServicesAccount setDescription(String description) { /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); @@ -83,6 +88,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { * it was pointing to JSON null. * @throws IOException If an error occurs while reading the CognitiveServicesAccount. */ + @Generated public static CognitiveServicesAccount fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { String discriminatorValue = null; @@ -114,6 +120,7 @@ public static CognitiveServicesAccount fromJson(JsonReader jsonReader) throws IO }); } + @Generated static CognitiveServicesAccount fromJsonKnownDiscriminator(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { CognitiveServicesAccount deserializedCognitiveServicesAccount = new CognitiveServicesAccount(); diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/CognitiveServicesAccountKey.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/CognitiveServicesAccountKey.java similarity index 69% rename from sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/CognitiveServicesAccountKey.java rename to sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/CognitiveServicesAccountKey.java index 747b6b378cba..d47b263479c8 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/CognitiveServicesAccountKey.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/CognitiveServicesAccountKey.java @@ -1,47 +1,50 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. -package com.azure.search.documents.indexes.models; +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.search.documents.models; import com.azure.core.annotation.Fluent; +import com.azure.core.annotation.Generated; import com.azure.json.JsonReader; import com.azure.json.JsonToken; import com.azure.json.JsonWriter; import java.io.IOException; /** - * The multi-region account key of an Azure AI service resource that's attached to a skillset. + * The multi-region account key of an Azure AI service resource that's attached to + * a skillset. */ @Fluent public final class CognitiveServicesAccountKey extends CognitiveServicesAccount { - /* - * A URI fragment specifying the type of Azure AI service resource attached to a skillset. + * The discriminator for derived types. */ + @Generated private String odataType = "#Microsoft.Azure.Search.CognitiveServicesByKey"; /* * The key used to provision the Azure AI service resource attached to a skillset. */ - private String key; + @Generated + private final String key; /** * Creates an instance of CognitiveServicesAccountKey class. - * + * * @param key the key value to set. */ + @Generated public CognitiveServicesAccountKey(String key) { this.key = key; } /** - * Get the odataType property: A URI fragment specifying the type of Azure AI service resource attached to a - * skillset. - * + * Get the odataType property: The discriminator for derived types. + * * @return the odataType value. */ + @Generated @Override public String getOdataType() { return this.odataType; @@ -49,9 +52,10 @@ public String getOdataType() { /** * Get the key property: The key used to provision the Azure AI service resource attached to a skillset. - * + * * @return the key value. */ + @Generated public String getKey() { return this.key; } @@ -59,6 +63,7 @@ public String getKey() { /** * {@inheritDoc} */ + @Generated @Override public CognitiveServicesAccountKey setDescription(String description) { super.setDescription(description); @@ -68,6 +73,7 @@ public CognitiveServicesAccountKey setDescription(String description) { /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); @@ -79,52 +85,38 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of CognitiveServicesAccountKey from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of CognitiveServicesAccountKey if the JsonReader was pointing to an instance of it, or null * if it was pointing to JSON null. * @throws IllegalStateException If the deserialized JSON object was missing any required properties. * @throws IOException If an error occurs while reading the CognitiveServicesAccountKey. */ + @Generated public static CognitiveServicesAccountKey fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { String description = null; - boolean keyFound = false; String key = null; String odataType = "#Microsoft.Azure.Search.CognitiveServicesByKey"; while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); + if ("description".equals(fieldName)) { description = reader.getString(); } else if ("key".equals(fieldName)) { key = reader.getString(); - keyFound = true; } else if ("@odata.type".equals(fieldName)) { odataType = reader.getString(); } else { reader.skipChildren(); } } - if (keyFound) { - CognitiveServicesAccountKey deserializedCognitiveServicesAccountKey - = new CognitiveServicesAccountKey(key); - deserializedCognitiveServicesAccountKey.setDescription(description); - deserializedCognitiveServicesAccountKey.odataType = odataType; - return deserializedCognitiveServicesAccountKey; - } - throw new IllegalStateException("Missing required property: key"); - }); - } + CognitiveServicesAccountKey deserializedCognitiveServicesAccountKey = new CognitiveServicesAccountKey(key); + deserializedCognitiveServicesAccountKey.setDescription(description); + deserializedCognitiveServicesAccountKey.odataType = odataType; - /** - * Set the key property: The key used to provision the cognitive service resource attached to a skillset. - * - * @param key the key value to set. - * @return the CognitiveServicesAccountKey object itself. - */ - public CognitiveServicesAccountKey setKey(String key) { - this.key = key; - return this; + return deserializedCognitiveServicesAccountKey; + }); } } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/CommonGramTokenFilter.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/CommonGramTokenFilter.java similarity index 53% rename from sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/CommonGramTokenFilter.java rename to sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/CommonGramTokenFilter.java index f67249a9bbd8..3ab84b58c35b 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/CommonGramTokenFilter.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/CommonGramTokenFilter.java @@ -1,45 +1,50 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) TypeSpec Code Generator. -package com.azure.search.documents.indexes.models; +package com.azure.search.documents.models; import com.azure.core.annotation.Fluent; +import com.azure.core.annotation.Generated; import com.azure.json.JsonReader; import com.azure.json.JsonToken; import com.azure.json.JsonWriter; import java.io.IOException; -import java.util.ArrayList; import java.util.List; /** - * 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. + * 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. */ @Fluent public final class CommonGramTokenFilter extends TokenFilter { /* - * A URI fragment specifying the type of token filter. + * The discriminator for derived types. */ + @Generated private String odataType = "#Microsoft.Azure.Search.CommonGramTokenFilter"; /* * The set of common words. */ + @Generated private final List commonWords; /* - * A value indicating whether common words matching will be case insensitive. Default is false. + * A value indicating whether common words matching will be case insensitive. + * Default is false. */ - private Boolean caseIgnored; + @Generated + private Boolean ignoreCase; /* - * 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. + * 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. */ - private Boolean queryModeUsed; + @Generated + private Boolean useQueryMode; /** * Creates an instance of CommonGramTokenFilter class. @@ -47,16 +52,18 @@ public final class CommonGramTokenFilter extends TokenFilter { * @param name the name value to set. * @param commonWords the commonWords value to set. */ + @Generated public CommonGramTokenFilter(String name, List commonWords) { super(name); this.commonWords = commonWords; } /** - * Get the odataType property: A URI fragment specifying the type of token filter. + * Get the odataType property: The discriminator for derived types. * * @return the odataType value. */ + @Generated @Override public String getOdataType() { return this.odataType; @@ -67,67 +74,73 @@ public String getOdataType() { * * @return the commonWords value. */ + @Generated public List getCommonWords() { return this.commonWords; } /** - * Get the caseIgnored property: A value indicating whether common words matching will be case insensitive. Default - * is false. + * Get the ignoreCase property: A value indicating whether common words matching will be case insensitive. + * Default is false. * - * @return the caseIgnored value. + * @return the ignoreCase value. */ - public Boolean isCaseIgnored() { - return this.caseIgnored; + @Generated + public Boolean isIgnoreCase() { + return this.ignoreCase; } /** - * Set the caseIgnored property: A value indicating whether common words matching will be case insensitive. Default - * is false. + * Set the ignoreCase property: A value indicating whether common words matching will be case insensitive. + * Default is false. * - * @param caseIgnored the caseIgnored value to set. + * @param ignoreCase the ignoreCase value to set. * @return the CommonGramTokenFilter object itself. */ - public CommonGramTokenFilter setCaseIgnored(Boolean caseIgnored) { - this.caseIgnored = caseIgnored; + @Generated + public CommonGramTokenFilter setIgnoreCase(Boolean ignoreCase) { + this.ignoreCase = ignoreCase; return this; } /** - * Get the queryModeUsed property: 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. + * Get the useQueryMode property: 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. * - * @return the queryModeUsed value. + * @return the useQueryMode value. */ - public Boolean isQueryModeUsed() { - return this.queryModeUsed; + @Generated + public Boolean isUseQueryMode() { + return this.useQueryMode; } /** - * Set the queryModeUsed property: 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. + * Set the useQueryMode property: 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. * - * @param queryModeUsed the queryModeUsed value to set. + * @param useQueryMode the useQueryMode value to set. * @return the CommonGramTokenFilter object itself. */ - public CommonGramTokenFilter setQueryModeUsed(Boolean queryModeUsed) { - this.queryModeUsed = queryModeUsed; + @Generated + public CommonGramTokenFilter setUseQueryMode(Boolean useQueryMode) { + this.useQueryMode = useQueryMode; return this; } /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); jsonWriter.writeStringField("name", getName()); jsonWriter.writeArrayField("commonWords", this.commonWords, (writer, element) -> writer.writeString(element)); jsonWriter.writeStringField("@odata.type", this.odataType); - jsonWriter.writeBooleanField("ignoreCase", this.caseIgnored); - jsonWriter.writeBooleanField("queryMode", this.queryModeUsed); + jsonWriter.writeBooleanField("ignoreCase", this.ignoreCase); + jsonWriter.writeBooleanField("queryMode", this.useQueryMode); return jsonWriter.writeEndObject(); } @@ -140,53 +153,38 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { * @throws IllegalStateException If the deserialized JSON object was missing any required properties. * @throws IOException If an error occurs while reading the CommonGramTokenFilter. */ + @Generated public static CommonGramTokenFilter fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { - boolean nameFound = false; String name = null; - boolean commonWordsFound = false; List commonWords = null; String odataType = "#Microsoft.Azure.Search.CommonGramTokenFilter"; - Boolean caseIgnored = null; - Boolean queryModeUsed = null; + Boolean ignoreCase = null; + Boolean useQueryMode = null; while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); if ("name".equals(fieldName)) { name = reader.getString(); - nameFound = true; } else if ("commonWords".equals(fieldName)) { commonWords = reader.readArray(reader1 -> reader1.getString()); - commonWordsFound = true; } else if ("@odata.type".equals(fieldName)) { odataType = reader.getString(); } else if ("ignoreCase".equals(fieldName)) { - caseIgnored = reader.getNullable(JsonReader::getBoolean); + ignoreCase = reader.getNullable(JsonReader::getBoolean); } else if ("queryMode".equals(fieldName)) { - queryModeUsed = reader.getNullable(JsonReader::getBoolean); + useQueryMode = reader.getNullable(JsonReader::getBoolean); } else { reader.skipChildren(); } } - if (nameFound && commonWordsFound) { - CommonGramTokenFilter deserializedCommonGramTokenFilter = new CommonGramTokenFilter(name, commonWords); - deserializedCommonGramTokenFilter.odataType = odataType; - deserializedCommonGramTokenFilter.caseIgnored = caseIgnored; - deserializedCommonGramTokenFilter.queryModeUsed = queryModeUsed; + CommonGramTokenFilter deserializedCommonGramTokenFilter = new CommonGramTokenFilter(name, commonWords); + deserializedCommonGramTokenFilter.odataType = odataType; + deserializedCommonGramTokenFilter.ignoreCase = ignoreCase; + deserializedCommonGramTokenFilter.useQueryMode = useQueryMode; - return deserializedCommonGramTokenFilter; - } - List missingProperties = new ArrayList<>(); - if (!nameFound) { - missingProperties.add("name"); - } - if (!commonWordsFound) { - missingProperties.add("commonWords"); - } - - throw new IllegalStateException( - "Missing required property/properties: " + String.join(", ", missingProperties)); + return deserializedCommonGramTokenFilter; }); } } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/ConditionalSkill.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/ConditionalSkill.java similarity index 73% rename from sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/ConditionalSkill.java rename to sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/ConditionalSkill.java index 8a8087b26b2e..802cfe31b2ed 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/ConditionalSkill.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/ConditionalSkill.java @@ -1,27 +1,27 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) TypeSpec Code Generator. -package com.azure.search.documents.indexes.models; +package com.azure.search.documents.models; import com.azure.core.annotation.Fluent; +import com.azure.core.annotation.Generated; import com.azure.json.JsonReader; import com.azure.json.JsonToken; import com.azure.json.JsonWriter; import java.io.IOException; -import java.util.ArrayList; import java.util.List; /** - * A skill that enables scenarios that require a Boolean operation to determine the data to assign to an output. + * A skill that enables scenarios that require a Boolean operation to determine + * the data to assign to an output. */ @Fluent public final class ConditionalSkill extends SearchIndexerSkill { /* - * A URI fragment specifying the type of skill. + * The discriminator for derived types. */ + @Generated private String odataType = "#Microsoft.Skills.Util.ConditionalSkill"; /** @@ -30,15 +30,17 @@ public final class ConditionalSkill extends SearchIndexerSkill { * @param inputs the inputs value to set. * @param outputs the outputs value to set. */ + @Generated public ConditionalSkill(List inputs, List outputs) { super(inputs, outputs); } /** - * Get the odataType property: A URI fragment specifying the type of skill. + * Get the odataType property: The discriminator for derived types. * * @return the odataType value. */ + @Generated @Override public String getOdataType() { return this.odataType; @@ -47,6 +49,7 @@ public String getOdataType() { /** * {@inheritDoc} */ + @Generated @Override public ConditionalSkill setName(String name) { super.setName(name); @@ -56,6 +59,7 @@ public ConditionalSkill setName(String name) { /** * {@inheritDoc} */ + @Generated @Override public ConditionalSkill setDescription(String description) { super.setDescription(description); @@ -65,6 +69,7 @@ public ConditionalSkill setDescription(String description) { /** * {@inheritDoc} */ + @Generated @Override public ConditionalSkill setContext(String context) { super.setContext(context); @@ -74,6 +79,7 @@ public ConditionalSkill setContext(String context) { /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); @@ -95,11 +101,10 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { * @throws IllegalStateException If the deserialized JSON object was missing any required properties. * @throws IOException If an error occurs while reading the ConditionalSkill. */ + @Generated public static ConditionalSkill fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { - boolean inputsFound = false; List inputs = null; - boolean outputsFound = false; List outputs = null; String name = null; String description = null; @@ -111,10 +116,8 @@ public static ConditionalSkill fromJson(JsonReader jsonReader) throws IOExceptio if ("inputs".equals(fieldName)) { inputs = reader.readArray(reader1 -> InputFieldMappingEntry.fromJson(reader1)); - inputsFound = true; } else if ("outputs".equals(fieldName)) { outputs = reader.readArray(reader1 -> OutputFieldMappingEntry.fromJson(reader1)); - outputsFound = true; } else if ("name".equals(fieldName)) { name = reader.getString(); } else if ("description".equals(fieldName)) { @@ -127,25 +130,13 @@ public static ConditionalSkill fromJson(JsonReader jsonReader) throws IOExceptio reader.skipChildren(); } } - if (inputsFound && outputsFound) { - ConditionalSkill deserializedConditionalSkill = new ConditionalSkill(inputs, outputs); - deserializedConditionalSkill.setName(name); - deserializedConditionalSkill.setDescription(description); - deserializedConditionalSkill.setContext(context); - deserializedConditionalSkill.odataType = odataType; + ConditionalSkill deserializedConditionalSkill = new ConditionalSkill(inputs, outputs); + deserializedConditionalSkill.setName(name); + deserializedConditionalSkill.setDescription(description); + deserializedConditionalSkill.setContext(context); + deserializedConditionalSkill.odataType = odataType; - return deserializedConditionalSkill; - } - List missingProperties = new ArrayList<>(); - if (!inputsFound) { - missingProperties.add("inputs"); - } - if (!outputsFound) { - missingProperties.add("outputs"); - } - - throw new IllegalStateException( - "Missing required property/properties: " + String.join(", ", missingProperties)); + return deserializedConditionalSkill; }); } } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/CorsOptions.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/CorsOptions.java similarity index 77% rename from sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/CorsOptions.java rename to sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/CorsOptions.java index c19eae8af88f..d6b6b47bb233 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/CorsOptions.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/CorsOptions.java @@ -1,12 +1,11 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) TypeSpec Code Generator. -package com.azure.search.documents.indexes.models; +package com.azure.search.documents.models; import com.azure.core.annotation.Fluent; +import com.azure.core.annotation.Generated; import com.azure.json.JsonReader; import com.azure.json.JsonSerializable; import com.azure.json.JsonToken; @@ -20,15 +19,19 @@ @Fluent public final class CorsOptions implements JsonSerializable { /* - * 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). + * 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). */ + @Generated private final List allowedOrigins; /* - * The duration for which browsers should cache CORS preflight responses. Defaults to 5 minutes. + * The duration for which browsers should cache CORS preflight responses. Defaults + * to 5 minutes. */ + @Generated private Long maxAgeInSeconds; /** @@ -36,17 +39,20 @@ public final class CorsOptions implements JsonSerializable { * * @param allowedOrigins the allowedOrigins value to set. */ + @Generated public CorsOptions(List allowedOrigins) { this.allowedOrigins = allowedOrigins; } /** * Get the allowedOrigins property: 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). + * 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). * * @return the allowedOrigins value. */ + @Generated public List getAllowedOrigins() { return this.allowedOrigins; } @@ -57,6 +63,7 @@ public List getAllowedOrigins() { * * @return the maxAgeInSeconds value. */ + @Generated public Long getMaxAgeInSeconds() { return this.maxAgeInSeconds; } @@ -68,6 +75,7 @@ public Long getMaxAgeInSeconds() { * @param maxAgeInSeconds the maxAgeInSeconds value to set. * @return the CorsOptions object itself. */ + @Generated public CorsOptions setMaxAgeInSeconds(Long maxAgeInSeconds) { this.maxAgeInSeconds = maxAgeInSeconds; return this; @@ -76,6 +84,7 @@ public CorsOptions setMaxAgeInSeconds(Long maxAgeInSeconds) { /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); @@ -94,9 +103,9 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { * @throws IllegalStateException If the deserialized JSON object was missing any required properties. * @throws IOException If an error occurs while reading the CorsOptions. */ + @Generated public static CorsOptions fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { - boolean allowedOriginsFound = false; List allowedOrigins = null; Long maxAgeInSeconds = null; while (reader.nextToken() != JsonToken.END_OBJECT) { @@ -105,20 +114,16 @@ public static CorsOptions fromJson(JsonReader jsonReader) throws IOException { if ("allowedOrigins".equals(fieldName)) { allowedOrigins = reader.readArray(reader1 -> reader1.getString()); - allowedOriginsFound = true; } else if ("maxAgeInSeconds".equals(fieldName)) { maxAgeInSeconds = reader.getNullable(JsonReader::getLong); } else { reader.skipChildren(); } } - if (allowedOriginsFound) { - CorsOptions deserializedCorsOptions = new CorsOptions(allowedOrigins); - deserializedCorsOptions.maxAgeInSeconds = maxAgeInSeconds; + CorsOptions deserializedCorsOptions = new CorsOptions(allowedOrigins); + deserializedCorsOptions.maxAgeInSeconds = maxAgeInSeconds; - return deserializedCorsOptions; - } - throw new IllegalStateException("Missing required property: allowedOrigins"); + return deserializedCorsOptions; }); } } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/CustomAnalyzer.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/CustomAnalyzer.java similarity index 58% rename from sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/CustomAnalyzer.java rename to sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/CustomAnalyzer.java index 98d568402d4c..59be2b4dd543 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/CustomAnalyzer.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/CustomAnalyzer.java @@ -1,125 +1,139 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. -package com.azure.search.documents.indexes.models; +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.search.documents.models; import com.azure.core.annotation.Fluent; +import com.azure.core.annotation.Generated; import com.azure.json.JsonReader; import com.azure.json.JsonToken; import com.azure.json.JsonWriter; import java.io.IOException; -import java.util.ArrayList; -import java.util.Arrays; import java.util.List; /** - * 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. + * 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. */ @Fluent public final class CustomAnalyzer extends LexicalAnalyzer { - /* - * A URI fragment specifying the type of analyzer. + * The discriminator for derived types. */ + @Generated private String odataType = "#Microsoft.Azure.Search.CustomAnalyzer"; /* - * The name of the tokenizer to use to divide continuous text into a sequence of tokens, such as breaking a sentence - * into words. + * The name of the tokenizer to use to divide continuous text into a sequence of + * tokens, such as breaking a sentence into words. */ + @Generated private final LexicalTokenizerName tokenizer; /* - * 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. + * 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. */ + @Generated private List tokenFilters; /* - * 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. + * 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. */ + @Generated private List charFilters; /** * Creates an instance of CustomAnalyzer class. - * + * * @param name the name value to set. * @param tokenizer the tokenizer value to set. */ + @Generated public CustomAnalyzer(String name, LexicalTokenizerName tokenizer) { super(name); this.tokenizer = tokenizer; } /** - * Get the odataType property: A URI fragment specifying the type of analyzer. - * + * Get the odataType property: The discriminator for derived types. + * * @return the odataType value. */ + @Generated @Override public String getOdataType() { return this.odataType; } /** - * Get the tokenizer property: The name of the tokenizer to use to divide continuous text into a sequence of tokens, - * such as breaking a sentence into words. - * + * Get the tokenizer property: The name of the tokenizer to use to divide continuous text into a sequence of + * tokens, such as breaking a sentence into words. + * * @return the tokenizer value. */ + @Generated public LexicalTokenizerName getTokenizer() { return this.tokenizer; } /** * Get the tokenFilters property: 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. - * + * 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. + * * @return the tokenFilters value. */ + @Generated public List getTokenFilters() { return this.tokenFilters; } /** * Set the tokenFilters property: 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. - * + * 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. + * * @param tokenFilters the tokenFilters value to set. * @return the CustomAnalyzer object itself. */ + @Generated public CustomAnalyzer setTokenFilters(List tokenFilters) { this.tokenFilters = tokenFilters; return this; } /** - * Get the charFilters property: 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. - * + * Get the charFilters property: 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. + * * @return the charFilters value. */ + @Generated public List getCharFilters() { return this.charFilters; } /** - * Set the charFilters property: 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. - * + * Set the charFilters property: 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. + * * @param charFilters the charFilters value to set. * @return the CustomAnalyzer object itself. */ + @Generated public CustomAnalyzer setCharFilters(List charFilters) { this.charFilters = charFilters; return this; @@ -128,6 +142,7 @@ public CustomAnalyzer setCharFilters(List charFilters) { /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); @@ -143,18 +158,17 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of CustomAnalyzer from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of CustomAnalyzer if the JsonReader was pointing to an instance of it, or null if it was * pointing to JSON null. * @throws IllegalStateException If the deserialized JSON object was missing any required properties. * @throws IOException If an error occurs while reading the CustomAnalyzer. */ + @Generated public static CustomAnalyzer fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { - boolean nameFound = false; String name = null; - boolean tokenizerFound = false; LexicalTokenizerName tokenizer = null; String odataType = "#Microsoft.Azure.Search.CustomAnalyzer"; List tokenFilters = null; @@ -162,12 +176,11 @@ public static CustomAnalyzer fromJson(JsonReader jsonReader) throws IOException while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); + if ("name".equals(fieldName)) { name = reader.getString(); - nameFound = true; } else if ("tokenizer".equals(fieldName)) { tokenizer = LexicalTokenizerName.fromString(reader.getString()); - tokenizerFound = true; } else if ("@odata.type".equals(fieldName)) { odataType = reader.getString(); } else if ("tokenFilters".equals(fieldName)) { @@ -178,48 +191,12 @@ public static CustomAnalyzer fromJson(JsonReader jsonReader) throws IOException reader.skipChildren(); } } - if (nameFound && tokenizerFound) { - CustomAnalyzer deserializedCustomAnalyzer = new CustomAnalyzer(name, tokenizer); - deserializedCustomAnalyzer.odataType = odataType; - deserializedCustomAnalyzer.tokenFilters = tokenFilters; - deserializedCustomAnalyzer.charFilters = charFilters; - return deserializedCustomAnalyzer; - } - List missingProperties = new ArrayList<>(); - if (!nameFound) { - missingProperties.add("name"); - } - if (!tokenizerFound) { - missingProperties.add("tokenizer"); - } - throw new IllegalStateException( - "Missing required property/properties: " + String.join(", ", missingProperties)); - }); - } - - /** - * Set the tokenFilters property: 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. - * - * @param tokenFilters the tokenFilters value to set. - * @return the CustomAnalyzer object itself. - */ - public CustomAnalyzer setTokenFilters(TokenFilterName... tokenFilters) { - this.tokenFilters = (tokenFilters == null) ? null : Arrays.asList(tokenFilters); - return this; - } + CustomAnalyzer deserializedCustomAnalyzer = new CustomAnalyzer(name, tokenizer); + deserializedCustomAnalyzer.odataType = odataType; + deserializedCustomAnalyzer.tokenFilters = tokenFilters; + deserializedCustomAnalyzer.charFilters = charFilters; - /** - * Set the charFilters property: 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. - * - * @param charFilters the charFilters value to set. - * @return the CustomAnalyzer object itself. - */ - public CustomAnalyzer setCharFilters(CharFilterName... charFilters) { - this.charFilters = (charFilters == null) ? null : Arrays.asList(charFilters); - return this; + return deserializedCustomAnalyzer; + }); } } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/CustomEntity.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/CustomEntity.java similarity index 70% rename from sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/CustomEntity.java rename to sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/CustomEntity.java index 179cf1faf472..a32e19ba725c 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/CustomEntity.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/CustomEntity.java @@ -1,12 +1,11 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) TypeSpec Code Generator. -package com.azure.search.documents.indexes.models; +package com.azure.search.documents.models; import com.azure.core.annotation.Fluent; +import com.azure.core.annotation.Generated; import com.azure.json.JsonReader; import com.azure.json.JsonSerializable; import com.azure.json.JsonToken; @@ -15,82 +14,103 @@ import java.util.List; /** - * An object that contains information about the matches that were found, and related metadata. + * An object that contains information about the matches that were found, and + * related metadata. */ @Fluent public final class CustomEntity implements JsonSerializable { /* - * 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. + * 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. */ + @Generated private final String name; /* - * 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. + * 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. */ + @Generated private String 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. + * 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. */ + @Generated private String 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. + * 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. */ + @Generated private String 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. + * 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. */ + @Generated private String id; /* - * 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. + * 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. */ + @Generated private Boolean caseSensitive; /* - * Defaults to false. Boolean value denoting whether comparisons with the entity name should be sensitive to accent. + * Defaults to false. Boolean value denoting whether comparisons with the entity + * name should be sensitive to accent. */ + @Generated private Boolean accentSensitive; /* - * 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. - */ + * 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. + */ + @Generated private Integer fuzzyEditDistance; /* - * Changes the default case sensitivity value for this entity. It be used to change the default value of all aliases - * caseSensitive values. + * Changes the default case sensitivity value for this entity. It be used to + * change the default value of all aliases caseSensitive values. */ + @Generated private Boolean defaultCaseSensitive; /* - * Changes the default accent sensitivity value for this entity. It be used to change the default value of all - * aliases accentSensitive values. + * Changes the default accent sensitivity value for this entity. It be used to + * change the default value of all aliases accentSensitive values. */ + @Generated private Boolean defaultAccentSensitive; /* - * Changes the default fuzzy edit distance value for this entity. It can be used to change the default value of all - * aliases fuzzyEditDistance values. + * Changes the default fuzzy edit distance value for this entity. It can be used + * to change the default value of all aliases fuzzyEditDistance values. */ + @Generated private Integer defaultFuzzyEditDistance; /* - * An array of complex objects that can be used to specify alternative spellings or synonyms to the root entity - * name. + * An array of complex objects that can be used to specify alternative spellings + * or synonyms to the root entity name. */ + @Generated private List aliases; /** @@ -98,103 +118,122 @@ public final class CustomEntity implements JsonSerializable { * * @param name the name value to set. */ + @Generated public CustomEntity(String name) { this.name = name; } /** - * Get the name property: 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. + * Get the name property: 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. * * @return the name value. */ + @Generated public String getName() { return this.name; } /** * Get the description property: 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. + * text(s). The value of this field will appear with every match of its entity in + * the skill output. * * @return the description value. */ + @Generated public String getDescription() { return this.description; } /** * Set the description property: 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. + * text(s). The value of this field will appear with every match of its entity in + * the skill output. * * @param description the description value to set. * @return the CustomEntity object itself. */ + @Generated public CustomEntity setDescription(String description) { this.description = description; return this; } /** - * Get the type property: 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. + * Get the type property: 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. * * @return the type value. */ + @Generated public String getType() { return this.type; } /** - * Set the type property: 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. + * Set the type property: 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. * * @param type the type value to set. * @return the CustomEntity object itself. */ + @Generated public CustomEntity setType(String type) { this.type = type; return this; } /** - * Get the subtype property: 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. + * Get the subtype property: 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. * * @return the subtype value. */ + @Generated public String getSubtype() { return this.subtype; } /** - * Set the subtype property: 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. + * Set the subtype property: 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. * * @param subtype the subtype value to set. * @return the CustomEntity object itself. */ + @Generated public CustomEntity setSubtype(String subtype) { this.subtype = subtype; return this; } /** - * Get the id property: 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. + * Get the id property: 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. * * @return the id value. */ + @Generated public String getId() { return this.id; } /** - * Set the id property: 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. + * Set the id property: 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. * * @param id the id value to set. * @return the CustomEntity object itself. */ + @Generated public CustomEntity setId(String id) { this.id = id; return this; @@ -202,23 +241,25 @@ public CustomEntity setId(String id) { /** * Get the caseSensitive property: 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. + * name should be sensitive to character casing. Sample case insensitive matches + * of "Microsoft" could be: microsoft, microSoft, MICROSOFT. * * @return the caseSensitive value. */ + @Generated public Boolean isCaseSensitive() { return this.caseSensitive; } /** * Set the caseSensitive property: 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. + * name should be sensitive to character casing. Sample case insensitive matches + * of "Microsoft" could be: microsoft, microSoft, MICROSOFT. * * @param caseSensitive the caseSensitive value to set. * @return the CustomEntity object itself. */ + @Generated public CustomEntity setCaseSensitive(Boolean caseSensitive) { this.caseSensitive = caseSensitive; return this; @@ -230,6 +271,7 @@ public CustomEntity setCaseSensitive(Boolean caseSensitive) { * * @return the accentSensitive value. */ + @Generated public Boolean isAccentSensitive() { return this.accentSensitive; } @@ -241,6 +283,7 @@ public Boolean isAccentSensitive() { * @param accentSensitive the accentSensitive value to set. * @return the CustomEntity object itself. */ + @Generated public CustomEntity setAccentSensitive(Boolean accentSensitive) { this.accentSensitive = accentSensitive; return this; @@ -248,27 +291,31 @@ public CustomEntity setAccentSensitive(Boolean accentSensitive) { /** * Get the fuzzyEditDistance property: 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. + * 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. * * @return the fuzzyEditDistance value. */ + @Generated public Integer getFuzzyEditDistance() { return this.fuzzyEditDistance; } /** * Set the fuzzyEditDistance property: 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. + * 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. * * @param fuzzyEditDistance the fuzzyEditDistance value to set. * @return the CustomEntity object itself. */ + @Generated public CustomEntity setFuzzyEditDistance(Integer fuzzyEditDistance) { this.fuzzyEditDistance = fuzzyEditDistance; return this; @@ -280,6 +327,7 @@ public CustomEntity setFuzzyEditDistance(Integer fuzzyEditDistance) { * * @return the defaultCaseSensitive value. */ + @Generated public Boolean isDefaultCaseSensitive() { return this.defaultCaseSensitive; } @@ -291,6 +339,7 @@ public Boolean isDefaultCaseSensitive() { * @param defaultCaseSensitive the defaultCaseSensitive value to set. * @return the CustomEntity object itself. */ + @Generated public CustomEntity setDefaultCaseSensitive(Boolean defaultCaseSensitive) { this.defaultCaseSensitive = defaultCaseSensitive; return this; @@ -298,21 +347,25 @@ public CustomEntity setDefaultCaseSensitive(Boolean defaultCaseSensitive) { /** * Get the defaultAccentSensitive property: Changes the default accent sensitivity value for this entity. It be used - * to change the default value of all aliases accentSensitive values. + * to + * change the default value of all aliases accentSensitive values. * * @return the defaultAccentSensitive value. */ + @Generated public Boolean isDefaultAccentSensitive() { return this.defaultAccentSensitive; } /** * Set the defaultAccentSensitive property: Changes the default accent sensitivity value for this entity. It be used - * to change the default value of all aliases accentSensitive values. + * to + * change the default value of all aliases accentSensitive values. * * @param defaultAccentSensitive the defaultAccentSensitive value to set. * @return the CustomEntity object itself. */ + @Generated public CustomEntity setDefaultAccentSensitive(Boolean defaultAccentSensitive) { this.defaultAccentSensitive = defaultAccentSensitive; return this; @@ -320,43 +373,49 @@ public CustomEntity setDefaultAccentSensitive(Boolean defaultAccentSensitive) { /** * Get the defaultFuzzyEditDistance property: Changes the default fuzzy edit distance value for this entity. It can - * be used to change the default value of all aliases fuzzyEditDistance values. + * be used + * to change the default value of all aliases fuzzyEditDistance values. * * @return the defaultFuzzyEditDistance value. */ + @Generated public Integer getDefaultFuzzyEditDistance() { return this.defaultFuzzyEditDistance; } /** * Set the defaultFuzzyEditDistance property: Changes the default fuzzy edit distance value for this entity. It can - * be used to change the default value of all aliases fuzzyEditDistance values. + * be used + * to change the default value of all aliases fuzzyEditDistance values. * * @param defaultFuzzyEditDistance the defaultFuzzyEditDistance value to set. * @return the CustomEntity object itself. */ + @Generated public CustomEntity setDefaultFuzzyEditDistance(Integer defaultFuzzyEditDistance) { this.defaultFuzzyEditDistance = defaultFuzzyEditDistance; return this; } /** - * Get the aliases property: An array of complex objects that can be used to specify alternative spellings or - * synonyms to the root entity name. + * Get the aliases property: An array of complex objects that can be used to specify alternative spellings + * or synonyms to the root entity name. * * @return the aliases value. */ + @Generated public List getAliases() { return this.aliases; } /** - * Set the aliases property: An array of complex objects that can be used to specify alternative spellings or - * synonyms to the root entity name. + * Set the aliases property: An array of complex objects that can be used to specify alternative spellings + * or synonyms to the root entity name. * * @param aliases the aliases value to set. * @return the CustomEntity object itself. */ + @Generated public CustomEntity setAliases(List aliases) { this.aliases = aliases; return this; @@ -365,6 +424,7 @@ public CustomEntity setAliases(List aliases) { /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); @@ -392,9 +452,9 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { * @throws IllegalStateException If the deserialized JSON object was missing any required properties. * @throws IOException If an error occurs while reading the CustomEntity. */ + @Generated public static CustomEntity fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { - boolean nameFound = false; String name = null; String description = null; String type = null; @@ -413,7 +473,6 @@ public static CustomEntity fromJson(JsonReader jsonReader) throws IOException { if ("name".equals(fieldName)) { name = reader.getString(); - nameFound = true; } else if ("description".equals(fieldName)) { description = reader.getString(); } else if ("type".equals(fieldName)) { @@ -440,23 +499,20 @@ public static CustomEntity fromJson(JsonReader jsonReader) throws IOException { reader.skipChildren(); } } - if (nameFound) { - CustomEntity deserializedCustomEntity = new CustomEntity(name); - deserializedCustomEntity.description = description; - deserializedCustomEntity.type = type; - deserializedCustomEntity.subtype = subtype; - deserializedCustomEntity.id = id; - deserializedCustomEntity.caseSensitive = caseSensitive; - deserializedCustomEntity.accentSensitive = accentSensitive; - deserializedCustomEntity.fuzzyEditDistance = fuzzyEditDistance; - deserializedCustomEntity.defaultCaseSensitive = defaultCaseSensitive; - deserializedCustomEntity.defaultAccentSensitive = defaultAccentSensitive; - deserializedCustomEntity.defaultFuzzyEditDistance = defaultFuzzyEditDistance; - deserializedCustomEntity.aliases = aliases; - - return deserializedCustomEntity; - } - throw new IllegalStateException("Missing required property: name"); + CustomEntity deserializedCustomEntity = new CustomEntity(name); + deserializedCustomEntity.description = description; + deserializedCustomEntity.type = type; + deserializedCustomEntity.subtype = subtype; + deserializedCustomEntity.id = id; + deserializedCustomEntity.caseSensitive = caseSensitive; + deserializedCustomEntity.accentSensitive = accentSensitive; + deserializedCustomEntity.fuzzyEditDistance = fuzzyEditDistance; + deserializedCustomEntity.defaultCaseSensitive = defaultCaseSensitive; + deserializedCustomEntity.defaultAccentSensitive = defaultAccentSensitive; + deserializedCustomEntity.defaultFuzzyEditDistance = defaultFuzzyEditDistance; + deserializedCustomEntity.aliases = aliases; + + return deserializedCustomEntity; }); } } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/CustomEntityAlias.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/CustomEntityAlias.java similarity index 86% rename from sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/CustomEntityAlias.java rename to sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/CustomEntityAlias.java index 4c04c2f994d0..00175f21c435 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/CustomEntityAlias.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/CustomEntityAlias.java @@ -1,12 +1,11 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) TypeSpec Code Generator. -package com.azure.search.documents.indexes.models; +package com.azure.search.documents.models; import com.azure.core.annotation.Fluent; +import com.azure.core.annotation.Generated; import com.azure.json.JsonReader; import com.azure.json.JsonSerializable; import com.azure.json.JsonToken; @@ -14,28 +13,33 @@ import java.io.IOException; /** - * A complex object that can be used to specify alternative spellings or synonyms to the root entity name. + * A complex object that can be used to specify alternative spellings or synonyms + * to the root entity name. */ @Fluent public final class CustomEntityAlias implements JsonSerializable { /* * The text of the alias. */ + @Generated private final String text; /* * Determine if the alias is case sensitive. */ + @Generated private Boolean caseSensitive; /* * Determine if the alias is accent sensitive. */ + @Generated private Boolean accentSensitive; /* * Determine the fuzzy edit distance of the alias. */ + @Generated private Integer fuzzyEditDistance; /** @@ -43,6 +47,7 @@ public final class CustomEntityAlias implements JsonSerializable { - boolean textFound = false; String text = null; Boolean caseSensitive = null; Boolean accentSensitive = null; @@ -151,7 +164,6 @@ public static CustomEntityAlias fromJson(JsonReader jsonReader) throws IOExcepti if ("text".equals(fieldName)) { text = reader.getString(); - textFound = true; } else if ("caseSensitive".equals(fieldName)) { caseSensitive = reader.getNullable(JsonReader::getBoolean); } else if ("accentSensitive".equals(fieldName)) { @@ -162,15 +174,12 @@ public static CustomEntityAlias fromJson(JsonReader jsonReader) throws IOExcepti reader.skipChildren(); } } - if (textFound) { - CustomEntityAlias deserializedCustomEntityAlias = new CustomEntityAlias(text); - deserializedCustomEntityAlias.caseSensitive = caseSensitive; - deserializedCustomEntityAlias.accentSensitive = accentSensitive; - deserializedCustomEntityAlias.fuzzyEditDistance = fuzzyEditDistance; + CustomEntityAlias deserializedCustomEntityAlias = new CustomEntityAlias(text); + deserializedCustomEntityAlias.caseSensitive = caseSensitive; + deserializedCustomEntityAlias.accentSensitive = accentSensitive; + deserializedCustomEntityAlias.fuzzyEditDistance = fuzzyEditDistance; - return deserializedCustomEntityAlias; - } - throw new IllegalStateException("Missing required property: text"); + return deserializedCustomEntityAlias; }); } } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/CustomEntityLookupSkill.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/CustomEntityLookupSkill.java similarity index 74% rename from sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/CustomEntityLookupSkill.java rename to sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/CustomEntityLookupSkill.java index 268f3f1f082c..3fe4f8c5ddf4 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/CustomEntityLookupSkill.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/CustomEntityLookupSkill.java @@ -1,17 +1,15 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. -package com.azure.search.documents.indexes.models; +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.search.documents.models; import com.azure.core.annotation.Fluent; +import com.azure.core.annotation.Generated; import com.azure.json.JsonReader; import com.azure.json.JsonToken; import com.azure.json.JsonWriter; import java.io.IOException; -import java.util.ArrayList; -import java.util.Arrays; import java.util.List; /** @@ -19,62 +17,71 @@ */ @Fluent public final class CustomEntityLookupSkill extends SearchIndexerSkill { - /* - * A URI fragment specifying the type of skill. + * The discriminator for derived types. */ + @Generated private String odataType = "#Microsoft.Skills.Text.CustomEntityLookupSkill"; /* * A value indicating which language code to use. Default is `en`. */ + @Generated private CustomEntityLookupSkillLanguage defaultLanguageCode; /* - * 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. + * 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. */ + @Generated private String entitiesDefinitionUri; /* * The inline CustomEntity definition. */ + @Generated private List inlineEntitiesDefinition; /* - * A global flag for CaseSensitive. If CaseSensitive is not set in CustomEntity, this value will be the default - * value. + * A global flag for CaseSensitive. If CaseSensitive is not set in CustomEntity, + * this value will be the default value. */ + @Generated private Boolean globalDefaultCaseSensitive; /* - * A global flag for AccentSensitive. If AccentSensitive is not set in CustomEntity, this value will be the default - * value. + * A global flag for AccentSensitive. If AccentSensitive is not set in + * CustomEntity, this value will be the default value. */ + @Generated private Boolean globalDefaultAccentSensitive; /* - * A global flag for FuzzyEditDistance. If FuzzyEditDistance is not set in CustomEntity, this value will be the - * default value. + * A global flag for FuzzyEditDistance. If FuzzyEditDistance is not set in + * CustomEntity, this value will be the default value. */ + @Generated private Integer globalDefaultFuzzyEditDistance; /** * Creates an instance of CustomEntityLookupSkill class. - * + * * @param inputs the inputs value to set. * @param outputs the outputs value to set. */ + @Generated public CustomEntityLookupSkill(List inputs, List outputs) { super(inputs, outputs); } /** - * Get the odataType property: A URI fragment specifying the type of skill. - * + * Get the odataType property: The discriminator for derived types. + * * @return the odataType value. */ + @Generated @Override public String getOdataType() { return this.odataType; @@ -82,19 +89,21 @@ public String getOdataType() { /** * Get the defaultLanguageCode property: A value indicating which language code to use. Default is `en`. - * + * * @return the defaultLanguageCode value. */ + @Generated public CustomEntityLookupSkillLanguage getDefaultLanguageCode() { return this.defaultLanguageCode; } /** * Set the defaultLanguageCode property: A value indicating which language code to use. Default is `en`. - * + * * @param defaultLanguageCode the defaultLanguageCode value to set. * @return the CustomEntityLookupSkill object itself. */ + @Generated public CustomEntityLookupSkill setDefaultLanguageCode(CustomEntityLookupSkillLanguage defaultLanguageCode) { this.defaultLanguageCode = defaultLanguageCode; return this; @@ -102,23 +111,29 @@ public CustomEntityLookupSkill setDefaultLanguageCode(CustomEntityLookupSkillLan /** * Get the entitiesDefinitionUri property: 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. - * + * 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. + * * @return the entitiesDefinitionUri value. */ + @Generated public String getEntitiesDefinitionUri() { return this.entitiesDefinitionUri; } /** * Set the entitiesDefinitionUri property: 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. - * + * 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. + * * @param entitiesDefinitionUri the entitiesDefinitionUri value to set. * @return the CustomEntityLookupSkill object itself. */ + @Generated public CustomEntityLookupSkill setEntitiesDefinitionUri(String entitiesDefinitionUri) { this.entitiesDefinitionUri = entitiesDefinitionUri; return this; @@ -126,19 +141,21 @@ public CustomEntityLookupSkill setEntitiesDefinitionUri(String entitiesDefinitio /** * Get the inlineEntitiesDefinition property: The inline CustomEntity definition. - * + * * @return the inlineEntitiesDefinition value. */ + @Generated public List getInlineEntitiesDefinition() { return this.inlineEntitiesDefinition; } /** * Set the inlineEntitiesDefinition property: The inline CustomEntity definition. - * + * * @param inlineEntitiesDefinition the inlineEntitiesDefinition value to set. * @return the CustomEntityLookupSkill object itself. */ + @Generated public CustomEntityLookupSkill setInlineEntitiesDefinition(List inlineEntitiesDefinition) { this.inlineEntitiesDefinition = inlineEntitiesDefinition; return this; @@ -146,21 +163,25 @@ public CustomEntityLookupSkill setInlineEntitiesDefinition(List in /** * Get the globalDefaultCaseSensitive property: A global flag for CaseSensitive. If CaseSensitive is not set in - * CustomEntity, this value will be the default value. - * + * CustomEntity, + * this value will be the default value. + * * @return the globalDefaultCaseSensitive value. */ + @Generated public Boolean isGlobalDefaultCaseSensitive() { return this.globalDefaultCaseSensitive; } /** * Set the globalDefaultCaseSensitive property: A global flag for CaseSensitive. If CaseSensitive is not set in - * CustomEntity, this value will be the default value. - * + * CustomEntity, + * this value will be the default value. + * * @param globalDefaultCaseSensitive the globalDefaultCaseSensitive value to set. * @return the CustomEntityLookupSkill object itself. */ + @Generated public CustomEntityLookupSkill setGlobalDefaultCaseSensitive(Boolean globalDefaultCaseSensitive) { this.globalDefaultCaseSensitive = globalDefaultCaseSensitive; return this; @@ -168,21 +189,25 @@ public CustomEntityLookupSkill setGlobalDefaultCaseSensitive(Boolean globalDefau /** * Get the globalDefaultAccentSensitive property: A global flag for AccentSensitive. If AccentSensitive is not set - * in CustomEntity, this value will be the default value. - * + * in + * CustomEntity, this value will be the default value. + * * @return the globalDefaultAccentSensitive value. */ + @Generated public Boolean isGlobalDefaultAccentSensitive() { return this.globalDefaultAccentSensitive; } /** * Set the globalDefaultAccentSensitive property: A global flag for AccentSensitive. If AccentSensitive is not set - * in CustomEntity, this value will be the default value. - * + * in + * CustomEntity, this value will be the default value. + * * @param globalDefaultAccentSensitive the globalDefaultAccentSensitive value to set. * @return the CustomEntityLookupSkill object itself. */ + @Generated public CustomEntityLookupSkill setGlobalDefaultAccentSensitive(Boolean globalDefaultAccentSensitive) { this.globalDefaultAccentSensitive = globalDefaultAccentSensitive; return this; @@ -190,21 +215,25 @@ public CustomEntityLookupSkill setGlobalDefaultAccentSensitive(Boolean globalDef /** * Get the globalDefaultFuzzyEditDistance property: A global flag for FuzzyEditDistance. If FuzzyEditDistance is not - * set in CustomEntity, this value will be the default value. - * + * set in + * CustomEntity, this value will be the default value. + * * @return the globalDefaultFuzzyEditDistance value. */ + @Generated public Integer getGlobalDefaultFuzzyEditDistance() { return this.globalDefaultFuzzyEditDistance; } /** * Set the globalDefaultFuzzyEditDistance property: A global flag for FuzzyEditDistance. If FuzzyEditDistance is not - * set in CustomEntity, this value will be the default value. - * + * set in + * CustomEntity, this value will be the default value. + * * @param globalDefaultFuzzyEditDistance the globalDefaultFuzzyEditDistance value to set. * @return the CustomEntityLookupSkill object itself. */ + @Generated public CustomEntityLookupSkill setGlobalDefaultFuzzyEditDistance(Integer globalDefaultFuzzyEditDistance) { this.globalDefaultFuzzyEditDistance = globalDefaultFuzzyEditDistance; return this; @@ -213,6 +242,7 @@ public CustomEntityLookupSkill setGlobalDefaultFuzzyEditDistance(Integer globalD /** * {@inheritDoc} */ + @Generated @Override public CustomEntityLookupSkill setName(String name) { super.setName(name); @@ -222,6 +252,7 @@ public CustomEntityLookupSkill setName(String name) { /** * {@inheritDoc} */ + @Generated @Override public CustomEntityLookupSkill setDescription(String description) { super.setDescription(description); @@ -231,6 +262,7 @@ public CustomEntityLookupSkill setDescription(String description) { /** * {@inheritDoc} */ + @Generated @Override public CustomEntityLookupSkill setContext(String context) { super.setContext(context); @@ -240,6 +272,7 @@ public CustomEntityLookupSkill setContext(String context) { /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); @@ -262,18 +295,17 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of CustomEntityLookupSkill from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of CustomEntityLookupSkill if the JsonReader was pointing to an instance of it, or null if it * was pointing to JSON null. * @throws IllegalStateException If the deserialized JSON object was missing any required properties. * @throws IOException If an error occurs while reading the CustomEntityLookupSkill. */ + @Generated public static CustomEntityLookupSkill fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { - boolean inputsFound = false; List inputs = null; - boolean outputsFound = false; List outputs = null; String name = null; String description = null; @@ -288,12 +320,11 @@ public static CustomEntityLookupSkill fromJson(JsonReader jsonReader) throws IOE while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); + if ("inputs".equals(fieldName)) { inputs = reader.readArray(reader1 -> InputFieldMappingEntry.fromJson(reader1)); - inputsFound = true; } else if ("outputs".equals(fieldName)) { outputs = reader.readArray(reader1 -> OutputFieldMappingEntry.fromJson(reader1)); - outputsFound = true; } else if ("name".equals(fieldName)) { name = reader.getString(); } else if ("description".equals(fieldName)) { @@ -318,42 +349,19 @@ public static CustomEntityLookupSkill fromJson(JsonReader jsonReader) throws IOE reader.skipChildren(); } } - if (inputsFound && outputsFound) { - CustomEntityLookupSkill deserializedCustomEntityLookupSkill - = new CustomEntityLookupSkill(inputs, outputs); - deserializedCustomEntityLookupSkill.setName(name); - deserializedCustomEntityLookupSkill.setDescription(description); - deserializedCustomEntityLookupSkill.setContext(context); - deserializedCustomEntityLookupSkill.odataType = odataType; - deserializedCustomEntityLookupSkill.defaultLanguageCode = defaultLanguageCode; - deserializedCustomEntityLookupSkill.entitiesDefinitionUri = entitiesDefinitionUri; - deserializedCustomEntityLookupSkill.inlineEntitiesDefinition = inlineEntitiesDefinition; - deserializedCustomEntityLookupSkill.globalDefaultCaseSensitive = globalDefaultCaseSensitive; - deserializedCustomEntityLookupSkill.globalDefaultAccentSensitive = globalDefaultAccentSensitive; - deserializedCustomEntityLookupSkill.globalDefaultFuzzyEditDistance = globalDefaultFuzzyEditDistance; - return deserializedCustomEntityLookupSkill; - } - List missingProperties = new ArrayList<>(); - if (!inputsFound) { - missingProperties.add("inputs"); - } - if (!outputsFound) { - missingProperties.add("outputs"); - } - throw new IllegalStateException( - "Missing required property/properties: " + String.join(", ", missingProperties)); - }); - } + CustomEntityLookupSkill deserializedCustomEntityLookupSkill = new CustomEntityLookupSkill(inputs, outputs); + deserializedCustomEntityLookupSkill.setName(name); + deserializedCustomEntityLookupSkill.setDescription(description); + deserializedCustomEntityLookupSkill.setContext(context); + deserializedCustomEntityLookupSkill.odataType = odataType; + deserializedCustomEntityLookupSkill.defaultLanguageCode = defaultLanguageCode; + deserializedCustomEntityLookupSkill.entitiesDefinitionUri = entitiesDefinitionUri; + deserializedCustomEntityLookupSkill.inlineEntitiesDefinition = inlineEntitiesDefinition; + deserializedCustomEntityLookupSkill.globalDefaultCaseSensitive = globalDefaultCaseSensitive; + deserializedCustomEntityLookupSkill.globalDefaultAccentSensitive = globalDefaultAccentSensitive; + deserializedCustomEntityLookupSkill.globalDefaultFuzzyEditDistance = globalDefaultFuzzyEditDistance; - /** - * Set the inlineEntitiesDefinition property: The inline CustomEntity definition. - * - * @param inlineEntitiesDefinition the inlineEntitiesDefinition value to set. - * @return the CustomEntityLookupSkill object itself. - */ - public CustomEntityLookupSkill setInlineEntitiesDefinition(CustomEntity... inlineEntitiesDefinition) { - this.inlineEntitiesDefinition - = (inlineEntitiesDefinition == null) ? null : Arrays.asList(inlineEntitiesDefinition); - return this; + return deserializedCustomEntityLookupSkill; + }); } } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/CustomEntityLookupSkillLanguage.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/CustomEntityLookupSkillLanguage.java similarity index 87% rename from sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/CustomEntityLookupSkillLanguage.java rename to sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/CustomEntityLookupSkillLanguage.java index cb60360a4bb6..c664592ab7d7 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/CustomEntityLookupSkillLanguage.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/CustomEntityLookupSkillLanguage.java @@ -1,11 +1,10 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) TypeSpec Code Generator. -package com.azure.search.documents.indexes.models; +package com.azure.search.documents.models; +import com.azure.core.annotation.Generated; import com.azure.core.util.ExpandableStringEnum; import java.util.Collection; @@ -16,46 +15,55 @@ public final class CustomEntityLookupSkillLanguage extends ExpandableStringEnum< /** * Danish. */ + @Generated public static final CustomEntityLookupSkillLanguage DA = fromString("da"); /** * German. */ + @Generated public static final CustomEntityLookupSkillLanguage DE = fromString("de"); /** * English. */ + @Generated public static final CustomEntityLookupSkillLanguage EN = fromString("en"); /** * Spanish. */ + @Generated public static final CustomEntityLookupSkillLanguage ES = fromString("es"); /** * Finnish. */ + @Generated public static final CustomEntityLookupSkillLanguage FI = fromString("fi"); /** * French. */ + @Generated public static final CustomEntityLookupSkillLanguage FR = fromString("fr"); /** * Italian. */ + @Generated public static final CustomEntityLookupSkillLanguage IT = fromString("it"); /** * Korean. */ + @Generated public static final CustomEntityLookupSkillLanguage KO = fromString("ko"); /** * Portuguese. */ + @Generated public static final CustomEntityLookupSkillLanguage PT = fromString("pt"); /** @@ -63,6 +71,7 @@ public final class CustomEntityLookupSkillLanguage extends ExpandableStringEnum< * * @deprecated Use the {@link #fromString(String)} factory method. */ + @Generated @Deprecated public CustomEntityLookupSkillLanguage() { } @@ -73,6 +82,7 @@ public CustomEntityLookupSkillLanguage() { * @param name a name to look for. * @return the corresponding CustomEntityLookupSkillLanguage. */ + @Generated public static CustomEntityLookupSkillLanguage fromString(String name) { return fromString(name, CustomEntityLookupSkillLanguage.class); } @@ -82,6 +92,7 @@ public static CustomEntityLookupSkillLanguage fromString(String name) { * * @return known CustomEntityLookupSkillLanguage values. */ + @Generated public static Collection values() { return values(CustomEntityLookupSkillLanguage.class); } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/CustomNormalizer.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/CustomNormalizer.java similarity index 67% rename from sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/CustomNormalizer.java rename to sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/CustomNormalizer.java index 652e271e6d6a..019c98d02cb5 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/CustomNormalizer.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/CustomNormalizer.java @@ -1,12 +1,11 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) TypeSpec Code Generator. -package com.azure.search.documents.indexes.models; +package com.azure.search.documents.models; import com.azure.core.annotation.Fluent; +import com.azure.core.annotation.Generated; import com.azure.json.JsonReader; import com.azure.json.JsonToken; import com.azure.json.JsonWriter; @@ -14,27 +13,33 @@ import java.util.List; /** - * 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 + * 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. */ @Fluent public final class CustomNormalizer extends LexicalNormalizer { /* - * A URI fragment specifying the type of normalizer. + * The discriminator for derived types. */ + @Generated private String odataType = "#Microsoft.Azure.Search.CustomNormalizer"; /* - * 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. + * 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. */ + @Generated private List tokenFilters; /* - * 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. + * 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. */ + @Generated private List charFilters; /** @@ -42,63 +47,69 @@ public final class CustomNormalizer extends LexicalNormalizer { * * @param name the name value to set. */ + @Generated public CustomNormalizer(String name) { super(name); } /** - * Get the odataType property: A URI fragment specifying the type of normalizer. + * Get the odataType property: The discriminator for derived types. * * @return the odataType value. */ + @Generated @Override public String getOdataType() { return this.odataType; } /** - * Get the tokenFilters property: 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. + * Get the tokenFilters property: 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. * * @return the tokenFilters value. */ + @Generated public List getTokenFilters() { return this.tokenFilters; } /** - * Set the tokenFilters property: 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. + * Set the tokenFilters property: 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. * * @param tokenFilters the tokenFilters value to set. * @return the CustomNormalizer object itself. */ + @Generated public CustomNormalizer setTokenFilters(List tokenFilters) { this.tokenFilters = tokenFilters; return this; } /** - * Get the charFilters property: 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. + * Get the charFilters property: 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. * * @return the charFilters value. */ + @Generated public List getCharFilters() { return this.charFilters; } /** - * Set the charFilters property: 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. + * Set the charFilters property: 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. * * @param charFilters the charFilters value to set. * @return the CustomNormalizer object itself. */ + @Generated public CustomNormalizer setCharFilters(List charFilters) { this.charFilters = charFilters; return this; @@ -107,6 +118,7 @@ public CustomNormalizer setCharFilters(List charFilters) { /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); @@ -128,9 +140,9 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { * @throws IllegalStateException If the deserialized JSON object was missing any required properties. * @throws IOException If an error occurs while reading the CustomNormalizer. */ + @Generated public static CustomNormalizer fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { - boolean nameFound = false; String name = null; String odataType = "#Microsoft.Azure.Search.CustomNormalizer"; List tokenFilters = null; @@ -141,7 +153,6 @@ public static CustomNormalizer fromJson(JsonReader jsonReader) throws IOExceptio if ("name".equals(fieldName)) { name = reader.getString(); - nameFound = true; } else if ("@odata.type".equals(fieldName)) { odataType = reader.getString(); } else if ("tokenFilters".equals(fieldName)) { @@ -152,15 +163,12 @@ public static CustomNormalizer fromJson(JsonReader jsonReader) throws IOExceptio reader.skipChildren(); } } - if (nameFound) { - CustomNormalizer deserializedCustomNormalizer = new CustomNormalizer(name); - deserializedCustomNormalizer.odataType = odataType; - deserializedCustomNormalizer.tokenFilters = tokenFilters; - deserializedCustomNormalizer.charFilters = charFilters; + CustomNormalizer deserializedCustomNormalizer = new CustomNormalizer(name); + deserializedCustomNormalizer.odataType = odataType; + deserializedCustomNormalizer.tokenFilters = tokenFilters; + deserializedCustomNormalizer.charFilters = charFilters; - return deserializedCustomNormalizer; - } - throw new IllegalStateException("Missing required property: name"); + return deserializedCustomNormalizer; }); } } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/DataChangeDetectionPolicy.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/DataChangeDetectionPolicy.java similarity index 90% rename from sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/DataChangeDetectionPolicy.java rename to sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/DataChangeDetectionPolicy.java index bd8177a971c2..0113eb188926 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/DataChangeDetectionPolicy.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/DataChangeDetectionPolicy.java @@ -1,11 +1,10 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) TypeSpec Code Generator. -package com.azure.search.documents.indexes.models; +package com.azure.search.documents.models; +import com.azure.core.annotation.Generated; import com.azure.core.annotation.Immutable; import com.azure.json.JsonReader; import com.azure.json.JsonSerializable; @@ -19,21 +18,24 @@ @Immutable public class DataChangeDetectionPolicy implements JsonSerializable { /* - * A URI fragment specifying the type of data change detection policy. + * The discriminator for derived types. */ + @Generated private String odataType = "DataChangeDetectionPolicy"; /** * Creates an instance of DataChangeDetectionPolicy class. */ + @Generated public DataChangeDetectionPolicy() { } /** - * Get the odataType property: A URI fragment specifying the type of data change detection policy. + * Get the odataType property: The discriminator for derived types. * * @return the odataType value. */ + @Generated public String getOdataType() { return this.odataType; } @@ -41,6 +43,7 @@ public String getOdataType() { /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); @@ -56,6 +59,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { * it was pointing to JSON null. * @throws IOException If an error occurs while reading the DataChangeDetectionPolicy. */ + @Generated public static DataChangeDetectionPolicy fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { String discriminatorValue = null; @@ -83,6 +87,7 @@ public static DataChangeDetectionPolicy fromJson(JsonReader jsonReader) throws I }); } + @Generated static DataChangeDetectionPolicy fromJsonKnownDiscriminator(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { DataChangeDetectionPolicy deserializedDataChangeDetectionPolicy = new DataChangeDetectionPolicy(); diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/DataDeletionDetectionPolicy.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/DataDeletionDetectionPolicy.java similarity index 90% rename from sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/DataDeletionDetectionPolicy.java rename to sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/DataDeletionDetectionPolicy.java index 03aa1302dd7a..6ba37f2a2905 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/DataDeletionDetectionPolicy.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/DataDeletionDetectionPolicy.java @@ -1,11 +1,10 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) TypeSpec Code Generator. -package com.azure.search.documents.indexes.models; +package com.azure.search.documents.models; +import com.azure.core.annotation.Generated; import com.azure.core.annotation.Immutable; import com.azure.json.JsonReader; import com.azure.json.JsonSerializable; @@ -19,21 +18,24 @@ @Immutable public class DataDeletionDetectionPolicy implements JsonSerializable { /* - * A URI fragment specifying the type of data deletion detection policy. + * The discriminator for derived types. */ + @Generated private String odataType = "DataDeletionDetectionPolicy"; /** * Creates an instance of DataDeletionDetectionPolicy class. */ + @Generated public DataDeletionDetectionPolicy() { } /** - * Get the odataType property: A URI fragment specifying the type of data deletion detection policy. + * Get the odataType property: The discriminator for derived types. * * @return the odataType value. */ + @Generated public String getOdataType() { return this.odataType; } @@ -41,6 +43,7 @@ public String getOdataType() { /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); @@ -56,6 +59,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { * if it was pointing to JSON null. * @throws IOException If an error occurs while reading the DataDeletionDetectionPolicy. */ + @Generated public static DataDeletionDetectionPolicy fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { String discriminatorValue = null; @@ -84,6 +88,7 @@ public static DataDeletionDetectionPolicy fromJson(JsonReader jsonReader) throws }); } + @Generated static DataDeletionDetectionPolicy fromJsonKnownDiscriminator(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { DataDeletionDetectionPolicy deserializedDataDeletionDetectionPolicy = new DataDeletionDetectionPolicy(); diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/implementation/models/DataSourceCredentials.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/DataSourceCredentials.java similarity index 78% rename from sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/implementation/models/DataSourceCredentials.java rename to sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/DataSourceCredentials.java index 17bdf4ff102d..e0934fdeb4ff 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/implementation/models/DataSourceCredentials.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/DataSourceCredentials.java @@ -1,12 +1,11 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) TypeSpec Code Generator. -package com.azure.search.documents.indexes.implementation.models; +package com.azure.search.documents.models; import com.azure.core.annotation.Fluent; +import com.azure.core.annotation.Generated; import com.azure.json.JsonReader; import com.azure.json.JsonSerializable; import com.azure.json.JsonToken; @@ -19,36 +18,43 @@ @Fluent public final class DataSourceCredentials implements JsonSerializable { /* - * 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. + * 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. */ + @Generated private String connectionString; /** * Creates an instance of DataSourceCredentials class. */ + @Generated public DataSourceCredentials() { } /** * Get the connectionString property: The connection string for the datasource. Set to `<unchanged>` (with - * brackets) if you don't want the connection string updated. Set to `<redacted>` if you want to remove the - * connection string value from the datasource. + * brackets) + * if you don't want the connection string updated. Set to `<redacted>` if you + * want to remove the connection string value from the datasource. * * @return the connectionString value. */ + @Generated public String getConnectionString() { return this.connectionString; } /** * Set the connectionString property: The connection string for the datasource. Set to `<unchanged>` (with - * brackets) if you don't want the connection string updated. Set to `<redacted>` if you want to remove the - * connection string value from the datasource. + * brackets) + * if you don't want the connection string updated. Set to `<redacted>` if you + * want to remove the connection string value from the datasource. * * @param connectionString the connectionString value to set. * @return the DataSourceCredentials object itself. */ + @Generated public DataSourceCredentials setConnectionString(String connectionString) { this.connectionString = connectionString; return this; @@ -57,6 +63,7 @@ public DataSourceCredentials setConnectionString(String connectionString) { /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); @@ -72,6 +79,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { * was pointing to JSON null. * @throws IOException If an error occurs while reading the DataSourceCredentials. */ + @Generated public static DataSourceCredentials fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { DataSourceCredentials deserializedDataSourceCredentials = new DataSourceCredentials(); diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/DebugInfo.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/DebugInfo.java index e7b370d7a70f..fc09d81699f7 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/DebugInfo.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/DebugInfo.java @@ -1,11 +1,10 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.search.documents.models; +import com.azure.core.annotation.Generated; import com.azure.core.annotation.Immutable; import com.azure.json.JsonReader; import com.azure.json.JsonSerializable; @@ -14,19 +13,22 @@ import java.io.IOException; /** - * Contains debugging information that can be used to further explore your search results. + * Contains debugging information that can be used to further explore your search + * results. */ @Immutable public final class DebugInfo implements JsonSerializable { /* * Contains debugging information specific to query rewrites. */ + @Generated private QueryRewritesDebugInfo queryRewrites; /** * Creates an instance of DebugInfo class. */ - public DebugInfo() { + @Generated + private DebugInfo() { } /** @@ -34,6 +36,7 @@ public DebugInfo() { * * @return the queryRewrites value. */ + @Generated public QueryRewritesDebugInfo getQueryRewrites() { return this.queryRewrites; } @@ -41,6 +44,7 @@ public QueryRewritesDebugInfo getQueryRewrites() { /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); @@ -55,6 +59,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { * to JSON null. * @throws IOException If an error occurs while reading the DebugInfo. */ + @Generated public static DebugInfo fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { DebugInfo deserializedDebugInfo = new DebugInfo(); diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/DefaultCognitiveServicesAccount.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/DefaultCognitiveServicesAccount.java similarity index 85% rename from sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/DefaultCognitiveServicesAccount.java rename to sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/DefaultCognitiveServicesAccount.java index 608efdf697f1..b413ce6d6b44 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/DefaultCognitiveServicesAccount.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/DefaultCognitiveServicesAccount.java @@ -1,39 +1,41 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) TypeSpec Code Generator. -package com.azure.search.documents.indexes.models; +package com.azure.search.documents.models; import com.azure.core.annotation.Fluent; +import com.azure.core.annotation.Generated; import com.azure.json.JsonReader; import com.azure.json.JsonToken; import com.azure.json.JsonWriter; import java.io.IOException; /** - * An empty object that represents the default Azure AI service resource for a skillset. + * An empty object that represents the default Azure AI service resource for a + * skillset. */ @Fluent public final class DefaultCognitiveServicesAccount extends CognitiveServicesAccount { /* - * A URI fragment specifying the type of Azure AI service resource attached to a skillset. + * The discriminator for derived types. */ + @Generated private String odataType = "#Microsoft.Azure.Search.DefaultCognitiveServices"; /** * Creates an instance of DefaultCognitiveServicesAccount class. */ + @Generated public DefaultCognitiveServicesAccount() { } /** - * Get the odataType property: A URI fragment specifying the type of Azure AI service resource attached to a - * skillset. + * Get the odataType property: The discriminator for derived types. * * @return the odataType value. */ + @Generated @Override public String getOdataType() { return this.odataType; @@ -42,6 +44,7 @@ public String getOdataType() { /** * {@inheritDoc} */ + @Generated @Override public DefaultCognitiveServicesAccount setDescription(String description) { super.setDescription(description); @@ -51,6 +54,7 @@ public DefaultCognitiveServicesAccount setDescription(String description) { /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); @@ -67,6 +71,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { * null if it was pointing to JSON null. * @throws IOException If an error occurs while reading the DefaultCognitiveServicesAccount. */ + @Generated public static DefaultCognitiveServicesAccount fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { DefaultCognitiveServicesAccount deserializedDefaultCognitiveServicesAccount diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/DictionaryDecompounderTokenFilter.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/DictionaryDecompounderTokenFilter.java similarity index 71% rename from sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/DictionaryDecompounderTokenFilter.java rename to sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/DictionaryDecompounderTokenFilter.java index 0557eb40b21b..d3f9762e01e5 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/DictionaryDecompounderTokenFilter.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/DictionaryDecompounderTokenFilter.java @@ -1,53 +1,62 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) TypeSpec Code Generator. -package com.azure.search.documents.indexes.models; +package com.azure.search.documents.models; import com.azure.core.annotation.Fluent; +import com.azure.core.annotation.Generated; import com.azure.json.JsonReader; import com.azure.json.JsonToken; import com.azure.json.JsonWriter; import java.io.IOException; -import java.util.ArrayList; import java.util.List; /** - * Decomposes compound words found in many Germanic languages. This token filter is implemented using Apache Lucene. + * Decomposes compound words found in many Germanic languages. This token filter + * is implemented using Apache Lucene. */ @Fluent public final class DictionaryDecompounderTokenFilter extends TokenFilter { /* - * A URI fragment specifying the type of token filter. + * The discriminator for derived types. */ + @Generated private String odataType = "#Microsoft.Azure.Search.DictionaryDecompounderTokenFilter"; /* * The list of words to match against. */ + @Generated private final List wordList; /* - * The minimum word size. Only words longer than this get processed. Default is 5. Maximum is 300. + * The minimum word size. Only words longer than this get processed. Default is 5. + * Maximum is 300. */ + @Generated private Integer minWordSize; /* - * The minimum subword size. Only subwords longer than this are outputted. Default is 2. Maximum is 300. + * The minimum subword size. Only subwords longer than this are outputted. Default + * is 2. Maximum is 300. */ + @Generated private Integer minSubwordSize; /* - * The maximum subword size. Only subwords shorter than this are outputted. Default is 15. Maximum is 300. + * The maximum subword size. Only subwords shorter than this are outputted. + * Default is 15. Maximum is 300. */ + @Generated private Integer maxSubwordSize; /* - * A value indicating whether to add only the longest matching subword to the output. Default is false. + * A value indicating whether to add only the longest matching subword to the + * output. Default is false. */ - private Boolean onlyLongestMatched; + @Generated + private Boolean onlyLongestMatch; /** * Creates an instance of DictionaryDecompounderTokenFilter class. @@ -55,16 +64,18 @@ public final class DictionaryDecompounderTokenFilter extends TokenFilter { * @param name the name value to set. * @param wordList the wordList value to set. */ + @Generated public DictionaryDecompounderTokenFilter(String name, List wordList) { super(name); this.wordList = wordList; } /** - * Get the odataType property: A URI fragment specifying the type of token filter. + * Get the odataType property: The discriminator for derived types. * * @return the odataType value. */ + @Generated @Override public String getOdataType() { return this.odataType; @@ -75,6 +86,7 @@ public String getOdataType() { * * @return the wordList value. */ + @Generated public List getWordList() { return this.wordList; } @@ -85,6 +97,7 @@ public List getWordList() { * * @return the minWordSize value. */ + @Generated public Integer getMinWordSize() { return this.minWordSize; } @@ -96,6 +109,7 @@ public Integer getMinWordSize() { * @param minWordSize the minWordSize value to set. * @return the DictionaryDecompounderTokenFilter object itself. */ + @Generated public DictionaryDecompounderTokenFilter setMinWordSize(Integer minWordSize) { this.minWordSize = minWordSize; return this; @@ -107,6 +121,7 @@ public DictionaryDecompounderTokenFilter setMinWordSize(Integer minWordSize) { * * @return the minSubwordSize value. */ + @Generated public Integer getMinSubwordSize() { return this.minSubwordSize; } @@ -118,58 +133,64 @@ public Integer getMinSubwordSize() { * @param minSubwordSize the minSubwordSize value to set. * @return the DictionaryDecompounderTokenFilter object itself. */ + @Generated public DictionaryDecompounderTokenFilter setMinSubwordSize(Integer minSubwordSize) { this.minSubwordSize = minSubwordSize; return this; } /** - * Get the maxSubwordSize property: The maximum subword size. Only subwords shorter than this are outputted. Default - * is 15. Maximum is 300. + * Get the maxSubwordSize property: The maximum subword size. Only subwords shorter than this are outputted. + * Default is 15. Maximum is 300. * * @return the maxSubwordSize value. */ + @Generated public Integer getMaxSubwordSize() { return this.maxSubwordSize; } /** - * Set the maxSubwordSize property: The maximum subword size. Only subwords shorter than this are outputted. Default - * is 15. Maximum is 300. + * Set the maxSubwordSize property: The maximum subword size. Only subwords shorter than this are outputted. + * Default is 15. Maximum is 300. * * @param maxSubwordSize the maxSubwordSize value to set. * @return the DictionaryDecompounderTokenFilter object itself. */ + @Generated public DictionaryDecompounderTokenFilter setMaxSubwordSize(Integer maxSubwordSize) { this.maxSubwordSize = maxSubwordSize; return this; } /** - * Get the onlyLongestMatched property: A value indicating whether to add only the longest matching subword to the + * Get the onlyLongestMatch property: A value indicating whether to add only the longest matching subword to the * output. Default is false. * - * @return the onlyLongestMatched value. + * @return the onlyLongestMatch value. */ - public Boolean isOnlyLongestMatched() { - return this.onlyLongestMatched; + @Generated + public Boolean isOnlyLongestMatch() { + return this.onlyLongestMatch; } /** - * Set the onlyLongestMatched property: A value indicating whether to add only the longest matching subword to the + * Set the onlyLongestMatch property: A value indicating whether to add only the longest matching subword to the * output. Default is false. * - * @param onlyLongestMatched the onlyLongestMatched value to set. + * @param onlyLongestMatch the onlyLongestMatch value to set. * @return the DictionaryDecompounderTokenFilter object itself. */ - public DictionaryDecompounderTokenFilter setOnlyLongestMatched(Boolean onlyLongestMatched) { - this.onlyLongestMatched = onlyLongestMatched; + @Generated + public DictionaryDecompounderTokenFilter setOnlyLongestMatch(Boolean onlyLongestMatch) { + this.onlyLongestMatch = onlyLongestMatch; return this; } /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); @@ -179,7 +200,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeNumberField("minWordSize", this.minWordSize); jsonWriter.writeNumberField("minSubwordSize", this.minSubwordSize); jsonWriter.writeNumberField("maxSubwordSize", this.maxSubwordSize); - jsonWriter.writeBooleanField("onlyLongestMatch", this.onlyLongestMatched); + jsonWriter.writeBooleanField("onlyLongestMatch", this.onlyLongestMatch); return jsonWriter.writeEndObject(); } @@ -192,27 +213,24 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { * @throws IllegalStateException If the deserialized JSON object was missing any required properties. * @throws IOException If an error occurs while reading the DictionaryDecompounderTokenFilter. */ + @Generated public static DictionaryDecompounderTokenFilter fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { - boolean nameFound = false; String name = null; - boolean wordListFound = false; List wordList = null; String odataType = "#Microsoft.Azure.Search.DictionaryDecompounderTokenFilter"; Integer minWordSize = null; Integer minSubwordSize = null; Integer maxSubwordSize = null; - Boolean onlyLongestMatched = null; + Boolean onlyLongestMatch = null; while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); if ("name".equals(fieldName)) { name = reader.getString(); - nameFound = true; } else if ("wordList".equals(fieldName)) { wordList = reader.readArray(reader1 -> reader1.getString()); - wordListFound = true; } else if ("@odata.type".equals(fieldName)) { odataType = reader.getString(); } else if ("minWordSize".equals(fieldName)) { @@ -222,32 +240,20 @@ public static DictionaryDecompounderTokenFilter fromJson(JsonReader jsonReader) } else if ("maxSubwordSize".equals(fieldName)) { maxSubwordSize = reader.getNullable(JsonReader::getInt); } else if ("onlyLongestMatch".equals(fieldName)) { - onlyLongestMatched = reader.getNullable(JsonReader::getBoolean); + onlyLongestMatch = reader.getNullable(JsonReader::getBoolean); } else { reader.skipChildren(); } } - if (nameFound && wordListFound) { - DictionaryDecompounderTokenFilter deserializedDictionaryDecompounderTokenFilter - = new DictionaryDecompounderTokenFilter(name, wordList); - deserializedDictionaryDecompounderTokenFilter.odataType = odataType; - deserializedDictionaryDecompounderTokenFilter.minWordSize = minWordSize; - deserializedDictionaryDecompounderTokenFilter.minSubwordSize = minSubwordSize; - deserializedDictionaryDecompounderTokenFilter.maxSubwordSize = maxSubwordSize; - deserializedDictionaryDecompounderTokenFilter.onlyLongestMatched = onlyLongestMatched; - - return deserializedDictionaryDecompounderTokenFilter; - } - List missingProperties = new ArrayList<>(); - if (!nameFound) { - missingProperties.add("name"); - } - if (!wordListFound) { - missingProperties.add("wordList"); - } + DictionaryDecompounderTokenFilter deserializedDictionaryDecompounderTokenFilter + = new DictionaryDecompounderTokenFilter(name, wordList); + deserializedDictionaryDecompounderTokenFilter.odataType = odataType; + deserializedDictionaryDecompounderTokenFilter.minWordSize = minWordSize; + deserializedDictionaryDecompounderTokenFilter.minSubwordSize = minSubwordSize; + deserializedDictionaryDecompounderTokenFilter.maxSubwordSize = maxSubwordSize; + deserializedDictionaryDecompounderTokenFilter.onlyLongestMatch = onlyLongestMatch; - throw new IllegalStateException( - "Missing required property/properties: " + String.join(", ", missingProperties)); + return deserializedDictionaryDecompounderTokenFilter; }); } } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/DistanceScoringFunction.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/DistanceScoringFunction.java similarity index 68% rename from sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/DistanceScoringFunction.java rename to sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/DistanceScoringFunction.java index 0e5a0c0594dc..1e64ee718f05 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/DistanceScoringFunction.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/DistanceScoringFunction.java @@ -1,33 +1,32 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) TypeSpec Code Generator. -package com.azure.search.documents.indexes.models; +package com.azure.search.documents.models; import com.azure.core.annotation.Fluent; +import com.azure.core.annotation.Generated; import com.azure.json.JsonReader; import com.azure.json.JsonToken; import com.azure.json.JsonWriter; import java.io.IOException; -import java.util.ArrayList; -import java.util.List; /** - * Defines a function that boosts scores based on distance from a geographic location. + * Defines a function that boosts scores based on distance from a geographic + * location. */ @Fluent public final class DistanceScoringFunction extends ScoringFunction { /* - * Indicates the type of function to use. Valid values include magnitude, freshness, distance, and tag. The function - * type must be lower case. + * Type of ScoringFunction. */ + @Generated private String type = "distance"; /* * Parameter values for the distance scoring function. */ + @Generated private final DistanceScoringParameters parameters; /** @@ -37,17 +36,18 @@ public final class DistanceScoringFunction extends ScoringFunction { * @param boost the boost value to set. * @param parameters the parameters value to set. */ + @Generated public DistanceScoringFunction(String fieldName, double boost, DistanceScoringParameters parameters) { super(fieldName, boost); this.parameters = parameters; } /** - * Get the type property: Indicates the type of function to use. Valid values include magnitude, freshness, - * distance, and tag. The function type must be lower case. + * Get the type property: Type of ScoringFunction. * * @return the type value. */ + @Generated @Override public String getType() { return this.type; @@ -58,6 +58,7 @@ public String getType() { * * @return the parameters value. */ + @Generated public DistanceScoringParameters getParameters() { return this.parameters; } @@ -65,6 +66,7 @@ public DistanceScoringParameters getParameters() { /** * {@inheritDoc} */ + @Generated @Override public DistanceScoringFunction setInterpolation(ScoringFunctionInterpolation interpolation) { super.setInterpolation(interpolation); @@ -74,6 +76,7 @@ public DistanceScoringFunction setInterpolation(ScoringFunctionInterpolation int /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); @@ -94,14 +97,12 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { * @throws IllegalStateException If the deserialized JSON object was missing any required properties. * @throws IOException If an error occurs while reading the DistanceScoringFunction. */ + @Generated public static DistanceScoringFunction fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { - boolean fieldNameFound = false; String fieldName = null; - boolean boostFound = false; double boost = 0.0; ScoringFunctionInterpolation interpolation = null; - boolean parametersFound = false; DistanceScoringParameters parameters = null; String type = "distance"; while (reader.nextToken() != JsonToken.END_OBJECT) { @@ -110,42 +111,24 @@ public static DistanceScoringFunction fromJson(JsonReader jsonReader) throws IOE if ("fieldName".equals(jsonFieldName)) { fieldName = reader.getString(); - fieldNameFound = true; } else if ("boost".equals(jsonFieldName)) { boost = reader.getDouble(); - boostFound = true; } else if ("interpolation".equals(jsonFieldName)) { interpolation = ScoringFunctionInterpolation.fromString(reader.getString()); } else if ("distance".equals(jsonFieldName)) { parameters = DistanceScoringParameters.fromJson(reader); - parametersFound = true; } else if ("type".equals(jsonFieldName)) { type = reader.getString(); } else { reader.skipChildren(); } } - if (fieldNameFound && boostFound && parametersFound) { - DistanceScoringFunction deserializedDistanceScoringFunction - = new DistanceScoringFunction(fieldName, boost, parameters); - deserializedDistanceScoringFunction.setInterpolation(interpolation); - deserializedDistanceScoringFunction.type = type; + DistanceScoringFunction deserializedDistanceScoringFunction + = new DistanceScoringFunction(fieldName, boost, parameters); + deserializedDistanceScoringFunction.setInterpolation(interpolation); + deserializedDistanceScoringFunction.type = type; - return deserializedDistanceScoringFunction; - } - List missingProperties = new ArrayList<>(); - if (!fieldNameFound) { - missingProperties.add("fieldName"); - } - if (!boostFound) { - missingProperties.add("boost"); - } - if (!parametersFound) { - missingProperties.add("distance"); - } - - throw new IllegalStateException( - "Missing required property/properties: " + String.join(", ", missingProperties)); + return deserializedDistanceScoringFunction; }); } } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/DistanceScoringParameters.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/DistanceScoringParameters.java similarity index 73% rename from sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/DistanceScoringParameters.java rename to sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/DistanceScoringParameters.java index 44bca19d7a8e..50b84b253666 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/DistanceScoringParameters.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/DistanceScoringParameters.java @@ -1,19 +1,16 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) TypeSpec Code Generator. -package com.azure.search.documents.indexes.models; +package com.azure.search.documents.models; +import com.azure.core.annotation.Generated; import com.azure.core.annotation.Immutable; import com.azure.json.JsonReader; import com.azure.json.JsonSerializable; import com.azure.json.JsonToken; import com.azure.json.JsonWriter; import java.io.IOException; -import java.util.ArrayList; -import java.util.List; /** * Provides parameter values to a distance scoring function. @@ -21,13 +18,17 @@ @Immutable public final class DistanceScoringParameters implements JsonSerializable { /* - * The name of the parameter passed in search queries to specify the reference location. + * The name of the parameter passed in search queries to specify the reference + * location. */ + @Generated private final String referencePointParameter; /* - * The distance in kilometers from the reference location where the boosting range ends. + * The distance in kilometers from the reference location where the boosting range + * ends. */ + @Generated private final double boostingDistance; /** @@ -36,6 +37,7 @@ public final class DistanceScoringParameters implements JsonSerializable { - boolean referencePointParameterFound = false; String referencePointParameter = null; - boolean boostingDistanceFound = false; double boostingDistance = 0.0; while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); @@ -93,27 +99,13 @@ public static DistanceScoringParameters fromJson(JsonReader jsonReader) throws I if ("referencePointParameter".equals(fieldName)) { referencePointParameter = reader.getString(); - referencePointParameterFound = true; } else if ("boostingDistance".equals(fieldName)) { boostingDistance = reader.getDouble(); - boostingDistanceFound = true; } else { reader.skipChildren(); } } - if (referencePointParameterFound && boostingDistanceFound) { - return new DistanceScoringParameters(referencePointParameter, boostingDistance); - } - List missingProperties = new ArrayList<>(); - if (!referencePointParameterFound) { - missingProperties.add("referencePointParameter"); - } - if (!boostingDistanceFound) { - missingProperties.add("boostingDistance"); - } - - throw new IllegalStateException( - "Missing required property/properties: " + String.join(", ", missingProperties)); + return new DistanceScoringParameters(referencePointParameter, boostingDistance); }); } } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/DocumentDebugInfo.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/DocumentDebugInfo.java index c73f1333369f..3667b9c60348 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/DocumentDebugInfo.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/DocumentDebugInfo.java @@ -1,11 +1,10 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.search.documents.models; +import com.azure.core.annotation.Generated; import com.azure.core.annotation.Immutable; import com.azure.json.JsonReader; import com.azure.json.JsonSerializable; @@ -14,24 +13,28 @@ import java.io.IOException; /** - * Contains debugging information that can be used to further explore your search results. + * Contains debugging information that can be used to further explore your search + * results. */ @Immutable public final class DocumentDebugInfo implements JsonSerializable { /* * Contains debugging information specific to semantic ranking requests. */ + @Generated private SemanticDebugInfo semantic; /* * Contains debugging information specific to vector and hybrid search. */ + @Generated private VectorsDebugInfo vectors; /** * Creates an instance of DocumentDebugInfo class. */ - public DocumentDebugInfo() { + @Generated + private DocumentDebugInfo() { } /** @@ -39,6 +42,7 @@ public DocumentDebugInfo() { * * @return the semantic value. */ + @Generated public SemanticDebugInfo getSemantic() { return this.semantic; } @@ -48,6 +52,7 @@ public SemanticDebugInfo getSemantic() { * * @return the vectors value. */ + @Generated public VectorsDebugInfo getVectors() { return this.vectors; } @@ -55,6 +60,7 @@ public VectorsDebugInfo getVectors() { /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); @@ -69,6 +75,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { * pointing to JSON null. * @throws IOException If an error occurs while reading the DocumentDebugInfo. */ + @Generated public static DocumentDebugInfo fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { DocumentDebugInfo deserializedDocumentDebugInfo = new DocumentDebugInfo(); diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/DocumentExtractionSkill.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/DocumentExtractionSkill.java similarity index 78% rename from sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/DocumentExtractionSkill.java rename to sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/DocumentExtractionSkill.java index b1fa6626ba40..b0f14217fc08 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/DocumentExtractionSkill.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/DocumentExtractionSkill.java @@ -1,17 +1,16 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) TypeSpec Code Generator. -package com.azure.search.documents.indexes.models; +package com.azure.search.documents.models; import com.azure.core.annotation.Fluent; +import com.azure.core.annotation.Generated; +import com.azure.core.util.BinaryData; import com.azure.json.JsonReader; import com.azure.json.JsonToken; import com.azure.json.JsonWriter; import java.io.IOException; -import java.util.ArrayList; import java.util.List; import java.util.Map; @@ -21,24 +20,28 @@ @Fluent public final class DocumentExtractionSkill extends SearchIndexerSkill { /* - * A URI fragment specifying the type of skill. + * The discriminator for derived types. */ + @Generated private String odataType = "#Microsoft.Skills.Util.DocumentExtractionSkill"; /* * The parsingMode for the skill. Will be set to 'default' if not defined. */ + @Generated private String parsingMode; /* * The type of data to be extracted for the skill. Will be set to 'contentAndMetadata' if not defined. */ + @Generated private String dataToExtract; /* * A dictionary of configurations for the skill. */ - private Map configuration; + @Generated + private Map configuration; /** * Creates an instance of DocumentExtractionSkill class. @@ -46,15 +49,17 @@ public final class DocumentExtractionSkill extends SearchIndexerSkill { * @param inputs the inputs value to set. * @param outputs the outputs value to set. */ + @Generated public DocumentExtractionSkill(List inputs, List outputs) { super(inputs, outputs); } /** - * Get the odataType property: A URI fragment specifying the type of skill. + * Get the odataType property: The discriminator for derived types. * * @return the odataType value. */ + @Generated @Override public String getOdataType() { return this.odataType; @@ -65,6 +70,7 @@ public String getOdataType() { * * @return the parsingMode value. */ + @Generated public String getParsingMode() { return this.parsingMode; } @@ -75,6 +81,7 @@ public String getParsingMode() { * @param parsingMode the parsingMode value to set. * @return the DocumentExtractionSkill object itself. */ + @Generated public DocumentExtractionSkill setParsingMode(String parsingMode) { this.parsingMode = parsingMode; return this; @@ -86,6 +93,7 @@ public DocumentExtractionSkill setParsingMode(String parsingMode) { * * @return the dataToExtract value. */ + @Generated public String getDataToExtract() { return this.dataToExtract; } @@ -97,6 +105,7 @@ public String getDataToExtract() { * @param dataToExtract the dataToExtract value to set. * @return the DocumentExtractionSkill object itself. */ + @Generated public DocumentExtractionSkill setDataToExtract(String dataToExtract) { this.dataToExtract = dataToExtract; return this; @@ -107,7 +116,8 @@ public DocumentExtractionSkill setDataToExtract(String dataToExtract) { * * @return the configuration value. */ - public Map getConfiguration() { + @Generated + public Map getConfiguration() { return this.configuration; } @@ -117,7 +127,8 @@ public Map getConfiguration() { * @param configuration the configuration value to set. * @return the DocumentExtractionSkill object itself. */ - public DocumentExtractionSkill setConfiguration(Map configuration) { + @Generated + public DocumentExtractionSkill setConfiguration(Map configuration) { this.configuration = configuration; return this; } @@ -125,6 +136,7 @@ public DocumentExtractionSkill setConfiguration(Map configuratio /** * {@inheritDoc} */ + @Generated @Override public DocumentExtractionSkill setName(String name) { super.setName(name); @@ -134,6 +146,7 @@ public DocumentExtractionSkill setName(String name) { /** * {@inheritDoc} */ + @Generated @Override public DocumentExtractionSkill setDescription(String description) { super.setDescription(description); @@ -143,6 +156,7 @@ public DocumentExtractionSkill setDescription(String description) { /** * {@inheritDoc} */ + @Generated @Override public DocumentExtractionSkill setContext(String context) { super.setContext(context); @@ -152,6 +166,7 @@ public DocumentExtractionSkill setContext(String context) { /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); @@ -164,7 +179,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStringField("parsingMode", this.parsingMode); jsonWriter.writeStringField("dataToExtract", this.dataToExtract); jsonWriter.writeMapField("configuration", this.configuration, - (writer, element) -> writer.writeUntyped(element)); + (writer, element) -> writer.writeUntyped(element == null ? null : element.toObject(Object.class))); return jsonWriter.writeEndObject(); } @@ -177,11 +192,10 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { * @throws IllegalStateException If the deserialized JSON object was missing any required properties. * @throws IOException If an error occurs while reading the DocumentExtractionSkill. */ + @Generated public static DocumentExtractionSkill fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { - boolean inputsFound = false; List inputs = null; - boolean outputsFound = false; List outputs = null; String name = null; String description = null; @@ -189,17 +203,15 @@ public static DocumentExtractionSkill fromJson(JsonReader jsonReader) throws IOE String odataType = "#Microsoft.Skills.Util.DocumentExtractionSkill"; String parsingMode = null; String dataToExtract = null; - Map configuration = null; + Map configuration = null; while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); if ("inputs".equals(fieldName)) { inputs = reader.readArray(reader1 -> InputFieldMappingEntry.fromJson(reader1)); - inputsFound = true; } else if ("outputs".equals(fieldName)) { outputs = reader.readArray(reader1 -> OutputFieldMappingEntry.fromJson(reader1)); - outputsFound = true; } else if ("name".equals(fieldName)) { name = reader.getString(); } else if ("description".equals(fieldName)) { @@ -213,34 +225,22 @@ public static DocumentExtractionSkill fromJson(JsonReader jsonReader) throws IOE } else if ("dataToExtract".equals(fieldName)) { dataToExtract = reader.getString(); } else if ("configuration".equals(fieldName)) { - configuration = reader.readMap(reader1 -> reader1.readUntyped()); + configuration = reader.readMap(reader1 -> reader1 + .getNullable(nonNullReader -> BinaryData.fromObject(nonNullReader.readUntyped()))); } else { reader.skipChildren(); } } - if (inputsFound && outputsFound) { - DocumentExtractionSkill deserializedDocumentExtractionSkill - = new DocumentExtractionSkill(inputs, outputs); - deserializedDocumentExtractionSkill.setName(name); - deserializedDocumentExtractionSkill.setDescription(description); - deserializedDocumentExtractionSkill.setContext(context); - deserializedDocumentExtractionSkill.odataType = odataType; - deserializedDocumentExtractionSkill.parsingMode = parsingMode; - deserializedDocumentExtractionSkill.dataToExtract = dataToExtract; - deserializedDocumentExtractionSkill.configuration = configuration; - - return deserializedDocumentExtractionSkill; - } - List missingProperties = new ArrayList<>(); - if (!inputsFound) { - missingProperties.add("inputs"); - } - if (!outputsFound) { - missingProperties.add("outputs"); - } - - throw new IllegalStateException( - "Missing required property/properties: " + String.join(", ", missingProperties)); + DocumentExtractionSkill deserializedDocumentExtractionSkill = new DocumentExtractionSkill(inputs, outputs); + deserializedDocumentExtractionSkill.setName(name); + deserializedDocumentExtractionSkill.setDescription(description); + deserializedDocumentExtractionSkill.setContext(context); + deserializedDocumentExtractionSkill.odataType = odataType; + deserializedDocumentExtractionSkill.parsingMode = parsingMode; + deserializedDocumentExtractionSkill.dataToExtract = dataToExtract; + deserializedDocumentExtractionSkill.configuration = configuration; + + return deserializedDocumentExtractionSkill; }); } } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/DocumentIntelligenceLayoutSkill.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/DocumentIntelligenceLayoutSkill.java similarity index 79% rename from sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/DocumentIntelligenceLayoutSkill.java rename to sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/DocumentIntelligenceLayoutSkill.java index 6e9984b142ed..e1eb7e4f6513 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/DocumentIntelligenceLayoutSkill.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/DocumentIntelligenceLayoutSkill.java @@ -1,38 +1,39 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) TypeSpec Code Generator. -package com.azure.search.documents.indexes.models; +package com.azure.search.documents.models; import com.azure.core.annotation.Fluent; +import com.azure.core.annotation.Generated; import com.azure.json.JsonReader; import com.azure.json.JsonToken; import com.azure.json.JsonWriter; import java.io.IOException; -import java.util.ArrayList; import java.util.List; /** - * A skill that extracts content and layout information (as markdown), via Azure AI Services, from files within the - * enrichment pipeline. + * A skill that extracts content and layout information (as markdown), via Azure + * AI Services, from files within the enrichment pipeline. */ @Fluent public final class DocumentIntelligenceLayoutSkill extends SearchIndexerSkill { /* - * A URI fragment specifying the type of skill. + * The discriminator for derived types. */ + @Generated private String odataType = "#Microsoft.Skills.Util.DocumentIntelligenceLayoutSkill"; /* * Controls the cardinality of the output produced by the skill. Default is 'oneToMany'. */ + @Generated private DocumentIntelligenceLayoutSkillOutputMode outputMode; /* * The depth of headers in the markdown output. Default is h6. */ + @Generated private DocumentIntelligenceLayoutSkillMarkdownHeaderDepth markdownHeaderDepth; /** @@ -41,15 +42,17 @@ public final class DocumentIntelligenceLayoutSkill extends SearchIndexerSkill { * @param inputs the inputs value to set. * @param outputs the outputs value to set. */ + @Generated public DocumentIntelligenceLayoutSkill(List inputs, List outputs) { super(inputs, outputs); } /** - * Get the odataType property: A URI fragment specifying the type of skill. + * Get the odataType property: The discriminator for derived types. * * @return the odataType value. */ + @Generated @Override public String getOdataType() { return this.odataType; @@ -61,6 +64,7 @@ public String getOdataType() { * * @return the outputMode value. */ + @Generated public DocumentIntelligenceLayoutSkillOutputMode getOutputMode() { return this.outputMode; } @@ -72,6 +76,7 @@ public DocumentIntelligenceLayoutSkillOutputMode getOutputMode() { * @param outputMode the outputMode value to set. * @return the DocumentIntelligenceLayoutSkill object itself. */ + @Generated public DocumentIntelligenceLayoutSkill setOutputMode(DocumentIntelligenceLayoutSkillOutputMode outputMode) { this.outputMode = outputMode; return this; @@ -82,6 +87,7 @@ public DocumentIntelligenceLayoutSkill setOutputMode(DocumentIntelligenceLayoutS * * @return the markdownHeaderDepth value. */ + @Generated public DocumentIntelligenceLayoutSkillMarkdownHeaderDepth getMarkdownHeaderDepth() { return this.markdownHeaderDepth; } @@ -92,6 +98,7 @@ public DocumentIntelligenceLayoutSkillMarkdownHeaderDepth getMarkdownHeaderDepth * @param markdownHeaderDepth the markdownHeaderDepth value to set. * @return the DocumentIntelligenceLayoutSkill object itself. */ + @Generated public DocumentIntelligenceLayoutSkill setMarkdownHeaderDepth(DocumentIntelligenceLayoutSkillMarkdownHeaderDepth markdownHeaderDepth) { this.markdownHeaderDepth = markdownHeaderDepth; @@ -101,6 +108,7 @@ public DocumentIntelligenceLayoutSkillMarkdownHeaderDepth getMarkdownHeaderDepth /** * {@inheritDoc} */ + @Generated @Override public DocumentIntelligenceLayoutSkill setName(String name) { super.setName(name); @@ -110,6 +118,7 @@ public DocumentIntelligenceLayoutSkill setName(String name) { /** * {@inheritDoc} */ + @Generated @Override public DocumentIntelligenceLayoutSkill setDescription(String description) { super.setDescription(description); @@ -119,6 +128,7 @@ public DocumentIntelligenceLayoutSkill setDescription(String description) { /** * {@inheritDoc} */ + @Generated @Override public DocumentIntelligenceLayoutSkill setContext(String context) { super.setContext(context); @@ -128,6 +138,7 @@ public DocumentIntelligenceLayoutSkill setContext(String context) { /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); @@ -152,11 +163,10 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { * @throws IllegalStateException If the deserialized JSON object was missing any required properties. * @throws IOException If an error occurs while reading the DocumentIntelligenceLayoutSkill. */ + @Generated public static DocumentIntelligenceLayoutSkill fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { - boolean inputsFound = false; List inputs = null; - boolean outputsFound = false; List outputs = null; String name = null; String description = null; @@ -170,10 +180,8 @@ public static DocumentIntelligenceLayoutSkill fromJson(JsonReader jsonReader) th if ("inputs".equals(fieldName)) { inputs = reader.readArray(reader1 -> InputFieldMappingEntry.fromJson(reader1)); - inputsFound = true; } else if ("outputs".equals(fieldName)) { outputs = reader.readArray(reader1 -> OutputFieldMappingEntry.fromJson(reader1)); - outputsFound = true; } else if ("name".equals(fieldName)) { name = reader.getString(); } else if ("description".equals(fieldName)) { @@ -191,28 +199,16 @@ public static DocumentIntelligenceLayoutSkill fromJson(JsonReader jsonReader) th reader.skipChildren(); } } - if (inputsFound && outputsFound) { - DocumentIntelligenceLayoutSkill deserializedDocumentIntelligenceLayoutSkill - = new DocumentIntelligenceLayoutSkill(inputs, outputs); - deserializedDocumentIntelligenceLayoutSkill.setName(name); - deserializedDocumentIntelligenceLayoutSkill.setDescription(description); - deserializedDocumentIntelligenceLayoutSkill.setContext(context); - deserializedDocumentIntelligenceLayoutSkill.odataType = odataType; - deserializedDocumentIntelligenceLayoutSkill.outputMode = outputMode; - deserializedDocumentIntelligenceLayoutSkill.markdownHeaderDepth = markdownHeaderDepth; - - return deserializedDocumentIntelligenceLayoutSkill; - } - List missingProperties = new ArrayList<>(); - if (!inputsFound) { - missingProperties.add("inputs"); - } - if (!outputsFound) { - missingProperties.add("outputs"); - } - - throw new IllegalStateException( - "Missing required property/properties: " + String.join(", ", missingProperties)); + DocumentIntelligenceLayoutSkill deserializedDocumentIntelligenceLayoutSkill + = new DocumentIntelligenceLayoutSkill(inputs, outputs); + deserializedDocumentIntelligenceLayoutSkill.setName(name); + deserializedDocumentIntelligenceLayoutSkill.setDescription(description); + deserializedDocumentIntelligenceLayoutSkill.setContext(context); + deserializedDocumentIntelligenceLayoutSkill.odataType = odataType; + deserializedDocumentIntelligenceLayoutSkill.outputMode = outputMode; + deserializedDocumentIntelligenceLayoutSkill.markdownHeaderDepth = markdownHeaderDepth; + + return deserializedDocumentIntelligenceLayoutSkill; }); } } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/DocumentIntelligenceLayoutSkillMarkdownHeaderDepth.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/DocumentIntelligenceLayoutSkillMarkdownHeaderDepth.java similarity index 89% rename from sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/DocumentIntelligenceLayoutSkillMarkdownHeaderDepth.java rename to sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/DocumentIntelligenceLayoutSkillMarkdownHeaderDepth.java index 833760c3a1dd..35d04565038e 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/DocumentIntelligenceLayoutSkillMarkdownHeaderDepth.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/DocumentIntelligenceLayoutSkillMarkdownHeaderDepth.java @@ -1,11 +1,10 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) TypeSpec Code Generator. -package com.azure.search.documents.indexes.models; +package com.azure.search.documents.models; +import com.azure.core.annotation.Generated; import com.azure.core.util.ExpandableStringEnum; import java.util.Collection; @@ -17,31 +16,37 @@ public final class DocumentIntelligenceLayoutSkillMarkdownHeaderDepth /** * Header level 1. */ + @Generated public static final DocumentIntelligenceLayoutSkillMarkdownHeaderDepth H1 = fromString("h1"); /** * Header level 2. */ + @Generated public static final DocumentIntelligenceLayoutSkillMarkdownHeaderDepth H2 = fromString("h2"); /** * Header level 3. */ + @Generated public static final DocumentIntelligenceLayoutSkillMarkdownHeaderDepth H3 = fromString("h3"); /** * Header level 4. */ + @Generated public static final DocumentIntelligenceLayoutSkillMarkdownHeaderDepth H4 = fromString("h4"); /** * Header level 5. */ + @Generated public static final DocumentIntelligenceLayoutSkillMarkdownHeaderDepth H5 = fromString("h5"); /** * Header level 6. */ + @Generated public static final DocumentIntelligenceLayoutSkillMarkdownHeaderDepth H6 = fromString("h6"); /** @@ -49,6 +54,7 @@ public final class DocumentIntelligenceLayoutSkillMarkdownHeaderDepth * * @deprecated Use the {@link #fromString(String)} factory method. */ + @Generated @Deprecated public DocumentIntelligenceLayoutSkillMarkdownHeaderDepth() { } @@ -59,6 +65,7 @@ public DocumentIntelligenceLayoutSkillMarkdownHeaderDepth() { * @param name a name to look for. * @return the corresponding DocumentIntelligenceLayoutSkillMarkdownHeaderDepth. */ + @Generated public static DocumentIntelligenceLayoutSkillMarkdownHeaderDepth fromString(String name) { return fromString(name, DocumentIntelligenceLayoutSkillMarkdownHeaderDepth.class); } @@ -68,6 +75,7 @@ public static DocumentIntelligenceLayoutSkillMarkdownHeaderDepth fromString(Stri * * @return known DocumentIntelligenceLayoutSkillMarkdownHeaderDepth values. */ + @Generated public static Collection values() { return values(DocumentIntelligenceLayoutSkillMarkdownHeaderDepth.class); } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/DocumentIntelligenceLayoutSkillOutputMode.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/DocumentIntelligenceLayoutSkillOutputMode.java similarity index 88% rename from sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/DocumentIntelligenceLayoutSkillOutputMode.java rename to sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/DocumentIntelligenceLayoutSkillOutputMode.java index 1bd1fe113b19..a4ea6245d7c5 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/DocumentIntelligenceLayoutSkillOutputMode.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/DocumentIntelligenceLayoutSkillOutputMode.java @@ -1,11 +1,10 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) TypeSpec Code Generator. -package com.azure.search.documents.indexes.models; +package com.azure.search.documents.models; +import com.azure.core.annotation.Generated; import com.azure.core.util.ExpandableStringEnum; import java.util.Collection; @@ -17,6 +16,7 @@ public final class DocumentIntelligenceLayoutSkillOutputMode /** * Specify the deepest markdown header section to parse. */ + @Generated public static final DocumentIntelligenceLayoutSkillOutputMode ONE_TO_MANY = fromString("oneToMany"); /** @@ -24,6 +24,7 @@ public final class DocumentIntelligenceLayoutSkillOutputMode * * @deprecated Use the {@link #fromString(String)} factory method. */ + @Generated @Deprecated public DocumentIntelligenceLayoutSkillOutputMode() { } @@ -34,6 +35,7 @@ public DocumentIntelligenceLayoutSkillOutputMode() { * @param name a name to look for. * @return the corresponding DocumentIntelligenceLayoutSkillOutputMode. */ + @Generated public static DocumentIntelligenceLayoutSkillOutputMode fromString(String name) { return fromString(name, DocumentIntelligenceLayoutSkillOutputMode.class); } @@ -43,6 +45,7 @@ public static DocumentIntelligenceLayoutSkillOutputMode fromString(String name) * * @return known DocumentIntelligenceLayoutSkillOutputMode values. */ + @Generated public static Collection values() { return values(DocumentIntelligenceLayoutSkillOutputMode.class); } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/implementation/models/DocumentKeysOrIds.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/DocumentKeysOrIds.java similarity index 92% rename from sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/implementation/models/DocumentKeysOrIds.java rename to sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/DocumentKeysOrIds.java index e1b7f1d06bb7..25bdd7ed5567 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/implementation/models/DocumentKeysOrIds.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/DocumentKeysOrIds.java @@ -1,12 +1,11 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) TypeSpec Code Generator. -package com.azure.search.documents.indexes.implementation.models; +package com.azure.search.documents.models; import com.azure.core.annotation.Fluent; +import com.azure.core.annotation.Generated; import com.azure.json.JsonReader; import com.azure.json.JsonSerializable; import com.azure.json.JsonToken; @@ -15,23 +14,26 @@ import java.util.List; /** - * The DocumentKeysOrIds model. + * The type of the keysOrIds. */ @Fluent public final class DocumentKeysOrIds implements JsonSerializable { /* * document keys to be reset */ + @Generated private List documentKeys; /* * datasource document identifiers to be reset */ + @Generated private List datasourceDocumentIds; /** * Creates an instance of DocumentKeysOrIds class. */ + @Generated public DocumentKeysOrIds() { } @@ -40,6 +42,7 @@ public DocumentKeysOrIds() { * * @return the documentKeys value. */ + @Generated public List getDocumentKeys() { return this.documentKeys; } @@ -50,6 +53,7 @@ public List getDocumentKeys() { * @param documentKeys the documentKeys value to set. * @return the DocumentKeysOrIds object itself. */ + @Generated public DocumentKeysOrIds setDocumentKeys(List documentKeys) { this.documentKeys = documentKeys; return this; @@ -60,6 +64,7 @@ public DocumentKeysOrIds setDocumentKeys(List documentKeys) { * * @return the datasourceDocumentIds value. */ + @Generated public List getDatasourceDocumentIds() { return this.datasourceDocumentIds; } @@ -70,6 +75,7 @@ public List getDatasourceDocumentIds() { * @param datasourceDocumentIds the datasourceDocumentIds value to set. * @return the DocumentKeysOrIds object itself. */ + @Generated public DocumentKeysOrIds setDatasourceDocumentIds(List datasourceDocumentIds) { this.datasourceDocumentIds = datasourceDocumentIds; return this; @@ -78,6 +84,7 @@ public DocumentKeysOrIds setDatasourceDocumentIds(List datasourceDocumen /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); @@ -95,6 +102,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { * pointing to JSON null. * @throws IOException If an error occurs while reading the DocumentKeysOrIds. */ + @Generated public static DocumentKeysOrIds fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { DocumentKeysOrIds deserializedDocumentKeysOrIds = new DocumentKeysOrIds(); diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/EdgeNGramTokenFilterSide.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/EdgeNGramTokenFilterSide.java new file mode 100644 index 000000000000..3770555c3d8b --- /dev/null +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/EdgeNGramTokenFilterSide.java @@ -0,0 +1,57 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.search.documents.models; + +import com.azure.core.annotation.Generated; +import com.azure.core.util.ExpandableStringEnum; +import java.util.Collection; + +/** + * Specifies which side of the input an n-gram should be generated from. + */ +public final class EdgeNGramTokenFilterSide extends ExpandableStringEnum { + /** + * Specifies that the n-gram should be generated from the front of the input. + */ + @Generated + public static final EdgeNGramTokenFilterSide FRONT = fromString("front"); + + /** + * Specifies that the n-gram should be generated from the back of the input. + */ + @Generated + public static final EdgeNGramTokenFilterSide BACK = fromString("back"); + + /** + * Creates a new instance of EdgeNGramTokenFilterSide value. + * + * @deprecated Use the {@link #fromString(String)} factory method. + */ + @Generated + @Deprecated + public EdgeNGramTokenFilterSide() { + } + + /** + * Creates or finds a EdgeNGramTokenFilterSide from its string representation. + * + * @param name a name to look for. + * @return the corresponding EdgeNGramTokenFilterSide. + */ + @Generated + public static EdgeNGramTokenFilterSide fromString(String name) { + return fromString(name, EdgeNGramTokenFilterSide.class); + } + + /** + * Gets known EdgeNGramTokenFilterSide values. + * + * @return known EdgeNGramTokenFilterSide values. + */ + @Generated + public static Collection values() { + return values(EdgeNGramTokenFilterSide.class); + } +} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/implementation/models/EdgeNGramTokenFilterV2.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/EdgeNGramTokenFilterV2.java similarity index 76% rename from sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/implementation/models/EdgeNGramTokenFilterV2.java rename to sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/EdgeNGramTokenFilterV2.java index 684f68047ac5..2a31ca806bea 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/implementation/models/EdgeNGramTokenFilterV2.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/EdgeNGramTokenFilterV2.java @@ -1,43 +1,46 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) TypeSpec Code Generator. -package com.azure.search.documents.indexes.implementation.models; +package com.azure.search.documents.models; import com.azure.core.annotation.Fluent; +import com.azure.core.annotation.Generated; import com.azure.json.JsonReader; import com.azure.json.JsonToken; import com.azure.json.JsonWriter; -import com.azure.search.documents.indexes.models.EdgeNGramTokenFilterSide; -import com.azure.search.documents.indexes.models.TokenFilter; import java.io.IOException; /** - * 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. + * 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. */ @Fluent public final class EdgeNGramTokenFilterV2 extends TokenFilter { /* - * A URI fragment specifying the type of token filter. + * The discriminator for derived types. */ + @Generated private String odataType = "#Microsoft.Azure.Search.EdgeNGramTokenFilterV2"; /* - * The minimum n-gram length. Default is 1. Maximum is 300. Must be less than the value of maxGram. + * The minimum n-gram length. Default is 1. Maximum is 300. Must be less than the + * value of maxGram. */ + @Generated private Integer minGram; /* * The maximum n-gram length. Default is 2. Maximum is 300. */ + @Generated private Integer maxGram; /* - * Specifies which side of the input the n-gram should be generated from. Default is "front". + * Specifies which side of the input the n-gram should be generated from. Default + * is "front". */ + @Generated private EdgeNGramTokenFilterSide side; /** @@ -45,37 +48,41 @@ public final class EdgeNGramTokenFilterV2 extends TokenFilter { * * @param name the name value to set. */ + @Generated public EdgeNGramTokenFilterV2(String name) { super(name); } /** - * Get the odataType property: A URI fragment specifying the type of token filter. + * Get the odataType property: The discriminator for derived types. * * @return the odataType value. */ + @Generated @Override public String getOdataType() { return this.odataType; } /** - * Get the minGram property: The minimum n-gram length. Default is 1. Maximum is 300. Must be less than the value of - * maxGram. + * Get the minGram property: The minimum n-gram length. Default is 1. Maximum is 300. Must be less than the + * value of maxGram. * * @return the minGram value. */ + @Generated public Integer getMinGram() { return this.minGram; } /** - * Set the minGram property: The minimum n-gram length. Default is 1. Maximum is 300. Must be less than the value of - * maxGram. + * Set the minGram property: The minimum n-gram length. Default is 1. Maximum is 300. Must be less than the + * value of maxGram. * * @param minGram the minGram value to set. * @return the EdgeNGramTokenFilterV2 object itself. */ + @Generated public EdgeNGramTokenFilterV2 setMinGram(Integer minGram) { this.minGram = minGram; return this; @@ -86,6 +93,7 @@ public EdgeNGramTokenFilterV2 setMinGram(Integer minGram) { * * @return the maxGram value. */ + @Generated public Integer getMaxGram() { return this.maxGram; } @@ -96,26 +104,31 @@ public Integer getMaxGram() { * @param maxGram the maxGram value to set. * @return the EdgeNGramTokenFilterV2 object itself. */ + @Generated public EdgeNGramTokenFilterV2 setMaxGram(Integer maxGram) { this.maxGram = maxGram; return this; } /** - * Get the side property: Specifies which side of the input the n-gram should be generated from. Default is "front". + * Get the side property: Specifies which side of the input the n-gram should be generated from. Default + * is "front". * * @return the side value. */ + @Generated public EdgeNGramTokenFilterSide getSide() { return this.side; } /** - * Set the side property: Specifies which side of the input the n-gram should be generated from. Default is "front". + * Set the side property: Specifies which side of the input the n-gram should be generated from. Default + * is "front". * * @param side the side value to set. * @return the EdgeNGramTokenFilterV2 object itself. */ + @Generated public EdgeNGramTokenFilterV2 setSide(EdgeNGramTokenFilterSide side) { this.side = side; return this; @@ -124,6 +137,7 @@ public EdgeNGramTokenFilterV2 setSide(EdgeNGramTokenFilterSide side) { /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); @@ -144,9 +158,9 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { * @throws IllegalStateException If the deserialized JSON object was missing any required properties. * @throws IOException If an error occurs while reading the EdgeNGramTokenFilterV2. */ + @Generated public static EdgeNGramTokenFilterV2 fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { - boolean nameFound = false; String name = null; String odataType = "#Microsoft.Azure.Search.EdgeNGramTokenFilterV2"; Integer minGram = null; @@ -158,7 +172,6 @@ public static EdgeNGramTokenFilterV2 fromJson(JsonReader jsonReader) throws IOEx if ("name".equals(fieldName)) { name = reader.getString(); - nameFound = true; } else if ("@odata.type".equals(fieldName)) { odataType = reader.getString(); } else if ("minGram".equals(fieldName)) { @@ -171,16 +184,13 @@ public static EdgeNGramTokenFilterV2 fromJson(JsonReader jsonReader) throws IOEx reader.skipChildren(); } } - if (nameFound) { - EdgeNGramTokenFilterV2 deserializedEdgeNGramTokenFilterV2 = new EdgeNGramTokenFilterV2(name); - deserializedEdgeNGramTokenFilterV2.odataType = odataType; - deserializedEdgeNGramTokenFilterV2.minGram = minGram; - deserializedEdgeNGramTokenFilterV2.maxGram = maxGram; - deserializedEdgeNGramTokenFilterV2.side = side; - - return deserializedEdgeNGramTokenFilterV2; - } - throw new IllegalStateException("Missing required property: name"); + EdgeNGramTokenFilterV2 deserializedEdgeNGramTokenFilterV2 = new EdgeNGramTokenFilterV2(name); + deserializedEdgeNGramTokenFilterV2.odataType = odataType; + deserializedEdgeNGramTokenFilterV2.minGram = minGram; + deserializedEdgeNGramTokenFilterV2.maxGram = maxGram; + deserializedEdgeNGramTokenFilterV2.side = side; + + return deserializedEdgeNGramTokenFilterV2; }); } } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/EdgeNGramTokenizer.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/EdgeNGramTokenizer.java similarity index 75% rename from sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/EdgeNGramTokenizer.java rename to sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/EdgeNGramTokenizer.java index 84297bef40f4..511455bc87c6 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/EdgeNGramTokenizer.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/EdgeNGramTokenizer.java @@ -1,81 +1,88 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. -package com.azure.search.documents.indexes.models; +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.search.documents.models; import com.azure.core.annotation.Fluent; +import com.azure.core.annotation.Generated; import com.azure.json.JsonReader; import com.azure.json.JsonToken; import com.azure.json.JsonWriter; import java.io.IOException; -import java.util.Arrays; import java.util.List; /** - * Tokenizes the input from an edge into n-grams of the given size(s). This tokenizer is implemented using Apache - * Lucene. + * Tokenizes the input from an edge into n-grams of the given size(s). This + * tokenizer is implemented using Apache Lucene. */ @Fluent public final class EdgeNGramTokenizer extends LexicalTokenizer { - /* - * A URI fragment specifying the type of tokenizer. + * The discriminator for derived types. */ + @Generated private String odataType = "#Microsoft.Azure.Search.EdgeNGramTokenizer"; /* - * The minimum n-gram length. Default is 1. Maximum is 300. Must be less than the value of maxGram. + * The minimum n-gram length. Default is 1. Maximum is 300. Must be less than the + * value of maxGram. */ + @Generated private Integer minGram; /* * The maximum n-gram length. Default is 2. Maximum is 300. */ + @Generated private Integer maxGram; /* * Character classes to keep in the tokens. */ + @Generated private List tokenChars; /** * Creates an instance of EdgeNGramTokenizer class. - * + * * @param name the name value to set. */ + @Generated public EdgeNGramTokenizer(String name) { super(name); } /** - * Get the odataType property: A URI fragment specifying the type of tokenizer. - * + * Get the odataType property: The discriminator for derived types. + * * @return the odataType value. */ + @Generated @Override public String getOdataType() { return this.odataType; } /** - * Get the minGram property: The minimum n-gram length. Default is 1. Maximum is 300. Must be less than the value of - * maxGram. - * + * Get the minGram property: The minimum n-gram length. Default is 1. Maximum is 300. Must be less than the + * value of maxGram. + * * @return the minGram value. */ + @Generated public Integer getMinGram() { return this.minGram; } /** - * Set the minGram property: The minimum n-gram length. Default is 1. Maximum is 300. Must be less than the value of - * maxGram. - * + * Set the minGram property: The minimum n-gram length. Default is 1. Maximum is 300. Must be less than the + * value of maxGram. + * * @param minGram the minGram value to set. * @return the EdgeNGramTokenizer object itself. */ + @Generated public EdgeNGramTokenizer setMinGram(Integer minGram) { this.minGram = minGram; return this; @@ -83,19 +90,21 @@ public EdgeNGramTokenizer setMinGram(Integer minGram) { /** * Get the maxGram property: The maximum n-gram length. Default is 2. Maximum is 300. - * + * * @return the maxGram value. */ + @Generated public Integer getMaxGram() { return this.maxGram; } /** * Set the maxGram property: The maximum n-gram length. Default is 2. Maximum is 300. - * + * * @param maxGram the maxGram value to set. * @return the EdgeNGramTokenizer object itself. */ + @Generated public EdgeNGramTokenizer setMaxGram(Integer maxGram) { this.maxGram = maxGram; return this; @@ -103,19 +112,21 @@ public EdgeNGramTokenizer setMaxGram(Integer maxGram) { /** * Get the tokenChars property: Character classes to keep in the tokens. - * + * * @return the tokenChars value. */ + @Generated public List getTokenChars() { return this.tokenChars; } /** * Set the tokenChars property: Character classes to keep in the tokens. - * + * * @param tokenChars the tokenChars value to set. * @return the EdgeNGramTokenizer object itself. */ + @Generated public EdgeNGramTokenizer setTokenChars(List tokenChars) { this.tokenChars = tokenChars; return this; @@ -124,6 +135,7 @@ public EdgeNGramTokenizer setTokenChars(List tokenChars) { /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); @@ -138,16 +150,16 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of EdgeNGramTokenizer from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of EdgeNGramTokenizer if the JsonReader was pointing to an instance of it, or null if it was * pointing to JSON null. * @throws IllegalStateException If the deserialized JSON object was missing any required properties. * @throws IOException If an error occurs while reading the EdgeNGramTokenizer. */ + @Generated public static EdgeNGramTokenizer fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { - boolean nameFound = false; String name = null; String odataType = "#Microsoft.Azure.Search.EdgeNGramTokenizer"; Integer minGram = null; @@ -156,9 +168,9 @@ public static EdgeNGramTokenizer fromJson(JsonReader jsonReader) throws IOExcept while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); + if ("name".equals(fieldName)) { name = reader.getString(); - nameFound = true; } else if ("@odata.type".equals(fieldName)) { odataType = reader.getString(); } else if ("minGram".equals(fieldName)) { @@ -171,26 +183,13 @@ public static EdgeNGramTokenizer fromJson(JsonReader jsonReader) throws IOExcept reader.skipChildren(); } } - if (nameFound) { - EdgeNGramTokenizer deserializedEdgeNGramTokenizer = new EdgeNGramTokenizer(name); - deserializedEdgeNGramTokenizer.odataType = odataType; - deserializedEdgeNGramTokenizer.minGram = minGram; - deserializedEdgeNGramTokenizer.maxGram = maxGram; - deserializedEdgeNGramTokenizer.tokenChars = tokenChars; - return deserializedEdgeNGramTokenizer; - } - throw new IllegalStateException("Missing required property: name"); - }); - } + EdgeNGramTokenizer deserializedEdgeNGramTokenizer = new EdgeNGramTokenizer(name); + deserializedEdgeNGramTokenizer.odataType = odataType; + deserializedEdgeNGramTokenizer.minGram = minGram; + deserializedEdgeNGramTokenizer.maxGram = maxGram; + deserializedEdgeNGramTokenizer.tokenChars = tokenChars; - /** - * Set the tokenChars property: Character classes to keep in the tokens. - * - * @param tokenChars the tokenChars value to set. - * @return the EdgeNGramTokenizer object itself. - */ - public EdgeNGramTokenizer setTokenChars(TokenCharacterKind... tokenChars) { - this.tokenChars = (tokenChars == null) ? null : Arrays.asList(tokenChars); - return this; + return deserializedEdgeNGramTokenizer; + }); } } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/ElisionTokenFilter.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/ElisionTokenFilter.java similarity index 71% rename from sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/ElisionTokenFilter.java rename to sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/ElisionTokenFilter.java index c10dd116c2d2..df17c1ebd9ba 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/ElisionTokenFilter.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/ElisionTokenFilter.java @@ -1,49 +1,51 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. -package com.azure.search.documents.indexes.models; +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.search.documents.models; import com.azure.core.annotation.Fluent; +import com.azure.core.annotation.Generated; import com.azure.json.JsonReader; import com.azure.json.JsonToken; import com.azure.json.JsonWriter; import java.io.IOException; -import java.util.Arrays; import java.util.List; /** - * Removes elisions. For example, "l'avion" (the plane) will be converted to "avion" (plane). This token filter is - * implemented using Apache Lucene. + * Removes elisions. For example, "l'avion" (the plane) will be converted to + * "avion" (plane). This token filter is implemented using Apache Lucene. */ @Fluent public final class ElisionTokenFilter extends TokenFilter { - /* - * A URI fragment specifying the type of token filter. + * The discriminator for derived types. */ + @Generated private String odataType = "#Microsoft.Azure.Search.ElisionTokenFilter"; /* * The set of articles to remove. */ + @Generated private List articles; /** * Creates an instance of ElisionTokenFilter class. - * + * * @param name the name value to set. */ + @Generated public ElisionTokenFilter(String name) { super(name); } /** - * Get the odataType property: A URI fragment specifying the type of token filter. - * + * Get the odataType property: The discriminator for derived types. + * * @return the odataType value. */ + @Generated @Override public String getOdataType() { return this.odataType; @@ -51,19 +53,21 @@ public String getOdataType() { /** * Get the articles property: The set of articles to remove. - * + * * @return the articles value. */ + @Generated public List getArticles() { return this.articles; } /** * Set the articles property: The set of articles to remove. - * + * * @param articles the articles value to set. * @return the ElisionTokenFilter object itself. */ + @Generated public ElisionTokenFilter setArticles(List articles) { this.articles = articles; return this; @@ -72,6 +76,7 @@ public ElisionTokenFilter setArticles(List articles) { /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); @@ -83,25 +88,25 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of ElisionTokenFilter from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of ElisionTokenFilter if the JsonReader was pointing to an instance of it, or null if it was * pointing to JSON null. * @throws IllegalStateException If the deserialized JSON object was missing any required properties. * @throws IOException If an error occurs while reading the ElisionTokenFilter. */ + @Generated public static ElisionTokenFilter fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { - boolean nameFound = false; String name = null; String odataType = "#Microsoft.Azure.Search.ElisionTokenFilter"; List articles = null; while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); + if ("name".equals(fieldName)) { name = reader.getString(); - nameFound = true; } else if ("@odata.type".equals(fieldName)) { odataType = reader.getString(); } else if ("articles".equals(fieldName)) { @@ -110,24 +115,11 @@ public static ElisionTokenFilter fromJson(JsonReader jsonReader) throws IOExcept reader.skipChildren(); } } - if (nameFound) { - ElisionTokenFilter deserializedElisionTokenFilter = new ElisionTokenFilter(name); - deserializedElisionTokenFilter.odataType = odataType; - deserializedElisionTokenFilter.articles = articles; - return deserializedElisionTokenFilter; - } - throw new IllegalStateException("Missing required property: name"); - }); - } + ElisionTokenFilter deserializedElisionTokenFilter = new ElisionTokenFilter(name); + deserializedElisionTokenFilter.odataType = odataType; + deserializedElisionTokenFilter.articles = articles; - /** - * Set the articles property: The set of articles to remove. - * - * @param articles the articles value to set. - * @return the ElisionTokenFilter object itself. - */ - public ElisionTokenFilter setArticles(String... articles) { - this.articles = (articles == null) ? null : Arrays.asList(articles); - return this; + return deserializedElisionTokenFilter; + }); } } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/EntityCategory.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/EntityCategory.java similarity index 86% rename from sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/EntityCategory.java rename to sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/EntityCategory.java index 9c5f6b18c133..0de8528706da 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/EntityCategory.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/EntityCategory.java @@ -1,11 +1,10 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) TypeSpec Code Generator. -package com.azure.search.documents.indexes.models; +package com.azure.search.documents.models; +import com.azure.core.annotation.Generated; import com.azure.core.util.ExpandableStringEnum; import java.util.Collection; @@ -16,36 +15,43 @@ public final class EntityCategory extends ExpandableStringEnum { /** * Entities describing a physical location. */ + @Generated public static final EntityCategory LOCATION = fromString("location"); /** * Entities describing an organization. */ + @Generated public static final EntityCategory ORGANIZATION = fromString("organization"); /** * Entities describing a person. */ + @Generated public static final EntityCategory PERSON = fromString("person"); /** * Entities describing a quantity. */ + @Generated public static final EntityCategory QUANTITY = fromString("quantity"); /** * Entities describing a date and time. */ + @Generated public static final EntityCategory DATETIME = fromString("datetime"); /** * Entities describing a URL. */ + @Generated public static final EntityCategory URL = fromString("url"); /** * Entities describing an email address. */ + @Generated public static final EntityCategory EMAIL = fromString("email"); /** @@ -53,6 +59,7 @@ public final class EntityCategory extends ExpandableStringEnum { * * @deprecated Use the {@link #fromString(String)} factory method. */ + @Generated @Deprecated public EntityCategory() { } @@ -63,6 +70,7 @@ public EntityCategory() { * @param name a name to look for. * @return the corresponding EntityCategory. */ + @Generated public static EntityCategory fromString(String name) { return fromString(name, EntityCategory.class); } @@ -72,6 +80,7 @@ public static EntityCategory fromString(String name) { * * @return known EntityCategory values. */ + @Generated public static Collection values() { return values(EntityCategory.class); } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/EntityLinkingSkill.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/EntityLinkingSkill.java similarity index 74% rename from sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/EntityLinkingSkill.java rename to sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/EntityLinkingSkill.java index e10ad6ab9e2a..5ca2bcc3c2b3 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/EntityLinkingSkill.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/EntityLinkingSkill.java @@ -1,17 +1,15 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) TypeSpec Code Generator. -package com.azure.search.documents.indexes.models; +package com.azure.search.documents.models; import com.azure.core.annotation.Fluent; +import com.azure.core.annotation.Generated; import com.azure.json.JsonReader; import com.azure.json.JsonToken; import com.azure.json.JsonWriter; import java.io.IOException; -import java.util.ArrayList; import java.util.List; /** @@ -20,25 +18,31 @@ @Fluent public final class EntityLinkingSkill extends SearchIndexerSkill { /* - * A URI fragment specifying the type of skill. + * The discriminator for derived types. */ + @Generated private String odataType = "#Microsoft.Skills.Text.V3.EntityLinkingSkill"; /* * A value indicating which language code to use. Default is `en`. */ + @Generated private String defaultLanguageCode; /* - * 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. + * 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. */ + @Generated private Double minimumPrecision; /* - * 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. + * 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. */ + @Generated private String modelVersion; /** @@ -47,15 +51,17 @@ public final class EntityLinkingSkill extends SearchIndexerSkill { * @param inputs the inputs value to set. * @param outputs the outputs value to set. */ + @Generated public EntityLinkingSkill(List inputs, List outputs) { super(inputs, outputs); } /** - * Get the odataType property: A URI fragment specifying the type of skill. + * Get the odataType property: The discriminator for derived types. * * @return the odataType value. */ + @Generated @Override public String getOdataType() { return this.odataType; @@ -66,6 +72,7 @@ public String getOdataType() { * * @return the defaultLanguageCode value. */ + @Generated public String getDefaultLanguageCode() { return this.defaultLanguageCode; } @@ -76,6 +83,7 @@ public String getDefaultLanguageCode() { * @param defaultLanguageCode the defaultLanguageCode value to set. * @return the EntityLinkingSkill object itself. */ + @Generated public EntityLinkingSkill setDefaultLanguageCode(String defaultLanguageCode) { this.defaultLanguageCode = defaultLanguageCode; return this; @@ -83,47 +91,51 @@ public EntityLinkingSkill setDefaultLanguageCode(String defaultLanguageCode) { /** * Get the minimumPrecision property: 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. + * score is greater than the value specified. If not set (default), or if + * explicitly set to null, all entities will be included. * * @return the minimumPrecision value. */ + @Generated public Double getMinimumPrecision() { return this.minimumPrecision; } /** * Set the minimumPrecision property: 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. + * score is greater than the value specified. If not set (default), or if + * explicitly set to null, all entities will be included. * * @param minimumPrecision the minimumPrecision value to set. * @return the EntityLinkingSkill object itself. */ + @Generated public EntityLinkingSkill setMinimumPrecision(Double minimumPrecision) { this.minimumPrecision = minimumPrecision; return this; } /** - * Get the modelVersion property: 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. + * Get the modelVersion property: 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. * * @return the modelVersion value. */ + @Generated public String getModelVersion() { return this.modelVersion; } /** - * Set the modelVersion property: 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. + * Set the modelVersion property: 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. * * @param modelVersion the modelVersion value to set. * @return the EntityLinkingSkill object itself. */ + @Generated public EntityLinkingSkill setModelVersion(String modelVersion) { this.modelVersion = modelVersion; return this; @@ -132,6 +144,7 @@ public EntityLinkingSkill setModelVersion(String modelVersion) { /** * {@inheritDoc} */ + @Generated @Override public EntityLinkingSkill setName(String name) { super.setName(name); @@ -141,6 +154,7 @@ public EntityLinkingSkill setName(String name) { /** * {@inheritDoc} */ + @Generated @Override public EntityLinkingSkill setDescription(String description) { super.setDescription(description); @@ -150,6 +164,7 @@ public EntityLinkingSkill setDescription(String description) { /** * {@inheritDoc} */ + @Generated @Override public EntityLinkingSkill setContext(String context) { super.setContext(context); @@ -159,6 +174,7 @@ public EntityLinkingSkill setContext(String context) { /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); @@ -183,11 +199,10 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { * @throws IllegalStateException If the deserialized JSON object was missing any required properties. * @throws IOException If an error occurs while reading the EntityLinkingSkill. */ + @Generated public static EntityLinkingSkill fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { - boolean inputsFound = false; List inputs = null; - boolean outputsFound = false; List outputs = null; String name = null; String description = null; @@ -202,10 +217,8 @@ public static EntityLinkingSkill fromJson(JsonReader jsonReader) throws IOExcept if ("inputs".equals(fieldName)) { inputs = reader.readArray(reader1 -> InputFieldMappingEntry.fromJson(reader1)); - inputsFound = true; } else if ("outputs".equals(fieldName)) { outputs = reader.readArray(reader1 -> OutputFieldMappingEntry.fromJson(reader1)); - outputsFound = true; } else if ("name".equals(fieldName)) { name = reader.getString(); } else if ("description".equals(fieldName)) { @@ -224,28 +237,16 @@ public static EntityLinkingSkill fromJson(JsonReader jsonReader) throws IOExcept reader.skipChildren(); } } - if (inputsFound && outputsFound) { - EntityLinkingSkill deserializedEntityLinkingSkill = new EntityLinkingSkill(inputs, outputs); - deserializedEntityLinkingSkill.setName(name); - deserializedEntityLinkingSkill.setDescription(description); - deserializedEntityLinkingSkill.setContext(context); - deserializedEntityLinkingSkill.odataType = odataType; - deserializedEntityLinkingSkill.defaultLanguageCode = defaultLanguageCode; - deserializedEntityLinkingSkill.minimumPrecision = minimumPrecision; - deserializedEntityLinkingSkill.modelVersion = modelVersion; - - return deserializedEntityLinkingSkill; - } - List missingProperties = new ArrayList<>(); - if (!inputsFound) { - missingProperties.add("inputs"); - } - if (!outputsFound) { - missingProperties.add("outputs"); - } - - throw new IllegalStateException( - "Missing required property/properties: " + String.join(", ", missingProperties)); + EntityLinkingSkill deserializedEntityLinkingSkill = new EntityLinkingSkill(inputs, outputs); + deserializedEntityLinkingSkill.setName(name); + deserializedEntityLinkingSkill.setDescription(description); + deserializedEntityLinkingSkill.setContext(context); + deserializedEntityLinkingSkill.odataType = odataType; + deserializedEntityLinkingSkill.defaultLanguageCode = defaultLanguageCode; + deserializedEntityLinkingSkill.minimumPrecision = minimumPrecision; + deserializedEntityLinkingSkill.modelVersion = modelVersion; + + return deserializedEntityLinkingSkill; }); } } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/implementation/models/EntityRecognitionSkillV1.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/EntityRecognitionSkill.java similarity index 62% rename from sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/implementation/models/EntityRecognitionSkillV1.java rename to sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/EntityRecognitionSkill.java index 2375520b7576..104c94b69177 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/implementation/models/EntityRecognitionSkillV1.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/EntityRecognitionSkill.java @@ -1,72 +1,74 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) TypeSpec Code Generator. -package com.azure.search.documents.indexes.implementation.models; +package com.azure.search.documents.models; import com.azure.core.annotation.Fluent; +import com.azure.core.annotation.Generated; import com.azure.json.JsonReader; import com.azure.json.JsonToken; import com.azure.json.JsonWriter; -import com.azure.search.documents.indexes.models.EntityCategory; -import com.azure.search.documents.indexes.models.EntityRecognitionSkillLanguage; -import com.azure.search.documents.indexes.models.InputFieldMappingEntry; -import com.azure.search.documents.indexes.models.OutputFieldMappingEntry; -import com.azure.search.documents.indexes.models.SearchIndexerSkill; import java.io.IOException; -import java.util.ArrayList; import java.util.List; /** * This skill is deprecated. Use the V3.EntityRecognitionSkill instead. */ @Fluent -public final class EntityRecognitionSkillV1 extends SearchIndexerSkill { +public final class EntityRecognitionSkill extends SearchIndexerSkill { /* - * A URI fragment specifying the type of skill. + * The discriminator for derived types. */ + @Generated private String odataType = "#Microsoft.Skills.Text.EntityRecognitionSkill"; /* * A list of entity categories that should be extracted. */ + @Generated private List categories; /* * A value indicating which language code to use. Default is `en`. */ + @Generated private EntityRecognitionSkillLanguage defaultLanguageCode; /* - * 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. + * 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. */ + @Generated private Boolean includeTypelessEntities; /* - * 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. + * 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. */ + @Generated private Double minimumPrecision; /** - * Creates an instance of EntityRecognitionSkillV1 class. + * Creates an instance of EntityRecognitionSkill class. * * @param inputs the inputs value to set. * @param outputs the outputs value to set. */ - public EntityRecognitionSkillV1(List inputs, List outputs) { + @Generated + public EntityRecognitionSkill(List inputs, List outputs) { super(inputs, outputs); } /** - * Get the odataType property: A URI fragment specifying the type of skill. + * Get the odataType property: The discriminator for derived types. * * @return the odataType value. */ + @Generated @Override public String getOdataType() { return this.odataType; @@ -77,6 +79,7 @@ public String getOdataType() { * * @return the categories value. */ + @Generated public List getCategories() { return this.categories; } @@ -85,9 +88,10 @@ public List getCategories() { * Set the categories property: A list of entity categories that should be extracted. * * @param categories the categories value to set. - * @return the EntityRecognitionSkillV1 object itself. + * @return the EntityRecognitionSkill object itself. */ - public EntityRecognitionSkillV1 setCategories(List categories) { + @Generated + public EntityRecognitionSkill setCategories(List categories) { this.categories = categories; return this; } @@ -97,6 +101,7 @@ public EntityRecognitionSkillV1 setCategories(List categories) { * * @return the defaultLanguageCode value. */ + @Generated public EntityRecognitionSkillLanguage getDefaultLanguageCode() { return this.defaultLanguageCode; } @@ -105,57 +110,66 @@ public EntityRecognitionSkillLanguage getDefaultLanguageCode() { * Set the defaultLanguageCode property: A value indicating which language code to use. Default is `en`. * * @param defaultLanguageCode the defaultLanguageCode value to set. - * @return the EntityRecognitionSkillV1 object itself. + * @return the EntityRecognitionSkill object itself. */ - public EntityRecognitionSkillV1 setDefaultLanguageCode(EntityRecognitionSkillLanguage defaultLanguageCode) { + @Generated + public EntityRecognitionSkill setDefaultLanguageCode(EntityRecognitionSkillLanguage defaultLanguageCode) { this.defaultLanguageCode = defaultLanguageCode; return this; } /** * Get the includeTypelessEntities property: 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. + * 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. * * @return the includeTypelessEntities value. */ + @Generated public Boolean isIncludeTypelessEntities() { return this.includeTypelessEntities; } /** * Set the includeTypelessEntities property: 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. + * 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. * * @param includeTypelessEntities the includeTypelessEntities value to set. - * @return the EntityRecognitionSkillV1 object itself. + * @return the EntityRecognitionSkill object itself. */ - public EntityRecognitionSkillV1 setIncludeTypelessEntities(Boolean includeTypelessEntities) { + @Generated + public EntityRecognitionSkill setIncludeTypelessEntities(Boolean includeTypelessEntities) { this.includeTypelessEntities = includeTypelessEntities; return this; } /** * Get the minimumPrecision property: 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. + * score is greater than the value specified. If not set (default), or if + * explicitly set to null, all entities will be included. * * @return the minimumPrecision value. */ + @Generated public Double getMinimumPrecision() { return this.minimumPrecision; } /** * Set the minimumPrecision property: 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. + * score is greater than the value specified. If not set (default), or if + * explicitly set to null, all entities will be included. * * @param minimumPrecision the minimumPrecision value to set. - * @return the EntityRecognitionSkillV1 object itself. + * @return the EntityRecognitionSkill object itself. */ - public EntityRecognitionSkillV1 setMinimumPrecision(Double minimumPrecision) { + @Generated + public EntityRecognitionSkill setMinimumPrecision(Double minimumPrecision) { this.minimumPrecision = minimumPrecision; return this; } @@ -163,8 +177,9 @@ public EntityRecognitionSkillV1 setMinimumPrecision(Double minimumPrecision) { /** * {@inheritDoc} */ + @Generated @Override - public EntityRecognitionSkillV1 setName(String name) { + public EntityRecognitionSkill setName(String name) { super.setName(name); return this; } @@ -172,8 +187,9 @@ public EntityRecognitionSkillV1 setName(String name) { /** * {@inheritDoc} */ + @Generated @Override - public EntityRecognitionSkillV1 setDescription(String description) { + public EntityRecognitionSkill setDescription(String description) { super.setDescription(description); return this; } @@ -181,8 +197,9 @@ public EntityRecognitionSkillV1 setDescription(String description) { /** * {@inheritDoc} */ + @Generated @Override - public EntityRecognitionSkillV1 setContext(String context) { + public EntityRecognitionSkill setContext(String context) { super.setContext(context); return this; } @@ -190,6 +207,7 @@ public EntityRecognitionSkillV1 setContext(String context) { /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); @@ -209,19 +227,18 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { } /** - * Reads an instance of EntityRecognitionSkillV1 from the JsonReader. + * Reads an instance of EntityRecognitionSkill from the JsonReader. * * @param jsonReader The JsonReader being read. - * @return An instance of EntityRecognitionSkillV1 if the JsonReader was pointing to an instance of it, or null if - * it was pointing to JSON null. + * @return An instance of EntityRecognitionSkill if the JsonReader was pointing to an instance of it, or null if it + * was pointing to JSON null. * @throws IllegalStateException If the deserialized JSON object was missing any required properties. - * @throws IOException If an error occurs while reading the EntityRecognitionSkillV1. + * @throws IOException If an error occurs while reading the EntityRecognitionSkill. */ - public static EntityRecognitionSkillV1 fromJson(JsonReader jsonReader) throws IOException { + @Generated + public static EntityRecognitionSkill fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { - boolean inputsFound = false; List inputs = null; - boolean outputsFound = false; List outputs = null; String name = null; String description = null; @@ -237,10 +254,8 @@ public static EntityRecognitionSkillV1 fromJson(JsonReader jsonReader) throws IO if ("inputs".equals(fieldName)) { inputs = reader.readArray(reader1 -> InputFieldMappingEntry.fromJson(reader1)); - inputsFound = true; } else if ("outputs".equals(fieldName)) { outputs = reader.readArray(reader1 -> OutputFieldMappingEntry.fromJson(reader1)); - outputsFound = true; } else if ("name".equals(fieldName)) { name = reader.getString(); } else if ("description".equals(fieldName)) { @@ -261,30 +276,17 @@ public static EntityRecognitionSkillV1 fromJson(JsonReader jsonReader) throws IO reader.skipChildren(); } } - if (inputsFound && outputsFound) { - EntityRecognitionSkillV1 deserializedEntityRecognitionSkillV1 - = new EntityRecognitionSkillV1(inputs, outputs); - deserializedEntityRecognitionSkillV1.setName(name); - deserializedEntityRecognitionSkillV1.setDescription(description); - deserializedEntityRecognitionSkillV1.setContext(context); - deserializedEntityRecognitionSkillV1.odataType = odataType; - deserializedEntityRecognitionSkillV1.categories = categories; - deserializedEntityRecognitionSkillV1.defaultLanguageCode = defaultLanguageCode; - deserializedEntityRecognitionSkillV1.includeTypelessEntities = includeTypelessEntities; - deserializedEntityRecognitionSkillV1.minimumPrecision = minimumPrecision; + EntityRecognitionSkill deserializedEntityRecognitionSkill = new EntityRecognitionSkill(inputs, outputs); + deserializedEntityRecognitionSkill.setName(name); + deserializedEntityRecognitionSkill.setDescription(description); + deserializedEntityRecognitionSkill.setContext(context); + deserializedEntityRecognitionSkill.odataType = odataType; + deserializedEntityRecognitionSkill.categories = categories; + deserializedEntityRecognitionSkill.defaultLanguageCode = defaultLanguageCode; + deserializedEntityRecognitionSkill.includeTypelessEntities = includeTypelessEntities; + deserializedEntityRecognitionSkill.minimumPrecision = minimumPrecision; - return deserializedEntityRecognitionSkillV1; - } - List missingProperties = new ArrayList<>(); - if (!inputsFound) { - missingProperties.add("inputs"); - } - if (!outputsFound) { - missingProperties.add("outputs"); - } - - throw new IllegalStateException( - "Missing required property/properties: " + String.join(", ", missingProperties)); + return deserializedEntityRecognitionSkill; }); } } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/EntityRecognitionSkillLanguage.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/EntityRecognitionSkillLanguage.java similarity index 85% rename from sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/EntityRecognitionSkillLanguage.java rename to sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/EntityRecognitionSkillLanguage.java index 7b957df0367a..ebbe6d7e921c 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/EntityRecognitionSkillLanguage.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/EntityRecognitionSkillLanguage.java @@ -1,131 +1,154 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) TypeSpec Code Generator. -package com.azure.search.documents.indexes.models; +package com.azure.search.documents.models; +import com.azure.core.annotation.Generated; import com.azure.core.util.ExpandableStringEnum; import java.util.Collection; /** - * Deprecated. The language codes supported for input text by EntityRecognitionSkill. + * Deprecated. The language codes supported for input text by + * EntityRecognitionSkill. */ public final class EntityRecognitionSkillLanguage extends ExpandableStringEnum { /** * Arabic. */ + @Generated public static final EntityRecognitionSkillLanguage AR = fromString("ar"); /** * Czech. */ + @Generated public static final EntityRecognitionSkillLanguage CS = fromString("cs"); /** * Chinese-Simplified. */ + @Generated public static final EntityRecognitionSkillLanguage ZH_HANS = fromString("zh-Hans"); /** * Chinese-Traditional. */ + @Generated public static final EntityRecognitionSkillLanguage ZH_HANT = fromString("zh-Hant"); /** * Danish. */ + @Generated public static final EntityRecognitionSkillLanguage DA = fromString("da"); /** * Dutch. */ + @Generated public static final EntityRecognitionSkillLanguage NL = fromString("nl"); /** * English. */ + @Generated public static final EntityRecognitionSkillLanguage EN = fromString("en"); /** * Finnish. */ + @Generated public static final EntityRecognitionSkillLanguage FI = fromString("fi"); /** * French. */ + @Generated public static final EntityRecognitionSkillLanguage FR = fromString("fr"); /** * German. */ + @Generated public static final EntityRecognitionSkillLanguage DE = fromString("de"); /** * Greek. */ + @Generated public static final EntityRecognitionSkillLanguage EL = fromString("el"); /** * Hungarian. */ + @Generated public static final EntityRecognitionSkillLanguage HU = fromString("hu"); /** * Italian. */ + @Generated public static final EntityRecognitionSkillLanguage IT = fromString("it"); /** * Japanese. */ + @Generated public static final EntityRecognitionSkillLanguage JA = fromString("ja"); /** * Korean. */ + @Generated public static final EntityRecognitionSkillLanguage KO = fromString("ko"); /** * Norwegian (Bokmaal). */ + @Generated public static final EntityRecognitionSkillLanguage NO = fromString("no"); /** * Polish. */ + @Generated public static final EntityRecognitionSkillLanguage PL = fromString("pl"); /** * Portuguese (Portugal). */ + @Generated public static final EntityRecognitionSkillLanguage PT_PT = fromString("pt-PT"); /** * Portuguese (Brazil). */ + @Generated public static final EntityRecognitionSkillLanguage PT_BR = fromString("pt-BR"); /** * Russian. */ + @Generated public static final EntityRecognitionSkillLanguage RU = fromString("ru"); /** * Spanish. */ + @Generated public static final EntityRecognitionSkillLanguage ES = fromString("es"); /** * Swedish. */ + @Generated public static final EntityRecognitionSkillLanguage SV = fromString("sv"); /** * Turkish. */ + @Generated public static final EntityRecognitionSkillLanguage TR = fromString("tr"); /** @@ -133,6 +156,7 @@ public final class EntityRecognitionSkillLanguage extends ExpandableStringEnum values() { return values(EntityRecognitionSkillLanguage.class); } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/implementation/models/EntityRecognitionSkillV3.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/EntityRecognitionSkillV3.java similarity index 76% rename from sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/implementation/models/EntityRecognitionSkillV3.java rename to sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/EntityRecognitionSkillV3.java index 3b5ba12e229d..f8694a95421b 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/implementation/models/EntityRecognitionSkillV3.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/EntityRecognitionSkillV3.java @@ -1,20 +1,15 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) TypeSpec Code Generator. -package com.azure.search.documents.indexes.implementation.models; +package com.azure.search.documents.models; import com.azure.core.annotation.Fluent; +import com.azure.core.annotation.Generated; import com.azure.json.JsonReader; import com.azure.json.JsonToken; import com.azure.json.JsonWriter; -import com.azure.search.documents.indexes.models.InputFieldMappingEntry; -import com.azure.search.documents.indexes.models.OutputFieldMappingEntry; -import com.azure.search.documents.indexes.models.SearchIndexerSkill; import java.io.IOException; -import java.util.ArrayList; import java.util.List; /** @@ -23,30 +18,37 @@ @Fluent public final class EntityRecognitionSkillV3 extends SearchIndexerSkill { /* - * A URI fragment specifying the type of skill. + * The discriminator for derived types. */ + @Generated private String odataType = "#Microsoft.Skills.Text.V3.EntityRecognitionSkill"; /* * A list of entity categories that should be extracted. */ + @Generated private List categories; /* * A value indicating which language code to use. Default is `en`. */ + @Generated private String defaultLanguageCode; /* - * 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. + * 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. */ + @Generated private Double minimumPrecision; /* - * 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. + * 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. */ + @Generated private String modelVersion; /** @@ -55,15 +57,17 @@ public final class EntityRecognitionSkillV3 extends SearchIndexerSkill { * @param inputs the inputs value to set. * @param outputs the outputs value to set. */ + @Generated public EntityRecognitionSkillV3(List inputs, List outputs) { super(inputs, outputs); } /** - * Get the odataType property: A URI fragment specifying the type of skill. + * Get the odataType property: The discriminator for derived types. * * @return the odataType value. */ + @Generated @Override public String getOdataType() { return this.odataType; @@ -74,6 +78,7 @@ public String getOdataType() { * * @return the categories value. */ + @Generated public List getCategories() { return this.categories; } @@ -84,6 +89,7 @@ public List getCategories() { * @param categories the categories value to set. * @return the EntityRecognitionSkillV3 object itself. */ + @Generated public EntityRecognitionSkillV3 setCategories(List categories) { this.categories = categories; return this; @@ -94,6 +100,7 @@ public EntityRecognitionSkillV3 setCategories(List categories) { * * @return the defaultLanguageCode value. */ + @Generated public String getDefaultLanguageCode() { return this.defaultLanguageCode; } @@ -104,6 +111,7 @@ public String getDefaultLanguageCode() { * @param defaultLanguageCode the defaultLanguageCode value to set. * @return the EntityRecognitionSkillV3 object itself. */ + @Generated public EntityRecognitionSkillV3 setDefaultLanguageCode(String defaultLanguageCode) { this.defaultLanguageCode = defaultLanguageCode; return this; @@ -111,23 +119,25 @@ public EntityRecognitionSkillV3 setDefaultLanguageCode(String defaultLanguageCod /** * Get the minimumPrecision property: 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. + * score is greater than the value specified. If not set (default), or if + * explicitly set to null, all entities will be included. * * @return the minimumPrecision value. */ + @Generated public Double getMinimumPrecision() { return this.minimumPrecision; } /** * Set the minimumPrecision property: 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. + * score is greater than the value specified. If not set (default), or if + * explicitly set to null, all entities will be included. * * @param minimumPrecision the minimumPrecision value to set. * @return the EntityRecognitionSkillV3 object itself. */ + @Generated public EntityRecognitionSkillV3 setMinimumPrecision(Double minimumPrecision) { this.minimumPrecision = minimumPrecision; return this; @@ -135,23 +145,25 @@ public EntityRecognitionSkillV3 setMinimumPrecision(Double minimumPrecision) { /** * Get the modelVersion property: 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. + * default to the latest available when not specified. We recommend you do not + * specify this value unless absolutely necessary. * * @return the modelVersion value. */ + @Generated public String getModelVersion() { return this.modelVersion; } /** * Set the modelVersion property: 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. + * default to the latest available when not specified. We recommend you do not + * specify this value unless absolutely necessary. * * @param modelVersion the modelVersion value to set. * @return the EntityRecognitionSkillV3 object itself. */ + @Generated public EntityRecognitionSkillV3 setModelVersion(String modelVersion) { this.modelVersion = modelVersion; return this; @@ -160,6 +172,7 @@ public EntityRecognitionSkillV3 setModelVersion(String modelVersion) { /** * {@inheritDoc} */ + @Generated @Override public EntityRecognitionSkillV3 setName(String name) { super.setName(name); @@ -169,6 +182,7 @@ public EntityRecognitionSkillV3 setName(String name) { /** * {@inheritDoc} */ + @Generated @Override public EntityRecognitionSkillV3 setDescription(String description) { super.setDescription(description); @@ -178,6 +192,7 @@ public EntityRecognitionSkillV3 setDescription(String description) { /** * {@inheritDoc} */ + @Generated @Override public EntityRecognitionSkillV3 setContext(String context) { super.setContext(context); @@ -187,6 +202,7 @@ public EntityRecognitionSkillV3 setContext(String context) { /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); @@ -212,11 +228,10 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { * @throws IllegalStateException If the deserialized JSON object was missing any required properties. * @throws IOException If an error occurs while reading the EntityRecognitionSkillV3. */ + @Generated public static EntityRecognitionSkillV3 fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { - boolean inputsFound = false; List inputs = null; - boolean outputsFound = false; List outputs = null; String name = null; String description = null; @@ -232,10 +247,8 @@ public static EntityRecognitionSkillV3 fromJson(JsonReader jsonReader) throws IO if ("inputs".equals(fieldName)) { inputs = reader.readArray(reader1 -> InputFieldMappingEntry.fromJson(reader1)); - inputsFound = true; } else if ("outputs".equals(fieldName)) { outputs = reader.readArray(reader1 -> OutputFieldMappingEntry.fromJson(reader1)); - outputsFound = true; } else if ("name".equals(fieldName)) { name = reader.getString(); } else if ("description".equals(fieldName)) { @@ -256,30 +269,18 @@ public static EntityRecognitionSkillV3 fromJson(JsonReader jsonReader) throws IO reader.skipChildren(); } } - if (inputsFound && outputsFound) { - EntityRecognitionSkillV3 deserializedEntityRecognitionSkillV3 - = new EntityRecognitionSkillV3(inputs, outputs); - deserializedEntityRecognitionSkillV3.setName(name); - deserializedEntityRecognitionSkillV3.setDescription(description); - deserializedEntityRecognitionSkillV3.setContext(context); - deserializedEntityRecognitionSkillV3.odataType = odataType; - deserializedEntityRecognitionSkillV3.categories = categories; - deserializedEntityRecognitionSkillV3.defaultLanguageCode = defaultLanguageCode; - deserializedEntityRecognitionSkillV3.minimumPrecision = minimumPrecision; - deserializedEntityRecognitionSkillV3.modelVersion = modelVersion; + EntityRecognitionSkillV3 deserializedEntityRecognitionSkillV3 + = new EntityRecognitionSkillV3(inputs, outputs); + deserializedEntityRecognitionSkillV3.setName(name); + deserializedEntityRecognitionSkillV3.setDescription(description); + deserializedEntityRecognitionSkillV3.setContext(context); + deserializedEntityRecognitionSkillV3.odataType = odataType; + deserializedEntityRecognitionSkillV3.categories = categories; + deserializedEntityRecognitionSkillV3.defaultLanguageCode = defaultLanguageCode; + deserializedEntityRecognitionSkillV3.minimumPrecision = minimumPrecision; + deserializedEntityRecognitionSkillV3.modelVersion = modelVersion; - return deserializedEntityRecognitionSkillV3; - } - List missingProperties = new ArrayList<>(); - if (!inputsFound) { - missingProperties.add("inputs"); - } - if (!outputsFound) { - missingProperties.add("outputs"); - } - - throw new IllegalStateException( - "Missing required property/properties: " + String.join(", ", missingProperties)); + return deserializedEntityRecognitionSkillV3; }); } } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/ExhaustiveKnnAlgorithmConfiguration.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/ExhaustiveKnnAlgorithmConfiguration.java similarity index 76% rename from sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/ExhaustiveKnnAlgorithmConfiguration.java rename to sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/ExhaustiveKnnAlgorithmConfiguration.java index c5aeaf63d537..0e54a930af81 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/ExhaustiveKnnAlgorithmConfiguration.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/ExhaustiveKnnAlgorithmConfiguration.java @@ -1,31 +1,33 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) TypeSpec Code Generator. -package com.azure.search.documents.indexes.models; +package com.azure.search.documents.models; import com.azure.core.annotation.Fluent; +import com.azure.core.annotation.Generated; import com.azure.json.JsonReader; import com.azure.json.JsonToken; import com.azure.json.JsonWriter; import java.io.IOException; /** - * Contains configuration options specific to the exhaustive KNN algorithm used during querying, which will perform - * brute-force search across the entire vector index. + * Contains configuration options specific to the exhaustive KNN algorithm used + * during querying, which will perform brute-force search across the entire vector + * index. */ @Fluent public final class ExhaustiveKnnAlgorithmConfiguration extends VectorSearchAlgorithmConfiguration { /* - * The name of the kind of algorithm being configured for use with vector search. + * Type of VectorSearchAlgorithmConfiguration. */ + @Generated private VectorSearchAlgorithmKind kind = VectorSearchAlgorithmKind.EXHAUSTIVE_KNN; /* * Contains the parameters specific to exhaustive KNN algorithm. */ + @Generated private ExhaustiveKnnParameters parameters; /** @@ -33,15 +35,17 @@ public final class ExhaustiveKnnAlgorithmConfiguration extends VectorSearchAlgor * * @param name the name value to set. */ + @Generated public ExhaustiveKnnAlgorithmConfiguration(String name) { super(name); } /** - * Get the kind property: The name of the kind of algorithm being configured for use with vector search. + * Get the kind property: Type of VectorSearchAlgorithmConfiguration. * * @return the kind value. */ + @Generated @Override public VectorSearchAlgorithmKind getKind() { return this.kind; @@ -52,6 +56,7 @@ public VectorSearchAlgorithmKind getKind() { * * @return the parameters value. */ + @Generated public ExhaustiveKnnParameters getParameters() { return this.parameters; } @@ -62,6 +67,7 @@ public ExhaustiveKnnParameters getParameters() { * @param parameters the parameters value to set. * @return the ExhaustiveKnnAlgorithmConfiguration object itself. */ + @Generated public ExhaustiveKnnAlgorithmConfiguration setParameters(ExhaustiveKnnParameters parameters) { this.parameters = parameters; return this; @@ -70,6 +76,7 @@ public ExhaustiveKnnAlgorithmConfiguration setParameters(ExhaustiveKnnParameters /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); @@ -88,9 +95,9 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { * @throws IllegalStateException If the deserialized JSON object was missing any required properties. * @throws IOException If an error occurs while reading the ExhaustiveKnnAlgorithmConfiguration. */ + @Generated public static ExhaustiveKnnAlgorithmConfiguration fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { - boolean nameFound = false; String name = null; VectorSearchAlgorithmKind kind = VectorSearchAlgorithmKind.EXHAUSTIVE_KNN; ExhaustiveKnnParameters parameters = null; @@ -100,7 +107,6 @@ public static ExhaustiveKnnAlgorithmConfiguration fromJson(JsonReader jsonReader if ("name".equals(fieldName)) { name = reader.getString(); - nameFound = true; } else if ("kind".equals(fieldName)) { kind = VectorSearchAlgorithmKind.fromString(reader.getString()); } else if ("exhaustiveKnnParameters".equals(fieldName)) { @@ -109,15 +115,12 @@ public static ExhaustiveKnnAlgorithmConfiguration fromJson(JsonReader jsonReader reader.skipChildren(); } } - if (nameFound) { - ExhaustiveKnnAlgorithmConfiguration deserializedExhaustiveKnnAlgorithmConfiguration - = new ExhaustiveKnnAlgorithmConfiguration(name); - deserializedExhaustiveKnnAlgorithmConfiguration.kind = kind; - deserializedExhaustiveKnnAlgorithmConfiguration.parameters = parameters; + ExhaustiveKnnAlgorithmConfiguration deserializedExhaustiveKnnAlgorithmConfiguration + = new ExhaustiveKnnAlgorithmConfiguration(name); + deserializedExhaustiveKnnAlgorithmConfiguration.kind = kind; + deserializedExhaustiveKnnAlgorithmConfiguration.parameters = parameters; - return deserializedExhaustiveKnnAlgorithmConfiguration; - } - throw new IllegalStateException("Missing required property: name"); + return deserializedExhaustiveKnnAlgorithmConfiguration; }); } } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/ExhaustiveKnnParameters.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/ExhaustiveKnnParameters.java similarity index 92% rename from sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/ExhaustiveKnnParameters.java rename to sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/ExhaustiveKnnParameters.java index 1772039bf3e5..909ef26bb465 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/ExhaustiveKnnParameters.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/ExhaustiveKnnParameters.java @@ -1,12 +1,11 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) TypeSpec Code Generator. -package com.azure.search.documents.indexes.models; +package com.azure.search.documents.models; import com.azure.core.annotation.Fluent; +import com.azure.core.annotation.Generated; import com.azure.json.JsonReader; import com.azure.json.JsonSerializable; import com.azure.json.JsonToken; @@ -21,11 +20,13 @@ public final class ExhaustiveKnnParameters implements JsonSerializable { ExhaustiveKnnParameters deserializedExhaustiveKnnParameters = new ExhaustiveKnnParameters(); diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/FacetResult.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/FacetResult.java index 73004483df81..ebfbdc2f9ef3 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/FacetResult.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/FacetResult.java @@ -1,12 +1,12 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.search.documents.models; -import com.azure.core.annotation.Fluent; +import com.azure.core.annotation.Generated; +import com.azure.core.annotation.Immutable; +import com.azure.core.util.BinaryData; import com.azure.json.JsonReader; import com.azure.json.JsonSerializable; import com.azure.json.JsonToken; @@ -17,84 +17,110 @@ import java.util.Map; /** - * 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. + * 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. */ -@Fluent +@Immutable public final class FacetResult implements JsonSerializable { /* - * The approximate count of documents falling within the bucket described by this facet. + * The approximate count of documents falling within the bucket described by this + * facet. */ + @Generated private Long count; /* - * 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. + * 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. */ + @Generated private Map> facets; /* - * 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. + * The resulting total sum for the facet when a sum metric is requested. */ - private Map additionalProperties; + @Generated + private Long sum; + + /* + * 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. + */ + @Generated + private Map additionalProperties; /** * Creates an instance of FacetResult class. */ - public FacetResult() { + @Generated + private FacetResult() { } /** - * Get the count property: The approximate count of documents falling within the bucket described by this facet. + * Get the count property: The approximate count of documents falling within the bucket described by this + * facet. * * @return the count value. */ + @Generated public Long getCount() { return this.count; } /** - * Get the facets property: 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. + * Get the facets property: 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. * * @return the facets value. */ + @Generated public Map> getFacets() { return this.facets; } /** - * Get the additionalProperties property: 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. + * Get the sum property: The resulting total sum for the facet when a sum metric is requested. * - * @return the additionalProperties value. + * @return the sum value. */ - public Map getAdditionalProperties() { - return this.additionalProperties; + @Generated + public Long getSum() { + return this.sum; } /** - * Set the additionalProperties property: 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. + * Get the additionalProperties property: 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. * - * @param additionalProperties the additionalProperties value to set. - * @return the FacetResult object itself. + * @return the additionalProperties value. */ - public FacetResult setAdditionalProperties(Map additionalProperties) { - this.additionalProperties = additionalProperties; - return this; + @Generated + public Map getAdditionalProperties() { + return this.additionalProperties; } /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); + jsonWriter.writeNumberField("count", this.count); if (additionalProperties != null) { - for (Map.Entry additionalProperty : additionalProperties.entrySet()) { - jsonWriter.writeUntypedField(additionalProperty.getKey(), additionalProperty.getValue()); + for (Map.Entry additionalProperty : additionalProperties.entrySet()) { + jsonWriter.writeFieldName(additionalProperty.getKey()); + if (additionalProperty.getValue() == null) { + jsonWriter.writeNull(); + } else { + additionalProperty.getValue().writeTo(jsonWriter); + } } } return jsonWriter.writeEndObject(); @@ -108,10 +134,11 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { * pointing to JSON null. * @throws IOException If an error occurs while reading the FacetResult. */ + @Generated public static FacetResult fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { FacetResult deserializedFacetResult = new FacetResult(); - Map additionalProperties = null; + Map additionalProperties = null; while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); @@ -122,12 +149,15 @@ public static FacetResult fromJson(JsonReader jsonReader) throws IOException { Map> facets = reader.readMap(reader1 -> reader1.readArray(reader2 -> FacetResult.fromJson(reader2))); deserializedFacetResult.facets = facets; + } else if ("sum".equals(fieldName)) { + deserializedFacetResult.sum = reader.getNullable(JsonReader::getLong); } else { if (additionalProperties == null) { additionalProperties = new LinkedHashMap<>(); } - additionalProperties.put(fieldName, reader.readUntyped()); + additionalProperties.put(fieldName, + reader.getNullable(nonNullReader -> BinaryData.fromObject(nonNullReader.readUntyped()))); } } deserializedFacetResult.additionalProperties = additionalProperties; diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/FieldMapping.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/FieldMapping.java similarity index 85% rename from sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/FieldMapping.java rename to sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/FieldMapping.java index 501f00e4e445..bd49cbbc0ba4 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/FieldMapping.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/FieldMapping.java @@ -1,12 +1,11 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) TypeSpec Code Generator. -package com.azure.search.documents.indexes.models; +package com.azure.search.documents.models; import com.azure.core.annotation.Fluent; +import com.azure.core.annotation.Generated; import com.azure.json.JsonReader; import com.azure.json.JsonSerializable; import com.azure.json.JsonToken; @@ -14,23 +13,28 @@ import java.io.IOException; /** - * Defines a mapping between a field in a data source and a target field in an index. + * Defines a mapping between a field in a data source and a target field in an + * index. */ @Fluent public final class FieldMapping implements JsonSerializable { /* * The name of the field in the data source. */ + @Generated private final String sourceFieldName; /* - * The name of the target field in the index. Same as the source field name by default. + * The name of the target field in the index. Same as the source field name by + * default. */ + @Generated private String targetFieldName; /* * A function to apply to each source field value before indexing. */ + @Generated private FieldMappingFunction mappingFunction; /** @@ -38,6 +42,7 @@ public final class FieldMapping implements JsonSerializable { * * @param sourceFieldName the sourceFieldName value to set. */ + @Generated public FieldMapping(String sourceFieldName) { this.sourceFieldName = sourceFieldName; } @@ -47,6 +52,7 @@ public FieldMapping(String sourceFieldName) { * * @return the sourceFieldName value. */ + @Generated public String getSourceFieldName() { return this.sourceFieldName; } @@ -57,6 +63,7 @@ public String getSourceFieldName() { * * @return the targetFieldName value. */ + @Generated public String getTargetFieldName() { return this.targetFieldName; } @@ -68,6 +75,7 @@ public String getTargetFieldName() { * @param targetFieldName the targetFieldName value to set. * @return the FieldMapping object itself. */ + @Generated public FieldMapping setTargetFieldName(String targetFieldName) { this.targetFieldName = targetFieldName; return this; @@ -78,6 +86,7 @@ public FieldMapping setTargetFieldName(String targetFieldName) { * * @return the mappingFunction value. */ + @Generated public FieldMappingFunction getMappingFunction() { return this.mappingFunction; } @@ -88,6 +97,7 @@ public FieldMappingFunction getMappingFunction() { * @param mappingFunction the mappingFunction value to set. * @return the FieldMapping object itself. */ + @Generated public FieldMapping setMappingFunction(FieldMappingFunction mappingFunction) { this.mappingFunction = mappingFunction; return this; @@ -96,6 +106,7 @@ public FieldMapping setMappingFunction(FieldMappingFunction mappingFunction) { /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); @@ -114,9 +125,9 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { * @throws IllegalStateException If the deserialized JSON object was missing any required properties. * @throws IOException If an error occurs while reading the FieldMapping. */ + @Generated public static FieldMapping fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { - boolean sourceFieldNameFound = false; String sourceFieldName = null; String targetFieldName = null; FieldMappingFunction mappingFunction = null; @@ -126,7 +137,6 @@ public static FieldMapping fromJson(JsonReader jsonReader) throws IOException { if ("sourceFieldName".equals(fieldName)) { sourceFieldName = reader.getString(); - sourceFieldNameFound = true; } else if ("targetFieldName".equals(fieldName)) { targetFieldName = reader.getString(); } else if ("mappingFunction".equals(fieldName)) { @@ -135,14 +145,11 @@ public static FieldMapping fromJson(JsonReader jsonReader) throws IOException { reader.skipChildren(); } } - if (sourceFieldNameFound) { - FieldMapping deserializedFieldMapping = new FieldMapping(sourceFieldName); - deserializedFieldMapping.targetFieldName = targetFieldName; - deserializedFieldMapping.mappingFunction = mappingFunction; + FieldMapping deserializedFieldMapping = new FieldMapping(sourceFieldName); + deserializedFieldMapping.targetFieldName = targetFieldName; + deserializedFieldMapping.mappingFunction = mappingFunction; - return deserializedFieldMapping; - } - throw new IllegalStateException("Missing required property: sourceFieldName"); + return deserializedFieldMapping; }); } } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/FieldMappingFunction.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/FieldMappingFunction.java similarity index 69% rename from sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/FieldMappingFunction.java rename to sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/FieldMappingFunction.java index c77552ce57e1..871598404bc3 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/FieldMappingFunction.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/FieldMappingFunction.java @@ -1,12 +1,12 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) TypeSpec Code Generator. -package com.azure.search.documents.indexes.models; +package com.azure.search.documents.models; import com.azure.core.annotation.Fluent; +import com.azure.core.annotation.Generated; +import com.azure.core.util.BinaryData; import com.azure.json.JsonReader; import com.azure.json.JsonSerializable; import com.azure.json.JsonToken; @@ -15,25 +15,30 @@ import java.util.Map; /** - * Represents a function that transforms a value from a data source before indexing. + * Represents a function that transforms a value from a data source before + * indexing. */ @Fluent public final class FieldMappingFunction implements JsonSerializable { /* * The name of the field mapping function. */ + @Generated private final String name; /* - * A dictionary of parameter name/value pairs to pass to the function. Each value must be of a primitive type. + * A dictionary of parameter name/value pairs to pass to the function. Each value + * must be of a primitive type. */ - private Map parameters; + @Generated + private Map parameters; /** * Creates an instance of FieldMappingFunction class. * * @param name the name value to set. */ + @Generated public FieldMappingFunction(String name) { this.name = name; } @@ -43,28 +48,31 @@ public FieldMappingFunction(String name) { * * @return the name value. */ + @Generated public String getName() { return this.name; } /** - * Get the parameters property: A dictionary of parameter name/value pairs to pass to the function. Each value must - * be of a primitive type. + * Get the parameters property: A dictionary of parameter name/value pairs to pass to the function. Each value + * must be of a primitive type. * * @return the parameters value. */ - public Map getParameters() { + @Generated + public Map getParameters() { return this.parameters; } /** - * Set the parameters property: A dictionary of parameter name/value pairs to pass to the function. Each value must - * be of a primitive type. + * Set the parameters property: A dictionary of parameter name/value pairs to pass to the function. Each value + * must be of a primitive type. * * @param parameters the parameters value to set. * @return the FieldMappingFunction object itself. */ - public FieldMappingFunction setParameters(Map parameters) { + @Generated + public FieldMappingFunction setParameters(Map parameters) { this.parameters = parameters; return this; } @@ -72,11 +80,13 @@ public FieldMappingFunction setParameters(Map parameters) { /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); jsonWriter.writeStringField("name", this.name); - jsonWriter.writeMapField("parameters", this.parameters, (writer, element) -> writer.writeUntyped(element)); + jsonWriter.writeMapField("parameters", this.parameters, + (writer, element) -> writer.writeUntyped(element == null ? null : element.toObject(Object.class))); return jsonWriter.writeEndObject(); } @@ -89,31 +99,28 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { * @throws IllegalStateException If the deserialized JSON object was missing any required properties. * @throws IOException If an error occurs while reading the FieldMappingFunction. */ + @Generated public static FieldMappingFunction fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { - boolean nameFound = false; String name = null; - Map parameters = null; + Map parameters = null; while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); if ("name".equals(fieldName)) { name = reader.getString(); - nameFound = true; } else if ("parameters".equals(fieldName)) { - parameters = reader.readMap(reader1 -> reader1.readUntyped()); + parameters = reader.readMap(reader1 -> reader1 + .getNullable(nonNullReader -> BinaryData.fromObject(nonNullReader.readUntyped()))); } else { reader.skipChildren(); } } - if (nameFound) { - FieldMappingFunction deserializedFieldMappingFunction = new FieldMappingFunction(name); - deserializedFieldMappingFunction.parameters = parameters; + FieldMappingFunction deserializedFieldMappingFunction = new FieldMappingFunction(name); + deserializedFieldMappingFunction.parameters = parameters; - return deserializedFieldMappingFunction; - } - throw new IllegalStateException("Missing required property: name"); + return deserializedFieldMappingFunction; }); } } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/FreshnessScoringFunction.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/FreshnessScoringFunction.java similarity index 69% rename from sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/FreshnessScoringFunction.java rename to sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/FreshnessScoringFunction.java index ba8d57175d95..68491945e01c 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/FreshnessScoringFunction.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/FreshnessScoringFunction.java @@ -1,18 +1,15 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) TypeSpec Code Generator. -package com.azure.search.documents.indexes.models; +package com.azure.search.documents.models; import com.azure.core.annotation.Fluent; +import com.azure.core.annotation.Generated; import com.azure.json.JsonReader; import com.azure.json.JsonToken; import com.azure.json.JsonWriter; import java.io.IOException; -import java.util.ArrayList; -import java.util.List; /** * Defines a function that boosts scores based on the value of a date-time field. @@ -20,14 +17,15 @@ @Fluent public final class FreshnessScoringFunction extends ScoringFunction { /* - * Indicates the type of function to use. Valid values include magnitude, freshness, distance, and tag. The function - * type must be lower case. + * Type of ScoringFunction. */ + @Generated private String type = "freshness"; /* * Parameter values for the freshness scoring function. */ + @Generated private final FreshnessScoringParameters parameters; /** @@ -37,17 +35,18 @@ public final class FreshnessScoringFunction extends ScoringFunction { * @param boost the boost value to set. * @param parameters the parameters value to set. */ + @Generated public FreshnessScoringFunction(String fieldName, double boost, FreshnessScoringParameters parameters) { super(fieldName, boost); this.parameters = parameters; } /** - * Get the type property: Indicates the type of function to use. Valid values include magnitude, freshness, - * distance, and tag. The function type must be lower case. + * Get the type property: Type of ScoringFunction. * * @return the type value. */ + @Generated @Override public String getType() { return this.type; @@ -58,6 +57,7 @@ public String getType() { * * @return the parameters value. */ + @Generated public FreshnessScoringParameters getParameters() { return this.parameters; } @@ -65,6 +65,7 @@ public FreshnessScoringParameters getParameters() { /** * {@inheritDoc} */ + @Generated @Override public FreshnessScoringFunction setInterpolation(ScoringFunctionInterpolation interpolation) { super.setInterpolation(interpolation); @@ -74,6 +75,7 @@ public FreshnessScoringFunction setInterpolation(ScoringFunctionInterpolation in /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); @@ -94,14 +96,12 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { * @throws IllegalStateException If the deserialized JSON object was missing any required properties. * @throws IOException If an error occurs while reading the FreshnessScoringFunction. */ + @Generated public static FreshnessScoringFunction fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { - boolean fieldNameFound = false; String fieldName = null; - boolean boostFound = false; double boost = 0.0; ScoringFunctionInterpolation interpolation = null; - boolean parametersFound = false; FreshnessScoringParameters parameters = null; String type = "freshness"; while (reader.nextToken() != JsonToken.END_OBJECT) { @@ -110,42 +110,24 @@ public static FreshnessScoringFunction fromJson(JsonReader jsonReader) throws IO if ("fieldName".equals(jsonFieldName)) { fieldName = reader.getString(); - fieldNameFound = true; } else if ("boost".equals(jsonFieldName)) { boost = reader.getDouble(); - boostFound = true; } else if ("interpolation".equals(jsonFieldName)) { interpolation = ScoringFunctionInterpolation.fromString(reader.getString()); } else if ("freshness".equals(jsonFieldName)) { parameters = FreshnessScoringParameters.fromJson(reader); - parametersFound = true; } else if ("type".equals(jsonFieldName)) { type = reader.getString(); } else { reader.skipChildren(); } } - if (fieldNameFound && boostFound && parametersFound) { - FreshnessScoringFunction deserializedFreshnessScoringFunction - = new FreshnessScoringFunction(fieldName, boost, parameters); - deserializedFreshnessScoringFunction.setInterpolation(interpolation); - deserializedFreshnessScoringFunction.type = type; + FreshnessScoringFunction deserializedFreshnessScoringFunction + = new FreshnessScoringFunction(fieldName, boost, parameters); + deserializedFreshnessScoringFunction.setInterpolation(interpolation); + deserializedFreshnessScoringFunction.type = type; - return deserializedFreshnessScoringFunction; - } - List missingProperties = new ArrayList<>(); - if (!fieldNameFound) { - missingProperties.add("fieldName"); - } - if (!boostFound) { - missingProperties.add("boost"); - } - if (!parametersFound) { - missingProperties.add("freshness"); - } - - throw new IllegalStateException( - "Missing required property/properties: " + String.join(", ", missingProperties)); + return deserializedFreshnessScoringFunction; }); } } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/FreshnessScoringParameters.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/FreshnessScoringParameters.java similarity index 84% rename from sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/FreshnessScoringParameters.java rename to sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/FreshnessScoringParameters.java index bb4d0cefd025..7722251c5f54 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/FreshnessScoringParameters.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/FreshnessScoringParameters.java @@ -1,11 +1,10 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) TypeSpec Code Generator. -package com.azure.search.documents.indexes.models; +package com.azure.search.documents.models; +import com.azure.core.annotation.Generated; import com.azure.core.annotation.Immutable; import com.azure.core.util.CoreUtils; import com.azure.json.JsonReader; @@ -23,6 +22,7 @@ public final class FreshnessScoringParameters implements JsonSerializable { - boolean boostingDurationFound = false; Duration boostingDuration = null; while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); @@ -73,15 +76,11 @@ public static FreshnessScoringParameters fromJson(JsonReader jsonReader) throws if ("boostingDuration".equals(fieldName)) { boostingDuration = reader.getNullable(nonNullReader -> Duration.parse(nonNullReader.getString())); - boostingDurationFound = true; } else { reader.skipChildren(); } } - if (boostingDurationFound) { - return new FreshnessScoringParameters(boostingDuration); - } - throw new IllegalStateException("Missing required property: boostingDuration"); + return new FreshnessScoringParameters(boostingDuration); }); } } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/SearchIndexStatistics.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/GetIndexStatisticsResult.java similarity index 57% rename from sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/SearchIndexStatistics.java rename to sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/GetIndexStatisticsResult.java index 42b70c10bfb0..2ebe954f6005 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/SearchIndexStatistics.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/GetIndexStatisticsResult.java @@ -1,49 +1,53 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) TypeSpec Code Generator. -package com.azure.search.documents.indexes.models; +package com.azure.search.documents.models; +import com.azure.core.annotation.Generated; import com.azure.core.annotation.Immutable; import com.azure.json.JsonReader; import com.azure.json.JsonSerializable; import com.azure.json.JsonToken; import com.azure.json.JsonWriter; import java.io.IOException; -import java.util.ArrayList; -import java.util.List; /** - * Statistics for a given index. Statistics are collected periodically and are not guaranteed to always be up-to-date. + * Statistics for a given index. Statistics are collected periodically and are not + * guaranteed to always be up-to-date. */ @Immutable -public final class SearchIndexStatistics implements JsonSerializable { +public final class GetIndexStatisticsResult implements JsonSerializable { /* * The number of documents in the index. */ + @Generated private final long documentCount; /* * The amount of storage in bytes consumed by the index. */ + @Generated private final long storageSize; /* * The amount of memory in bytes consumed by vectors in the index. */ - private Long vectorIndexSize; + @Generated + private final long vectorIndexSize; /** - * Creates an instance of SearchIndexStatistics class. + * Creates an instance of GetIndexStatisticsResult class. * * @param documentCount the documentCount value to set. * @param storageSize the storageSize value to set. + * @param vectorIndexSize the vectorIndexSize value to set. */ - public SearchIndexStatistics(long documentCount, long storageSize) { + @Generated + private GetIndexStatisticsResult(long documentCount, long storageSize, long vectorIndexSize) { this.documentCount = documentCount; this.storageSize = storageSize; + this.vectorIndexSize = vectorIndexSize; } /** @@ -51,6 +55,7 @@ public SearchIndexStatistics(long documentCount, long storageSize) { * * @return the documentCount value. */ + @Generated public long getDocumentCount() { return this.documentCount; } @@ -60,6 +65,7 @@ public long getDocumentCount() { * * @return the storageSize value. */ + @Generated public long getStorageSize() { return this.storageSize; } @@ -69,68 +75,54 @@ public long getStorageSize() { * * @return the vectorIndexSize value. */ - public Long getVectorIndexSize() { + @Generated + public long getVectorIndexSize() { return this.vectorIndexSize; } /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); + jsonWriter.writeLongField("documentCount", this.documentCount); + jsonWriter.writeLongField("storageSize", this.storageSize); + jsonWriter.writeLongField("vectorIndexSize", this.vectorIndexSize); return jsonWriter.writeEndObject(); } /** - * Reads an instance of SearchIndexStatistics from the JsonReader. + * Reads an instance of GetIndexStatisticsResult from the JsonReader. * * @param jsonReader The JsonReader being read. - * @return An instance of SearchIndexStatistics if the JsonReader was pointing to an instance of it, or null if it - * was pointing to JSON null. + * @return An instance of GetIndexStatisticsResult if the JsonReader was pointing to an instance of it, or null if + * it was pointing to JSON null. * @throws IllegalStateException If the deserialized JSON object was missing any required properties. - * @throws IOException If an error occurs while reading the SearchIndexStatistics. + * @throws IOException If an error occurs while reading the GetIndexStatisticsResult. */ - public static SearchIndexStatistics fromJson(JsonReader jsonReader) throws IOException { + @Generated + public static GetIndexStatisticsResult fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { - boolean documentCountFound = false; long documentCount = 0L; - boolean storageSizeFound = false; long storageSize = 0L; - Long vectorIndexSize = null; + long vectorIndexSize = 0L; while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); if ("documentCount".equals(fieldName)) { documentCount = reader.getLong(); - documentCountFound = true; } else if ("storageSize".equals(fieldName)) { storageSize = reader.getLong(); - storageSizeFound = true; } else if ("vectorIndexSize".equals(fieldName)) { - vectorIndexSize = reader.getNullable(JsonReader::getLong); + vectorIndexSize = reader.getLong(); } else { reader.skipChildren(); } } - if (documentCountFound && storageSizeFound) { - SearchIndexStatistics deserializedSearchIndexStatistics - = new SearchIndexStatistics(documentCount, storageSize); - deserializedSearchIndexStatistics.vectorIndexSize = vectorIndexSize; - - return deserializedSearchIndexStatistics; - } - List missingProperties = new ArrayList<>(); - if (!documentCountFound) { - missingProperties.add("documentCount"); - } - if (!storageSizeFound) { - missingProperties.add("storageSize"); - } - - throw new IllegalStateException( - "Missing required property/properties: " + String.join(", ", missingProperties)); + return new GetIndexStatisticsResult(documentCount, storageSize, vectorIndexSize); }); } } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/HighWaterMarkChangeDetectionPolicy.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/HighWaterMarkChangeDetectionPolicy.java similarity index 75% rename from sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/HighWaterMarkChangeDetectionPolicy.java rename to sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/HighWaterMarkChangeDetectionPolicy.java index 75cbb3cc6c31..63632a059541 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/HighWaterMarkChangeDetectionPolicy.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/HighWaterMarkChangeDetectionPolicy.java @@ -1,11 +1,10 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) TypeSpec Code Generator. -package com.azure.search.documents.indexes.models; +package com.azure.search.documents.models; +import com.azure.core.annotation.Generated; import com.azure.core.annotation.Immutable; import com.azure.json.JsonReader; import com.azure.json.JsonToken; @@ -13,18 +12,21 @@ import java.io.IOException; /** - * Defines a data change detection policy that captures changes based on the value of a high water mark column. + * Defines a data change detection policy that captures changes based on the value + * of a high water mark column. */ @Immutable public final class HighWaterMarkChangeDetectionPolicy extends DataChangeDetectionPolicy { /* - * A URI fragment specifying the type of data change detection policy. + * The discriminator for derived types. */ + @Generated private String odataType = "#Microsoft.Azure.Search.HighWaterMarkChangeDetectionPolicy"; /* * The name of the high water mark column. */ + @Generated private final String highWaterMarkColumnName; /** @@ -32,15 +34,17 @@ public final class HighWaterMarkChangeDetectionPolicy extends DataChangeDetectio * * @param highWaterMarkColumnName the highWaterMarkColumnName value to set. */ + @Generated public HighWaterMarkChangeDetectionPolicy(String highWaterMarkColumnName) { this.highWaterMarkColumnName = highWaterMarkColumnName; } /** - * Get the odataType property: A URI fragment specifying the type of data change detection policy. + * Get the odataType property: The discriminator for derived types. * * @return the odataType value. */ + @Generated @Override public String getOdataType() { return this.odataType; @@ -51,6 +55,7 @@ public String getOdataType() { * * @return the highWaterMarkColumnName value. */ + @Generated public String getHighWaterMarkColumnName() { return this.highWaterMarkColumnName; } @@ -58,6 +63,7 @@ public String getHighWaterMarkColumnName() { /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); @@ -75,9 +81,9 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { * @throws IllegalStateException If the deserialized JSON object was missing any required properties. * @throws IOException If an error occurs while reading the HighWaterMarkChangeDetectionPolicy. */ + @Generated public static HighWaterMarkChangeDetectionPolicy fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { - boolean highWaterMarkColumnNameFound = false; String highWaterMarkColumnName = null; String odataType = "#Microsoft.Azure.Search.HighWaterMarkChangeDetectionPolicy"; while (reader.nextToken() != JsonToken.END_OBJECT) { @@ -86,21 +92,17 @@ public static HighWaterMarkChangeDetectionPolicy fromJson(JsonReader jsonReader) if ("highWaterMarkColumnName".equals(fieldName)) { highWaterMarkColumnName = reader.getString(); - highWaterMarkColumnNameFound = true; } else if ("@odata.type".equals(fieldName)) { odataType = reader.getString(); } else { reader.skipChildren(); } } - if (highWaterMarkColumnNameFound) { - HighWaterMarkChangeDetectionPolicy deserializedHighWaterMarkChangeDetectionPolicy - = new HighWaterMarkChangeDetectionPolicy(highWaterMarkColumnName); - deserializedHighWaterMarkChangeDetectionPolicy.odataType = odataType; + HighWaterMarkChangeDetectionPolicy deserializedHighWaterMarkChangeDetectionPolicy + = new HighWaterMarkChangeDetectionPolicy(highWaterMarkColumnName); + deserializedHighWaterMarkChangeDetectionPolicy.odataType = odataType; - return deserializedHighWaterMarkChangeDetectionPolicy; - } - throw new IllegalStateException("Missing required property: highWaterMarkColumnName"); + return deserializedHighWaterMarkChangeDetectionPolicy; }); } } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/HnswAlgorithmConfiguration.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/HnswAlgorithmConfiguration.java similarity index 76% rename from sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/HnswAlgorithmConfiguration.java rename to sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/HnswAlgorithmConfiguration.java index 47c2d9092651..15ebaaa01c10 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/HnswAlgorithmConfiguration.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/HnswAlgorithmConfiguration.java @@ -1,31 +1,33 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) TypeSpec Code Generator. -package com.azure.search.documents.indexes.models; +package com.azure.search.documents.models; import com.azure.core.annotation.Fluent; +import com.azure.core.annotation.Generated; import com.azure.json.JsonReader; import com.azure.json.JsonToken; import com.azure.json.JsonWriter; import java.io.IOException; /** - * 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. + * 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. */ @Fluent public final class HnswAlgorithmConfiguration extends VectorSearchAlgorithmConfiguration { /* - * The name of the kind of algorithm being configured for use with vector search. + * Type of VectorSearchAlgorithmConfiguration. */ + @Generated private VectorSearchAlgorithmKind kind = VectorSearchAlgorithmKind.HNSW; /* * Contains the parameters specific to HNSW algorithm. */ + @Generated private HnswParameters parameters; /** @@ -33,15 +35,17 @@ public final class HnswAlgorithmConfiguration extends VectorSearchAlgorithmConfi * * @param name the name value to set. */ + @Generated public HnswAlgorithmConfiguration(String name) { super(name); } /** - * Get the kind property: The name of the kind of algorithm being configured for use with vector search. + * Get the kind property: Type of VectorSearchAlgorithmConfiguration. * * @return the kind value. */ + @Generated @Override public VectorSearchAlgorithmKind getKind() { return this.kind; @@ -52,6 +56,7 @@ public VectorSearchAlgorithmKind getKind() { * * @return the parameters value. */ + @Generated public HnswParameters getParameters() { return this.parameters; } @@ -62,6 +67,7 @@ public HnswParameters getParameters() { * @param parameters the parameters value to set. * @return the HnswAlgorithmConfiguration object itself. */ + @Generated public HnswAlgorithmConfiguration setParameters(HnswParameters parameters) { this.parameters = parameters; return this; @@ -70,6 +76,7 @@ public HnswAlgorithmConfiguration setParameters(HnswParameters parameters) { /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); @@ -88,9 +95,9 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { * @throws IllegalStateException If the deserialized JSON object was missing any required properties. * @throws IOException If an error occurs while reading the HnswAlgorithmConfiguration. */ + @Generated public static HnswAlgorithmConfiguration fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { - boolean nameFound = false; String name = null; VectorSearchAlgorithmKind kind = VectorSearchAlgorithmKind.HNSW; HnswParameters parameters = null; @@ -100,7 +107,6 @@ public static HnswAlgorithmConfiguration fromJson(JsonReader jsonReader) throws if ("name".equals(fieldName)) { name = reader.getString(); - nameFound = true; } else if ("kind".equals(fieldName)) { kind = VectorSearchAlgorithmKind.fromString(reader.getString()); } else if ("hnswParameters".equals(fieldName)) { @@ -109,15 +115,11 @@ public static HnswAlgorithmConfiguration fromJson(JsonReader jsonReader) throws reader.skipChildren(); } } - if (nameFound) { - HnswAlgorithmConfiguration deserializedHnswAlgorithmConfiguration - = new HnswAlgorithmConfiguration(name); - deserializedHnswAlgorithmConfiguration.kind = kind; - deserializedHnswAlgorithmConfiguration.parameters = parameters; + HnswAlgorithmConfiguration deserializedHnswAlgorithmConfiguration = new HnswAlgorithmConfiguration(name); + deserializedHnswAlgorithmConfiguration.kind = kind; + deserializedHnswAlgorithmConfiguration.parameters = parameters; - return deserializedHnswAlgorithmConfiguration; - } - throw new IllegalStateException("Missing required property: name"); + return deserializedHnswAlgorithmConfiguration; }); } } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/HnswParameters.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/HnswParameters.java similarity index 69% rename from sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/HnswParameters.java rename to sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/HnswParameters.java index 56936942f2e2..4a7cc103f07a 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/HnswParameters.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/HnswParameters.java @@ -1,12 +1,11 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) TypeSpec Code Generator. -package com.azure.search.documents.indexes.models; +package com.azure.search.documents.models; import com.azure.core.annotation.Fluent; +import com.azure.core.annotation.Generated; import com.azure.json.JsonReader; import com.azure.json.JsonSerializable; import com.azure.json.JsonToken; @@ -19,56 +18,68 @@ @Fluent public final class HnswParameters implements JsonSerializable { /* - * 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. + * 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. */ + @Generated private Integer m; /* - * 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. + * 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. */ + @Generated private Integer efConstruction; /* - * 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. + * 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. */ + @Generated private Integer efSearch; /* * The similarity metric to use for vector comparisons. */ + @Generated private VectorSearchAlgorithmMetric metric; /** * Creates an instance of HnswParameters class. */ + @Generated public HnswParameters() { } /** - * Get the m property: 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. + * Get the m property: 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. * * @return the m value. */ + @Generated public Integer getM() { return this.m; } /** - * Set the m property: 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. + * Set the m property: 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. * * @param m the m value to set. * @return the HnswParameters object itself. */ + @Generated public HnswParameters setM(Integer m) { this.m = m; return this; @@ -76,47 +87,55 @@ public HnswParameters setM(Integer m) { /** * Get the efConstruction property: 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. + * 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. * * @return the efConstruction value. */ + @Generated public Integer getEfConstruction() { return this.efConstruction; } /** * Set the efConstruction property: 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. + * 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. * * @param efConstruction the efConstruction value to set. * @return the HnswParameters object itself. */ + @Generated public HnswParameters setEfConstruction(Integer efConstruction) { this.efConstruction = efConstruction; return this; } /** - * Get the efSearch property: 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. + * Get the efSearch property: 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. * * @return the efSearch value. */ + @Generated public Integer getEfSearch() { return this.efSearch; } /** - * Set the efSearch property: 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. + * Set the efSearch property: 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. * * @param efSearch the efSearch value to set. * @return the HnswParameters object itself. */ + @Generated public HnswParameters setEfSearch(Integer efSearch) { this.efSearch = efSearch; return this; @@ -127,6 +146,7 @@ public HnswParameters setEfSearch(Integer efSearch) { * * @return the metric value. */ + @Generated public VectorSearchAlgorithmMetric getMetric() { return this.metric; } @@ -137,6 +157,7 @@ public VectorSearchAlgorithmMetric getMetric() { * @param metric the metric value to set. * @return the HnswParameters object itself. */ + @Generated public HnswParameters setMetric(VectorSearchAlgorithmMetric metric) { this.metric = metric; return this; @@ -145,6 +166,7 @@ public HnswParameters setMetric(VectorSearchAlgorithmMetric metric) { /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); @@ -163,6 +185,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { * pointing to JSON null. * @throws IOException If an error occurs while reading the HnswParameters. */ + @Generated public static HnswParameters fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { HnswParameters deserializedHnswParameters = new HnswParameters(); diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/HybridCountAndFacetMode.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/HybridCountAndFacetMode.java index 2b63dc7ce417..56f5deb18a66 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/HybridCountAndFacetMode.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/HybridCountAndFacetMode.java @@ -1,29 +1,32 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.search.documents.models; +import com.azure.core.annotation.Generated; import com.azure.core.util.ExpandableStringEnum; import java.util.Collection; /** - * 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. The default value is 'countAllResults'. + * 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. The default value is 'countAllResults'. */ public final class HybridCountAndFacetMode extends ExpandableStringEnum { /** - * Only include documents that were matched within the 'maxTextRecallSize' retrieval window when computing 'count' - * and 'facets'. + * Only include documents that were matched within the 'maxTextRecallSize' + * retrieval window when computing 'count' and 'facets'. */ + @Generated public static final HybridCountAndFacetMode COUNT_RETRIEVABLE_RESULTS = fromString("countRetrievableResults"); /** - * Include all documents that were matched by the search query when computing 'count' and 'facets', regardless of - * whether or not those documents are within the 'maxTextRecallSize' retrieval window. + * Include all documents that were matched by the search query when computing 'count' + * and 'facets', regardless of whether or not those documents are within + * the 'maxTextRecallSize' retrieval window. */ + @Generated public static final HybridCountAndFacetMode COUNT_ALL_RESULTS = fromString("countAllResults"); /** @@ -31,6 +34,7 @@ public final class HybridCountAndFacetMode extends ExpandableStringEnum values() { return values(HybridCountAndFacetMode.class); } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/HybridSearch.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/HybridSearch.java index 55e9d8e58faa..975a1a2dbbb0 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/HybridSearch.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/HybridSearch.java @@ -1,12 +1,11 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.search.documents.models; import com.azure.core.annotation.Fluent; +import com.azure.core.annotation.Generated; import com.azure.json.JsonReader; import com.azure.json.JsonSerializable; import com.azure.json.JsonToken; @@ -19,49 +18,60 @@ @Fluent public final class HybridSearch implements JsonSerializable { /* - * 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. + * 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. */ + @Generated private Integer maxTextRecallSize; /* - * 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. + * 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. */ + @Generated private HybridCountAndFacetMode countAndFacetMode; /** * Creates an instance of HybridSearch class. */ + @Generated public HybridSearch() { } /** * Get the maxTextRecallSize property: 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. + * 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. * * @return the maxTextRecallSize value. */ + @Generated public Integer getMaxTextRecallSize() { return this.maxTextRecallSize; } /** * Set the maxTextRecallSize property: 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. + * 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. * * @param maxTextRecallSize the maxTextRecallSize value to set. * @return the HybridSearch object itself. */ + @Generated public HybridSearch setMaxTextRecallSize(Integer maxTextRecallSize) { this.maxTextRecallSize = maxTextRecallSize; return this; @@ -73,6 +83,7 @@ public HybridSearch setMaxTextRecallSize(Integer maxTextRecallSize) { * * @return the countAndFacetMode value. */ + @Generated public HybridCountAndFacetMode getCountAndFacetMode() { return this.countAndFacetMode; } @@ -84,6 +95,7 @@ public HybridCountAndFacetMode getCountAndFacetMode() { * @param countAndFacetMode the countAndFacetMode value to set. * @return the HybridSearch object itself. */ + @Generated public HybridSearch setCountAndFacetMode(HybridCountAndFacetMode countAndFacetMode) { this.countAndFacetMode = countAndFacetMode; return this; @@ -92,6 +104,7 @@ public HybridSearch setCountAndFacetMode(HybridCountAndFacetMode countAndFacetMo /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); @@ -109,6 +122,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { * pointing to JSON null. * @throws IOException If an error occurs while reading the HybridSearch. */ + @Generated public static HybridSearch fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { HybridSearch deserializedHybridSearch = new HybridSearch(); diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/ImageAnalysisSkill.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/ImageAnalysisSkill.java similarity index 74% rename from sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/ImageAnalysisSkill.java rename to sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/ImageAnalysisSkill.java index 7ebfd8de43bb..c6d252a5fa83 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/ImageAnalysisSkill.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/ImageAnalysisSkill.java @@ -1,60 +1,64 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. -package com.azure.search.documents.indexes.models; +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.search.documents.models; import com.azure.core.annotation.Fluent; +import com.azure.core.annotation.Generated; import com.azure.json.JsonReader; import com.azure.json.JsonToken; import com.azure.json.JsonWriter; import java.io.IOException; -import java.util.ArrayList; -import java.util.Arrays; import java.util.List; /** - * A skill that analyzes image files. It extracts a rich set of visual features based on the image content. + * A skill that analyzes image files. It extracts a rich set of visual features + * based on the image content. */ @Fluent public final class ImageAnalysisSkill extends SearchIndexerSkill { - /* - * A URI fragment specifying the type of skill. + * The discriminator for derived types. */ + @Generated private String odataType = "#Microsoft.Skills.Vision.ImageAnalysisSkill"; /* * A value indicating which language code to use. Default is `en`. */ + @Generated private ImageAnalysisSkillLanguage defaultLanguageCode; /* * A list of visual features. */ + @Generated private List visualFeatures; /* * A string indicating which domain-specific details to return. */ + @Generated private List details; /** * Creates an instance of ImageAnalysisSkill class. - * + * * @param inputs the inputs value to set. * @param outputs the outputs value to set. */ + @Generated public ImageAnalysisSkill(List inputs, List outputs) { super(inputs, outputs); } /** - * Get the odataType property: A URI fragment specifying the type of skill. - * + * Get the odataType property: The discriminator for derived types. + * * @return the odataType value. */ + @Generated @Override public String getOdataType() { return this.odataType; @@ -62,19 +66,21 @@ public String getOdataType() { /** * Get the defaultLanguageCode property: A value indicating which language code to use. Default is `en`. - * + * * @return the defaultLanguageCode value. */ + @Generated public ImageAnalysisSkillLanguage getDefaultLanguageCode() { return this.defaultLanguageCode; } /** * Set the defaultLanguageCode property: A value indicating which language code to use. Default is `en`. - * + * * @param defaultLanguageCode the defaultLanguageCode value to set. * @return the ImageAnalysisSkill object itself. */ + @Generated public ImageAnalysisSkill setDefaultLanguageCode(ImageAnalysisSkillLanguage defaultLanguageCode) { this.defaultLanguageCode = defaultLanguageCode; return this; @@ -82,19 +88,21 @@ public ImageAnalysisSkill setDefaultLanguageCode(ImageAnalysisSkillLanguage defa /** * Get the visualFeatures property: A list of visual features. - * + * * @return the visualFeatures value. */ + @Generated public List getVisualFeatures() { return this.visualFeatures; } /** * Set the visualFeatures property: A list of visual features. - * + * * @param visualFeatures the visualFeatures value to set. * @return the ImageAnalysisSkill object itself. */ + @Generated public ImageAnalysisSkill setVisualFeatures(List visualFeatures) { this.visualFeatures = visualFeatures; return this; @@ -102,19 +110,21 @@ public ImageAnalysisSkill setVisualFeatures(List visualFeatures) /** * Get the details property: A string indicating which domain-specific details to return. - * + * * @return the details value. */ + @Generated public List getDetails() { return this.details; } /** * Set the details property: A string indicating which domain-specific details to return. - * + * * @param details the details value to set. * @return the ImageAnalysisSkill object itself. */ + @Generated public ImageAnalysisSkill setDetails(List details) { this.details = details; return this; @@ -123,6 +133,7 @@ public ImageAnalysisSkill setDetails(List details) { /** * {@inheritDoc} */ + @Generated @Override public ImageAnalysisSkill setName(String name) { super.setName(name); @@ -132,6 +143,7 @@ public ImageAnalysisSkill setName(String name) { /** * {@inheritDoc} */ + @Generated @Override public ImageAnalysisSkill setDescription(String description) { super.setDescription(description); @@ -141,6 +153,7 @@ public ImageAnalysisSkill setDescription(String description) { /** * {@inheritDoc} */ + @Generated @Override public ImageAnalysisSkill setContext(String context) { super.setContext(context); @@ -150,6 +163,7 @@ public ImageAnalysisSkill setContext(String context) { /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); @@ -170,18 +184,17 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of ImageAnalysisSkill from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of ImageAnalysisSkill if the JsonReader was pointing to an instance of it, or null if it was * pointing to JSON null. * @throws IllegalStateException If the deserialized JSON object was missing any required properties. * @throws IOException If an error occurs while reading the ImageAnalysisSkill. */ + @Generated public static ImageAnalysisSkill fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { - boolean inputsFound = false; List inputs = null; - boolean outputsFound = false; List outputs = null; String name = null; String description = null; @@ -193,12 +206,11 @@ public static ImageAnalysisSkill fromJson(JsonReader jsonReader) throws IOExcept while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); + if ("inputs".equals(fieldName)) { inputs = reader.readArray(reader1 -> InputFieldMappingEntry.fromJson(reader1)); - inputsFound = true; } else if ("outputs".equals(fieldName)) { outputs = reader.readArray(reader1 -> OutputFieldMappingEntry.fromJson(reader1)); - outputsFound = true; } else if ("name".equals(fieldName)) { name = reader.getString(); } else if ("description".equals(fieldName)) { @@ -217,48 +229,16 @@ public static ImageAnalysisSkill fromJson(JsonReader jsonReader) throws IOExcept reader.skipChildren(); } } - if (inputsFound && outputsFound) { - ImageAnalysisSkill deserializedImageAnalysisSkill = new ImageAnalysisSkill(inputs, outputs); - deserializedImageAnalysisSkill.setName(name); - deserializedImageAnalysisSkill.setDescription(description); - deserializedImageAnalysisSkill.setContext(context); - deserializedImageAnalysisSkill.odataType = odataType; - deserializedImageAnalysisSkill.defaultLanguageCode = defaultLanguageCode; - deserializedImageAnalysisSkill.visualFeatures = visualFeatures; - deserializedImageAnalysisSkill.details = details; - return deserializedImageAnalysisSkill; - } - List missingProperties = new ArrayList<>(); - if (!inputsFound) { - missingProperties.add("inputs"); - } - if (!outputsFound) { - missingProperties.add("outputs"); - } - throw new IllegalStateException( - "Missing required property/properties: " + String.join(", ", missingProperties)); + ImageAnalysisSkill deserializedImageAnalysisSkill = new ImageAnalysisSkill(inputs, outputs); + deserializedImageAnalysisSkill.setName(name); + deserializedImageAnalysisSkill.setDescription(description); + deserializedImageAnalysisSkill.setContext(context); + deserializedImageAnalysisSkill.odataType = odataType; + deserializedImageAnalysisSkill.defaultLanguageCode = defaultLanguageCode; + deserializedImageAnalysisSkill.visualFeatures = visualFeatures; + deserializedImageAnalysisSkill.details = details; + + return deserializedImageAnalysisSkill; }); } - - /** - * Set the visualFeatures property: A list of visual features. - * - * @param visualFeatures the visualFeatures value to set. - * @return the ImageAnalysisSkill object itself. - */ - public ImageAnalysisSkill setVisualFeatures(VisualFeature... visualFeatures) { - this.visualFeatures = (visualFeatures == null) ? null : Arrays.asList(visualFeatures); - return this; - } - - /** - * Set the details property: A string indicating which domain-specific details to return. - * - * @param details the details value to set. - * @return the ImageAnalysisSkill object itself. - */ - public ImageAnalysisSkill setDetails(ImageDetail... details) { - this.details = (details == null) ? null : Arrays.asList(details); - return this; - } } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/ImageAnalysisSkillLanguage.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/ImageAnalysisSkillLanguage.java similarity index 87% rename from sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/ImageAnalysisSkillLanguage.java rename to sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/ImageAnalysisSkillLanguage.java index 9b2683705ad0..057fdb948e42 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/ImageAnalysisSkillLanguage.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/ImageAnalysisSkillLanguage.java @@ -1,11 +1,10 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) TypeSpec Code Generator. -package com.azure.search.documents.indexes.models; +package com.azure.search.documents.models; +import com.azure.core.annotation.Generated; import com.azure.core.util.ExpandableStringEnum; import java.util.Collection; @@ -16,261 +15,313 @@ public final class ImageAnalysisSkillLanguage extends ExpandableStringEnum values() { return values(ImageAnalysisSkillLanguage.class); } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/ImageDetail.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/ImageDetail.java similarity index 85% rename from sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/ImageDetail.java rename to sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/ImageDetail.java index 5fccb7d657d7..4f761bd338b2 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/ImageDetail.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/ImageDetail.java @@ -1,11 +1,10 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) TypeSpec Code Generator. -package com.azure.search.documents.indexes.models; +package com.azure.search.documents.models; +import com.azure.core.annotation.Generated; import com.azure.core.util.ExpandableStringEnum; import java.util.Collection; @@ -16,11 +15,13 @@ public final class ImageDetail extends ExpandableStringEnum { /** * Details recognized as celebrities. */ + @Generated public static final ImageDetail CELEBRITIES = fromString("celebrities"); /** * Details recognized as landmarks. */ + @Generated public static final ImageDetail LANDMARKS = fromString("landmarks"); /** @@ -28,6 +29,7 @@ public final class ImageDetail extends ExpandableStringEnum { * * @deprecated Use the {@link #fromString(String)} factory method. */ + @Generated @Deprecated public ImageDetail() { } @@ -38,6 +40,7 @@ public ImageDetail() { * @param name a name to look for. * @return the corresponding ImageDetail. */ + @Generated public static ImageDetail fromString(String name) { return fromString(name, ImageDetail.class); } @@ -47,6 +50,7 @@ public static ImageDetail fromString(String name) { * * @return known ImageDetail values. */ + @Generated public static Collection values() { return values(ImageDetail.class); } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/IndexAction.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/IndexAction.java index e8c7f698b9c9..19d0f66db254 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/IndexAction.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/IndexAction.java @@ -1,120 +1,140 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.search.documents.models; import com.azure.core.annotation.Fluent; -import com.azure.search.documents.implementation.converters.IndexActionHelper; - +import com.azure.core.annotation.Generated; +import com.azure.core.util.BinaryData; +import com.azure.json.JsonReader; +import com.azure.json.JsonSerializable; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import java.io.IOException; +import java.util.LinkedHashMap; import java.util.Map; /** * Represents an index action that operates on a document. - * - * @param The type of the document used in the indexing action. */ @Fluent -public final class IndexAction { - /* - * The document on which the action will be performed. - */ - private T document; - - private Map properties; - +public final class IndexAction implements JsonSerializable { /* * The operation to perform on a document in an indexing batch. */ + @Generated private IndexActionType actionType; - static { - IndexActionHelper.setAccessor(new IndexActionHelper.IndexActionAccessor() { - @Override - public void setProperties(IndexAction indexAction, Map properties) { - indexAction.setProperties(properties); - } - - @Override - public Map getProperties(IndexAction indexAction) { - return indexAction.getProperties(); - } - }); - } + /* + * Represents an index action that operates on a document. + */ + @Generated + private Map additionalProperties; /** - * Creates an instance of {@link IndexAction}. + * Creates an instance of IndexAction class. */ + @Generated public IndexAction() { } /** - * Get the document on which the action will be performed; Fields other than the key are ignored for delete - * actions. - * - * @return the document value. + * Get the actionType property: The operation to perform on a document in an indexing batch. + * + * @return the actionType value. */ - @SuppressWarnings("unchecked") - public T getDocument() { - if (this.properties != null) { - return (T) this.properties; - } - return this.document; + @Generated + public IndexActionType getActionType() { + return this.actionType; } /** - * Get the document on which the action will be performed; Fields other than the key are ignored for delete - * actions. - * - * @param document the document value to set. + * Set the actionType property: The operation to perform on a document in an indexing batch. + * + * @param actionType the actionType value to set. * @return the IndexAction object itself. */ - @SuppressWarnings("unchecked") - public IndexAction setDocument(T document) { - if (document instanceof Map) { - this.properties = (Map) document; - this.document = null; - } else { - this.document = document; - this.properties = null; - } + @Generated + public IndexAction setActionType(IndexActionType actionType) { + this.actionType = actionType; return this; } /** - * Get the actionType property: The operation to perform on a document in an indexing batch. - * - * @return the actionType value. + * Get the additionalProperties property: Represents an index action that operates on a document. + * + * @return the additionalProperties value. */ - public IndexActionType getActionType() { - return this.actionType; + @Generated + public Map getAdditionalProperties() { + return this.additionalProperties; } /** - * Set the actionType property: The operation to perform on a document in an indexing batch. - * - * @param actionType the actionType value to set. + * Set the additionalProperties property: Represents an index action that operates on a document. + * + * @param additionalProperties the additionalProperties value to set. * @return the IndexAction object itself. */ - public IndexAction setActionType(IndexActionType actionType) { - this.actionType = actionType; + @Generated + public IndexAction setAdditionalProperties(Map additionalProperties) { + this.additionalProperties = additionalProperties; return this; } /** - * The private setter to set the properties via {@link IndexActionHelper.IndexActionAccessor}. - * - * @param properties The properties. + * {@inheritDoc} */ - private void setProperties(Map properties) { - this.properties = properties; + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("@search.action", this.actionType == null ? null : this.actionType.toString()); + if (additionalProperties != null) { + for (Map.Entry additionalProperty : additionalProperties.entrySet()) { + jsonWriter.writeFieldName(additionalProperty.getKey()); + if (additionalProperty.getValue() == null) { + jsonWriter.writeNull(); + } else { + additionalProperty.getValue().writeTo(jsonWriter); + } + } + } + return jsonWriter.writeEndObject(); } /** - * The private getter to get the properties via {@link IndexActionHelper.IndexActionAccessor}. - * - * @return The properties + * Reads an instance of IndexAction from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of IndexAction if the JsonReader was pointing to an instance of it, or null if it was + * pointing to JSON null. + * @throws IOException If an error occurs while reading the IndexAction. */ - private Map getProperties() { - return this.properties; + @Generated + public static IndexAction fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + IndexAction deserializedIndexAction = new IndexAction(); + Map additionalProperties = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("@search.action".equals(fieldName)) { + deserializedIndexAction.actionType = IndexActionType.fromString(reader.getString()); + } else { + if (additionalProperties == null) { + additionalProperties = new LinkedHashMap<>(); + } + + additionalProperties.put(fieldName, + reader.getNullable(nonNullReader -> BinaryData.fromObject(nonNullReader.readUntyped()))); + } + } + deserializedIndexAction.additionalProperties = additionalProperties; + + return deserializedIndexAction; + }); } } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/IndexActionType.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/IndexActionType.java index 15d8f9eca65e..f770f089c146 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/IndexActionType.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/IndexActionType.java @@ -1,74 +1,78 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.search.documents.models; +import com.azure.core.annotation.Generated; +import com.azure.core.util.ExpandableStringEnum; +import java.util.Collection; + /** * The operation to perform on a document in an indexing batch. */ -public enum IndexActionType { +public final class IndexActionType extends ExpandableStringEnum { /** - * Inserts the document into the index if it is new and updates it if it exists. All fields are replaced in the - * update case. + * Inserts the document into the index if it is new and updates it if it exists. + * All fields are replaced in the update case. */ - UPLOAD("upload"), + @Generated + public static final IndexActionType UPLOAD = fromString("upload"); /** - * Merges the specified field values with an existing document. If the document does not exist, the merge will fail. - * Any field you specify in a merge will replace the existing field in the document. This also applies to - * collections of primitive and complex types. + * Merges the specified field values with an existing document. If the document + * does not exist, the merge will fail. Any field you specify in a merge will + * replace the existing field in the document. This also applies to collections of + * primitive and complex types. */ - MERGE("merge"), + @Generated + public static final IndexActionType MERGE = fromString("merge"); /** - * Behaves like merge if a document with the given key already exists in the index. If the document does not exist, - * it behaves like upload with a new document. + * Behaves like merge if a document with the given key already exists in the + * index. If the document does not exist, it behaves like upload with a new + * document. */ - MERGE_OR_UPLOAD("mergeOrUpload"), + @Generated + public static final IndexActionType MERGE_OR_UPLOAD = fromString("mergeOrUpload"); /** - * Removes the specified document from the index. Any field you specify in a delete operation other than the key - * field will be ignored. If you want to remove an individual field from a document, use merge instead and set the - * field explicitly to null. + * Removes the specified document from the index. Any field you specify in a + * delete operation other than the key field will be ignored. If you want to + * remove an individual field from a document, use merge instead and set the field + * explicitly to null. */ - DELETE("delete"); + @Generated + public static final IndexActionType DELETE = fromString("delete"); /** - * The actual serialized value for a IndexActionType instance. + * Creates a new instance of IndexActionType value. + * + * @deprecated Use the {@link #fromString(String)} factory method. */ - private final String value; - - IndexActionType(String value) { - this.value = value; + @Generated + @Deprecated + public IndexActionType() { } /** - * Parses a serialized value to a IndexActionType instance. + * Creates or finds a IndexActionType from its string representation. * - * @param value the serialized value to parse. - * @return the parsed IndexActionType object, or null if unable to parse. + * @param name a name to look for. + * @return the corresponding IndexActionType. */ - public static IndexActionType fromString(String value) { - if (value == null) { - return null; - } - IndexActionType[] items = IndexActionType.values(); - for (IndexActionType item : items) { - if (item.toString().equalsIgnoreCase(value)) { - return item; - } - } - return null; + @Generated + public static IndexActionType fromString(String name) { + return fromString(name, IndexActionType.class); } /** - * {@inheritDoc} + * Gets known IndexActionType values. + * + * @return known IndexActionType values. */ - @Override - public String toString() { - return this.value; + @Generated + public static Collection values() { + return values(IndexActionType.class); } } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/implementation/models/IndexBatch.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/IndexBatch.java similarity index 83% rename from sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/implementation/models/IndexBatch.java rename to sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/IndexBatch.java index 3d7f71958cb5..368f1c639ea4 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/implementation/models/IndexBatch.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/IndexBatch.java @@ -1,11 +1,10 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) TypeSpec Code Generator. -package com.azure.search.documents.implementation.models; +package com.azure.search.documents.models; +import com.azure.core.annotation.Generated; import com.azure.core.annotation.Immutable; import com.azure.json.JsonReader; import com.azure.json.JsonSerializable; @@ -22,6 +21,7 @@ public final class IndexBatch implements JsonSerializable { /* * The actions in the batch. */ + @Generated private final List actions; /** @@ -29,6 +29,7 @@ public final class IndexBatch implements JsonSerializable { * * @param actions the actions value to set. */ + @Generated public IndexBatch(List actions) { this.actions = actions; } @@ -38,6 +39,7 @@ public IndexBatch(List actions) { * * @return the actions value. */ + @Generated public List getActions() { return this.actions; } @@ -45,6 +47,7 @@ public List getActions() { /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); @@ -61,9 +64,9 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { * @throws IllegalStateException If the deserialized JSON object was missing any required properties. * @throws IOException If an error occurs while reading the IndexBatch. */ + @Generated public static IndexBatch fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { - boolean actionsFound = false; List actions = null; while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); @@ -71,15 +74,11 @@ public static IndexBatch fromJson(JsonReader jsonReader) throws IOException { if ("value".equals(fieldName)) { actions = reader.readArray(reader1 -> IndexAction.fromJson(reader1)); - actionsFound = true; } else { reader.skipChildren(); } } - if (actionsFound) { - return new IndexBatch(actions); - } - throw new IllegalStateException("Missing required property: value"); + return new IndexBatch(actions); }); } } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/IndexBatchBase.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/IndexBatchBase.java deleted file mode 100644 index 4c48125c2c92..000000000000 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/IndexBatchBase.java +++ /dev/null @@ -1,38 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.search.documents.models; - -import com.azure.core.annotation.Fluent; - -import java.util.List; - -/** - * Contains a batch of document write actions to send to the index. - * - * @param The type of the document being indexed. - */ -@Fluent -public class IndexBatchBase { - /* - * The actions in the batch. - */ - private final List> actions; - - /** - * Constructor of {@link IndexBatchBase} - * @param actions The actions in the batch. - */ - public IndexBatchBase(List> actions) { - this.actions = actions; - } - - /** - * Get the actions property: The actions in the batch. - * - * @return the actions value. - */ - public List> getActions() { - return this.actions; - } -} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/IndexBatchException.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/IndexBatchException.java deleted file mode 100644 index 7e4b4a7f9f28..000000000000 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/IndexBatchException.java +++ /dev/null @@ -1,116 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.search.documents.models; - -import com.azure.core.exception.AzureException; -import com.azure.search.documents.SearchDocument; - -import java.util.ArrayList; -import java.util.List; -import java.util.Set; -import java.util.function.Function; -import java.util.stream.Collectors; - -/** - * An {@code IndexBatchException} is thrown whenever Azure AI Search index call was only partially successful. - * Users can inspect the indexingResults to determine the operation(s) that have failed. - */ -public final class IndexBatchException extends AzureException { - private static final long serialVersionUID = -3478124828996650248L; - private static final String MESSAGE_FORMAT = "%s of %s indexing actions in the batch failed. The remaining" - + " actions succeeded and modified the index. Check indexingResults for the status of each index action."; - - /** - * Indexing results. - */ - private final ArrayList results; - - /** - * Constructs an {@code IndexBatchException} from the given {@link IndexDocumentsResult}. - * - * @param result The DocumentIndexResult returned from the service. - */ - public IndexBatchException(IndexDocumentsResult result) { - super(createMessage(result)); - this.results = new ArrayList<>(result.getResults()); - } - - /** - * Finds all index actions in the given batch that failed and need to be retried, and returns them in a new batch. - * - * @param originalBatch The batch that partially failed indexing. - * @param keyFieldName The name of the key field from the index schema. - * @return A new batch containing all the actions from the given batch that failed and should be retried. - */ - public IndexBatchBase findFailedActionsToRetry(IndexBatchBase originalBatch, - String keyFieldName) { - return findFailedActionsToRetry(originalBatch, searchDocument -> searchDocument.get(keyFieldName).toString()); - } - - /** - * Finds all index actions in the given batch that failed and need to be retried, and returns them in a new batch. - * - * @param originBatch The batch that partially failed indexing. - * @param keySelector A lambda that retrieves a key value from a given document of type T. - * @param The given document type. - * @return A new batch containing all the actions from the given batch that failed and should be retried. - */ - public IndexBatchBase findFailedActionsToRetry(IndexBatchBase originBatch, - Function keySelector) { - List> failedActions = doFindFailedActionsToRetry(originBatch, keySelector); - return new IndexBatchBase(failedActions); - } - - /** - * Gets the indexing results returned by the service. - * - * @return The indexing results returned by the service. - */ - public List getIndexingResults() { - return this.results; - } - - private static String createMessage(IndexDocumentsResult result) { - long failedResultCount = result.getResults().stream().filter(r -> !r.isSucceeded()).count(); - return String.format(MESSAGE_FORMAT, failedResultCount, result.getResults().size()); - } - - private List> doFindFailedActionsToRetry(IndexBatchBase originBatch, - Function keySelector) { - Set uniqueRetriableKeys = getIndexingResults().stream() - .filter(result -> isRetriableStatusCode(result.getStatusCode())) - .map(IndexingResult::getKey) - .collect(Collectors.toSet()); - return originBatch.getActions() - .stream() - .filter(action -> isActionIncluded(action, uniqueRetriableKeys, keySelector)) - .collect(Collectors.toList()); - } - - private boolean isActionIncluded(IndexAction action, Set uniqueRetriableKeys, - Function keySelector) { - if (action.getDocument() != null) { - return uniqueRetriableKeys.contains(keySelector.apply(action.getDocument())); - } - return false; - } - - /** - * Checks whether status code is retriable or not. - *
    - *
  • '409': A version conflict was detected when attempting to index a document.
  • - *
  • '422': The index is temporarily unavailable because it was updated with the - * 'allowIndexDowntime' flag set to 'true'.
  • - *
  • '503': Your search service is temporarily unavailable, possibly due to heavy load.
  • - *
- * - * @param statusCode The status code from http response. - * @return Indicates whether it is retriable or not. - */ - private static boolean isRetriableStatusCode(int statusCode) { - // 503 Service Unavailable: - // server error response code indicates that the server is not ready to handle the request - return statusCode == 409 || statusCode == 422 || statusCode == 503; - } -} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/IndexDocumentsOptions.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/IndexDocumentsOptions.java deleted file mode 100644 index 2ed4a0a70f4b..000000000000 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/IndexDocumentsOptions.java +++ /dev/null @@ -1,44 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.search.documents.models; - -import com.azure.core.annotation.Fluent; - -/** - * Options for document index operations. - */ -@Fluent -public class IndexDocumentsOptions { - private boolean throwOnAnyError = true; - - /** - * Creates an instance of {@link IndexDocumentsOptions}. - */ - public IndexDocumentsOptions() { - } - - /** - * Returns whether an exception will be thrown if any operation in the batch fails. - *

- * Default value is {@code true}. - * - * @return Flag indicating if an exception will be thrown if any operation in the batch fails. - */ - public boolean throwOnAnyError() { - return throwOnAnyError; - } - - /** - * Sets whether an exception is thrown if any operation in a batch fails. - *

- * Default value is {@code true}. - * - * @param throwOnAnyError Flag indicating whether to throw on batch operation failure. - * @return The updated IndexDocumentsOptions object. - */ - public IndexDocumentsOptions setThrowOnAnyError(boolean throwOnAnyError) { - this.throwOnAnyError = throwOnAnyError; - return this; - } -} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/IndexDocumentsResult.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/IndexDocumentsResult.java index 1ac946ac54ed..c7389f4b523d 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/IndexDocumentsResult.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/IndexDocumentsResult.java @@ -1,11 +1,10 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.search.documents.models; +import com.azure.core.annotation.Generated; import com.azure.core.annotation.Immutable; import com.azure.json.JsonReader; import com.azure.json.JsonSerializable; @@ -15,13 +14,15 @@ import java.util.List; /** - * Response containing the status of operations for all documents in the indexing request. + * Response containing the status of operations for all documents in the indexing + * request. */ @Immutable public final class IndexDocumentsResult implements JsonSerializable { /* * The list of status information for each document in the indexing request. */ + @Generated private final List results; /** @@ -29,7 +30,8 @@ public final class IndexDocumentsResult implements JsonSerializable results) { + @Generated + private IndexDocumentsResult(List results) { this.results = results; } @@ -38,6 +40,7 @@ public IndexDocumentsResult(List results) { * * @return the results value. */ + @Generated public List getResults() { return this.results; } @@ -45,9 +48,11 @@ public List getResults() { /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); + jsonWriter.writeArrayField("value", this.results, (writer, element) -> writer.writeJson(element)); return jsonWriter.writeEndObject(); } @@ -60,9 +65,9 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { * @throws IllegalStateException If the deserialized JSON object was missing any required properties. * @throws IOException If an error occurs while reading the IndexDocumentsResult. */ + @Generated public static IndexDocumentsResult fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { - boolean resultsFound = false; List results = null; while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); @@ -70,15 +75,11 @@ public static IndexDocumentsResult fromJson(JsonReader jsonReader) throws IOExce if ("value".equals(fieldName)) { results = reader.readArray(reader1 -> IndexingResult.fromJson(reader1)); - resultsFound = true; } else { reader.skipChildren(); } } - if (resultsFound) { - return new IndexDocumentsResult(results); - } - throw new IllegalStateException("Missing required property: value"); + return new IndexDocumentsResult(results); }); } } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/IndexProjectionMode.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/IndexProjectionMode.java similarity index 82% rename from sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/IndexProjectionMode.java rename to sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/IndexProjectionMode.java index 2714ba4ba46b..96827e16f8c3 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/IndexProjectionMode.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/IndexProjectionMode.java @@ -1,26 +1,30 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) TypeSpec Code Generator. -package com.azure.search.documents.indexes.models; +package com.azure.search.documents.models; +import com.azure.core.annotation.Generated; import com.azure.core.util.ExpandableStringEnum; import java.util.Collection; /** - * Defines behavior of the index projections in relation to the rest of the indexer. + * Defines behavior of the index projections in relation to the rest of the + * indexer. */ public final class IndexProjectionMode extends ExpandableStringEnum { /** - * The source document will be skipped from writing into the indexer's target index. + * The source document will be skipped from writing into the indexer's target + * index. */ + @Generated public static final IndexProjectionMode SKIP_INDEXING_PARENT_DOCUMENTS = fromString("skipIndexingParentDocuments"); /** - * The source document will be written into the indexer's target index. This is the default pattern. + * The source document will be written into the indexer's target index. This is + * the default pattern. */ + @Generated public static final IndexProjectionMode INCLUDE_INDEXING_PARENT_DOCUMENTS = fromString("includeIndexingParentDocuments"); @@ -29,6 +33,7 @@ public final class IndexProjectionMode extends ExpandableStringEnum values() { return values(IndexProjectionMode.class); } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/IndexStatisticsSummary.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/IndexStatisticsSummary.java new file mode 100644 index 000000000000..6cdba31c5334 --- /dev/null +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/IndexStatisticsSummary.java @@ -0,0 +1,134 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.search.documents.models; + +import com.azure.core.annotation.Generated; +import com.azure.core.annotation.Immutable; +import com.azure.json.JsonReader; +import com.azure.json.JsonSerializable; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import java.io.IOException; + +/** + * Statistics for a given index. Statistics are collected periodically and are not guaranteed to always be up-to-date. + */ +@Immutable +public final class IndexStatisticsSummary implements JsonSerializable { + /* + * The name of the index. + */ + @Generated + private String name; + + /* + * The number of documents in the index. + */ + @Generated + private long documentCount; + + /* + * The amount of storage in bytes consumed by the index. + */ + @Generated + private long storageSize; + + /* + * The amount of memory in bytes consumed by vectors in the index. + */ + @Generated + private Long vectorIndexSize; + + /** + * Creates an instance of IndexStatisticsSummary class. + */ + @Generated + private IndexStatisticsSummary() { + } + + /** + * Get the name property: The name of the index. + * + * @return the name value. + */ + @Generated + public String getName() { + return this.name; + } + + /** + * Get the documentCount property: The number of documents in the index. + * + * @return the documentCount value. + */ + @Generated + public long getDocumentCount() { + return this.documentCount; + } + + /** + * Get the storageSize property: The amount of storage in bytes consumed by the index. + * + * @return the storageSize value. + */ + @Generated + public long getStorageSize() { + return this.storageSize; + } + + /** + * Get the vectorIndexSize property: The amount of memory in bytes consumed by vectors in the index. + * + * @return the vectorIndexSize value. + */ + @Generated + public Long getVectorIndexSize() { + return this.vectorIndexSize; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of IndexStatisticsSummary from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of IndexStatisticsSummary if the JsonReader was pointing to an instance of it, or null if it + * was pointing to JSON null. + * @throws IllegalStateException If the deserialized JSON object was missing any required properties. + * @throws IOException If an error occurs while reading the IndexStatisticsSummary. + */ + @Generated + public static IndexStatisticsSummary fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + IndexStatisticsSummary deserializedIndexStatisticsSummary = new IndexStatisticsSummary(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("name".equals(fieldName)) { + deserializedIndexStatisticsSummary.name = reader.getString(); + } else if ("documentCount".equals(fieldName)) { + deserializedIndexStatisticsSummary.documentCount = reader.getLong(); + } else if ("storageSize".equals(fieldName)) { + deserializedIndexStatisticsSummary.storageSize = reader.getLong(); + } else if ("vectorIndexSize".equals(fieldName)) { + deserializedIndexStatisticsSummary.vectorIndexSize = reader.getNullable(JsonReader::getLong); + } else { + reader.skipChildren(); + } + } + + return deserializedIndexStatisticsSummary; + }); + } +} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/IndexerCurrentState.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/IndexerCurrentState.java similarity index 81% rename from sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/IndexerCurrentState.java rename to sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/IndexerCurrentState.java index b88db42a19d6..8b8de10f09fb 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/IndexerCurrentState.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/IndexerCurrentState.java @@ -1,11 +1,10 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) TypeSpec Code Generator. -package com.azure.search.documents.indexes.models; +package com.azure.search.documents.models; +import com.azure.core.annotation.Generated; import com.azure.core.annotation.Immutable; import com.azure.json.JsonReader; import com.azure.json.JsonSerializable; @@ -15,51 +14,66 @@ import java.util.List; /** - * Represents all of the state that defines and dictates the indexer's current execution. + * Represents all of the state that defines and dictates the indexer's current + * execution. */ @Immutable public final class IndexerCurrentState implements JsonSerializable { /* * The mode the indexer is running in. */ + @Generated private IndexingMode mode; /* - * Change tracking state used when indexing starts on all documents in the datasource. + * Change tracking state used when indexing starts on all documents in the + * datasource. */ + @Generated private String allDocsInitialChangeTrackingState; /* - * Change tracking state value when indexing finishes on all documents in the datasource. + * Change tracking state value when indexing finishes on all documents in the + * datasource. */ + @Generated private String allDocsFinalChangeTrackingState; /* - * Change tracking state used when indexing starts on select, reset documents in the datasource. + * Change tracking state used when indexing starts on select, reset documents in + * the datasource. */ + @Generated private String resetDocsInitialChangeTrackingState; /* - * Change tracking state value when indexing finishes on select, reset documents in the datasource. + * Change tracking state value when indexing finishes on select, reset documents + * in the datasource. */ + @Generated private String resetDocsFinalChangeTrackingState; /* - * 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. + * 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. */ + @Generated private List resetDocumentKeys; /* - * 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. + * 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. */ + @Generated private List resetDatasourceDocumentIds; /** * Creates an instance of IndexerCurrentState class. */ - public IndexerCurrentState() { + @Generated + private IndexerCurrentState() { } /** @@ -67,68 +81,80 @@ public IndexerCurrentState() { * * @return the mode value. */ + @Generated public IndexingMode getMode() { return this.mode; } /** * Get the allDocsInitialChangeTrackingState property: Change tracking state used when indexing starts on all - * documents in the datasource. + * documents in the + * datasource. * * @return the allDocsInitialChangeTrackingState value. */ + @Generated public String getAllDocsInitialChangeTrackingState() { return this.allDocsInitialChangeTrackingState; } /** * Get the allDocsFinalChangeTrackingState property: Change tracking state value when indexing finishes on all - * documents in the datasource. + * documents in the + * datasource. * * @return the allDocsFinalChangeTrackingState value. */ + @Generated public String getAllDocsFinalChangeTrackingState() { return this.allDocsFinalChangeTrackingState; } /** * Get the resetDocsInitialChangeTrackingState property: Change tracking state used when indexing starts on select, - * reset documents in the datasource. + * reset documents in + * the datasource. * * @return the resetDocsInitialChangeTrackingState value. */ + @Generated public String getResetDocsInitialChangeTrackingState() { return this.resetDocsInitialChangeTrackingState; } /** * Get the resetDocsFinalChangeTrackingState property: Change tracking state value when indexing finishes on select, - * reset documents in the datasource. + * reset documents + * in the datasource. * * @return the resetDocsFinalChangeTrackingState value. */ + @Generated public String getResetDocsFinalChangeTrackingState() { return this.resetDocsFinalChangeTrackingState; } /** * Get the resetDocumentKeys property: 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. + * document's unique identifier for the data in the search index. The indexer will + * prioritize selectively re-ingesting these keys. * * @return the resetDocumentKeys value. */ + @Generated public List getResetDocumentKeys() { return this.resetDocumentKeys; } /** * Get the resetDatasourceDocumentIds property: 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. + * datasource + * document id is the unique identifier for the data in the datasource. The + * indexer will prioritize selectively re-ingesting these ids. * * @return the resetDatasourceDocumentIds value. */ + @Generated public List getResetDatasourceDocumentIds() { return this.resetDatasourceDocumentIds; } @@ -136,6 +162,7 @@ public List getResetDatasourceDocumentIds() { /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); @@ -150,6 +177,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { * pointing to JSON null. * @throws IOException If an error occurs while reading the IndexerCurrentState. */ + @Generated public static IndexerCurrentState fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { IndexerCurrentState deserializedIndexerCurrentState = new IndexerCurrentState(); diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/IndexerExecutionEnvironment.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/IndexerExecutionEnvironment.java similarity index 75% rename from sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/IndexerExecutionEnvironment.java rename to sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/IndexerExecutionEnvironment.java index 5decce4ba2be..4eaead4711fc 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/IndexerExecutionEnvironment.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/IndexerExecutionEnvironment.java @@ -1,11 +1,10 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) TypeSpec Code Generator. -package com.azure.search.documents.indexes.models; +package com.azure.search.documents.models; +import com.azure.core.annotation.Generated; import com.azure.core.util.ExpandableStringEnum; import java.util.Collection; @@ -14,16 +13,20 @@ */ public final class IndexerExecutionEnvironment extends ExpandableStringEnum { /** - * Indicates that the search service can determine where the indexer should execute. This is the default environment - * when nothing is specified and is the recommended value. + * Indicates that the search service can determine where the indexer should + * execute. This is the default environment when nothing is specified and is the + * recommended value. */ + @Generated public static final IndexerExecutionEnvironment STANDARD = fromString("standard"); /** - * Indicates that the indexer should run with the environment provisioned specifically for the search service. This - * should only be specified as the execution environment if the indexer needs to access resources securely over + * Indicates that the indexer should run with the environment provisioned + * specifically for the search service. This should only be specified as the + * execution environment if the indexer needs to access resources securely over * shared private link resources. */ + @Generated public static final IndexerExecutionEnvironment PRIVATE = fromString("private"); /** @@ -31,6 +34,7 @@ public final class IndexerExecutionEnvironment extends ExpandableStringEnum values() { return values(IndexerExecutionEnvironment.class); } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/IndexerExecutionResult.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/IndexerExecutionResult.java similarity index 76% rename from sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/IndexerExecutionResult.java rename to sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/IndexerExecutionResult.java index 66bf3a8b1a3f..89004d689307 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/IndexerExecutionResult.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/IndexerExecutionResult.java @@ -1,11 +1,10 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) TypeSpec Code Generator. -package com.azure.search.documents.indexes.models; +package com.azure.search.documents.models; +import com.azure.core.annotation.Generated; import com.azure.core.annotation.Immutable; import com.azure.core.util.CoreUtils; import com.azure.json.JsonReader; @@ -14,7 +13,7 @@ import com.azure.json.JsonWriter; import java.io.IOException; import java.time.OffsetDateTime; -import java.util.ArrayList; +import java.time.format.DateTimeFormatter; import java.util.List; /** @@ -25,62 +24,75 @@ public final class IndexerExecutionResult implements JsonSerializable errors; /* * The item-level indexing warnings. */ + @Generated private final List warnings; /* - * 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. + * 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. */ + @Generated private final int itemCount; /* * The number of items that failed to be indexed during this indexer execution. */ + @Generated private final int failedItemCount; /* * Change tracking state with which an indexer execution started. */ + @Generated private String initialTrackingState; /* * Change tracking state with which an indexer execution finished. */ + @Generated private String finalTrackingState; /** @@ -92,7 +104,8 @@ public final class IndexerExecutionResult implements JsonSerializable errors, + @Generated + private IndexerExecutionResult(IndexerExecutionStatus status, List errors, List warnings, int itemCount, int failedItemCount) { this.status = status; this.errors = errors; @@ -106,6 +119,7 @@ public IndexerExecutionResult(IndexerExecutionStatus status, List getErrors() { return this.errors; } @@ -169,16 +189,19 @@ public List getErrors() { * * @return the warnings value. */ + @Generated public List getWarnings() { return this.warnings; } /** - * Get the itemCount property: 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. + * Get the itemCount property: 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. * * @return the itemCount value. */ + @Generated public int getItemCount() { return this.itemCount; } @@ -188,6 +211,7 @@ public int getItemCount() { * * @return the failedItemCount value. */ + @Generated public int getFailedItemCount() { return this.failedItemCount; } @@ -197,6 +221,7 @@ public int getFailedItemCount() { * * @return the initialTrackingState value. */ + @Generated public String getInitialTrackingState() { return this.initialTrackingState; } @@ -206,6 +231,7 @@ public String getInitialTrackingState() { * * @return the finalTrackingState value. */ + @Generated public String getFinalTrackingState() { return this.finalTrackingState; } @@ -213,9 +239,22 @@ public String getFinalTrackingState() { /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); + jsonWriter.writeStringField("status", this.status == null ? null : this.status.toString()); + jsonWriter.writeArrayField("errors", this.errors, (writer, element) -> writer.writeJson(element)); + jsonWriter.writeArrayField("warnings", this.warnings, (writer, element) -> writer.writeJson(element)); + jsonWriter.writeIntField("itemsProcessed", this.itemCount); + jsonWriter.writeIntField("itemsFailed", this.failedItemCount); + jsonWriter.writeStringField("errorMessage", this.errorMessage); + jsonWriter.writeStringField("startTime", + this.startTime == null ? null : DateTimeFormatter.ISO_OFFSET_DATE_TIME.format(this.startTime)); + jsonWriter.writeStringField("endTime", + this.endTime == null ? null : DateTimeFormatter.ISO_OFFSET_DATE_TIME.format(this.endTime)); + jsonWriter.writeStringField("initialTrackingState", this.initialTrackingState); + jsonWriter.writeStringField("finalTrackingState", this.finalTrackingState); return jsonWriter.writeEndObject(); } @@ -228,17 +267,13 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { * @throws IllegalStateException If the deserialized JSON object was missing any required properties. * @throws IOException If an error occurs while reading the IndexerExecutionResult. */ + @Generated public static IndexerExecutionResult fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { - boolean statusFound = false; IndexerExecutionStatus status = null; - boolean errorsFound = false; List errors = null; - boolean warningsFound = false; List warnings = null; - boolean itemCountFound = false; int itemCount = 0; - boolean failedItemCountFound = false; int failedItemCount = 0; IndexerExecutionStatusDetail statusDetail = null; IndexerCurrentState currentState = null; @@ -253,19 +288,14 @@ public static IndexerExecutionResult fromJson(JsonReader jsonReader) throws IOEx if ("status".equals(fieldName)) { status = IndexerExecutionStatus.fromString(reader.getString()); - statusFound = true; } else if ("errors".equals(fieldName)) { errors = reader.readArray(reader1 -> SearchIndexerError.fromJson(reader1)); - errorsFound = true; } else if ("warnings".equals(fieldName)) { warnings = reader.readArray(reader1 -> SearchIndexerWarning.fromJson(reader1)); - warningsFound = true; } else if ("itemsProcessed".equals(fieldName)) { itemCount = reader.getInt(); - itemCountFound = true; } else if ("itemsFailed".equals(fieldName)) { failedItemCount = reader.getInt(); - failedItemCountFound = true; } else if ("statusDetail".equals(fieldName)) { statusDetail = IndexerExecutionStatusDetail.fromString(reader.getString()); } else if ("currentState".equals(fieldName)) { @@ -286,38 +316,17 @@ public static IndexerExecutionResult fromJson(JsonReader jsonReader) throws IOEx reader.skipChildren(); } } - if (statusFound && errorsFound && warningsFound && itemCountFound && failedItemCountFound) { - IndexerExecutionResult deserializedIndexerExecutionResult - = new IndexerExecutionResult(status, errors, warnings, itemCount, failedItemCount); - deserializedIndexerExecutionResult.statusDetail = statusDetail; - deserializedIndexerExecutionResult.currentState = currentState; - deserializedIndexerExecutionResult.errorMessage = errorMessage; - deserializedIndexerExecutionResult.startTime = startTime; - deserializedIndexerExecutionResult.endTime = endTime; - deserializedIndexerExecutionResult.initialTrackingState = initialTrackingState; - deserializedIndexerExecutionResult.finalTrackingState = finalTrackingState; - - return deserializedIndexerExecutionResult; - } - List missingProperties = new ArrayList<>(); - if (!statusFound) { - missingProperties.add("status"); - } - if (!errorsFound) { - missingProperties.add("errors"); - } - if (!warningsFound) { - missingProperties.add("warnings"); - } - if (!itemCountFound) { - missingProperties.add("itemsProcessed"); - } - if (!failedItemCountFound) { - missingProperties.add("itemsFailed"); - } - - throw new IllegalStateException( - "Missing required property/properties: " + String.join(", ", missingProperties)); + IndexerExecutionResult deserializedIndexerExecutionResult + = new IndexerExecutionResult(status, errors, warnings, itemCount, failedItemCount); + deserializedIndexerExecutionResult.statusDetail = statusDetail; + deserializedIndexerExecutionResult.currentState = currentState; + deserializedIndexerExecutionResult.errorMessage = errorMessage; + deserializedIndexerExecutionResult.startTime = startTime; + deserializedIndexerExecutionResult.endTime = endTime; + deserializedIndexerExecutionResult.initialTrackingState = initialTrackingState; + deserializedIndexerExecutionResult.finalTrackingState = finalTrackingState; + + return deserializedIndexerExecutionResult; }); } } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/IndexerExecutionStatus.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/IndexerExecutionStatus.java new file mode 100644 index 000000000000..83f837c19cb9 --- /dev/null +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/IndexerExecutionStatus.java @@ -0,0 +1,70 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.search.documents.models; + +import com.azure.core.annotation.Generated; +import com.azure.core.util.ExpandableStringEnum; +import java.util.Collection; + +/** + * Represents the status of an individual indexer execution. + */ +public final class IndexerExecutionStatus extends ExpandableStringEnum { + /** + * An indexer invocation has failed, but the failure may be transient. Indexer + * invocations will continue per schedule. + */ + @Generated + public static final IndexerExecutionStatus TRANSIENT_FAILURE = fromString("transientFailure"); + + /** + * Indexer execution completed successfully. + */ + @Generated + public static final IndexerExecutionStatus SUCCESS = fromString("success"); + + /** + * Indexer execution is in progress. + */ + @Generated + public static final IndexerExecutionStatus IN_PROGRESS = fromString("inProgress"); + + /** + * Indexer has been reset. + */ + @Generated + public static final IndexerExecutionStatus RESET = fromString("reset"); + + /** + * Creates a new instance of IndexerExecutionStatus value. + * + * @deprecated Use the {@link #fromString(String)} factory method. + */ + @Generated + @Deprecated + public IndexerExecutionStatus() { + } + + /** + * Creates or finds a IndexerExecutionStatus from its string representation. + * + * @param name a name to look for. + * @return the corresponding IndexerExecutionStatus. + */ + @Generated + public static IndexerExecutionStatus fromString(String name) { + return fromString(name, IndexerExecutionStatus.class); + } + + /** + * Gets known IndexerExecutionStatus values. + * + * @return known IndexerExecutionStatus values. + */ + @Generated + public static Collection values() { + return values(IndexerExecutionStatus.class); + } +} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/IndexerExecutionStatusDetail.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/IndexerExecutionStatusDetail.java similarity index 87% rename from sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/IndexerExecutionStatusDetail.java rename to sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/IndexerExecutionStatusDetail.java index 7c1decf3eddc..d80594bcf983 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/IndexerExecutionStatusDetail.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/IndexerExecutionStatusDetail.java @@ -1,11 +1,10 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) TypeSpec Code Generator. -package com.azure.search.documents.indexes.models; +package com.azure.search.documents.models; +import com.azure.core.annotation.Generated; import com.azure.core.util.ExpandableStringEnum; import java.util.Collection; @@ -16,6 +15,7 @@ public final class IndexerExecutionStatusDetail extends ExpandableStringEnum values() { return values(IndexerExecutionStatusDetail.class); } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/IndexerStatus.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/IndexerStatus.java new file mode 100644 index 000000000000..bba51c8ac705 --- /dev/null +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/IndexerStatus.java @@ -0,0 +1,64 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.search.documents.models; + +import com.azure.core.annotation.Generated; +import com.azure.core.util.ExpandableStringEnum; +import java.util.Collection; + +/** + * Represents the overall indexer status. + */ +public final class IndexerStatus extends ExpandableStringEnum { + /** + * Indicates that the indexer is in an unknown state. + */ + @Generated + public static final IndexerStatus UNKNOWN = fromString("unknown"); + + /** + * Indicates that the indexer experienced an error that cannot be corrected + * without human intervention. + */ + @Generated + public static final IndexerStatus ERROR = fromString("error"); + + /** + * Indicates that the indexer is running normally. + */ + @Generated + public static final IndexerStatus RUNNING = fromString("running"); + + /** + * Creates a new instance of IndexerStatus value. + * + * @deprecated Use the {@link #fromString(String)} factory method. + */ + @Generated + @Deprecated + public IndexerStatus() { + } + + /** + * Creates or finds a IndexerStatus from its string representation. + * + * @param name a name to look for. + * @return the corresponding IndexerStatus. + */ + @Generated + public static IndexerStatus fromString(String name) { + return fromString(name, IndexerStatus.class); + } + + /** + * Gets known IndexerStatus values. + * + * @return known IndexerStatus values. + */ + @Generated + public static Collection values() { + return values(IndexerStatus.class); + } +} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/IndexingMode.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/IndexingMode.java similarity index 81% rename from sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/IndexingMode.java rename to sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/IndexingMode.java index 7d7b1e8f6fe8..9e4d551c8ead 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/IndexingMode.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/IndexingMode.java @@ -1,11 +1,10 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) TypeSpec Code Generator. -package com.azure.search.documents.indexes.models; +package com.azure.search.documents.models; +import com.azure.core.annotation.Generated; import com.azure.core.util.ExpandableStringEnum; import java.util.Collection; @@ -16,12 +15,14 @@ public final class IndexingMode extends ExpandableStringEnum { /** * The indexer is indexing all documents in the datasource. */ + @Generated public static final IndexingMode INDEXING_ALL_DOCS = fromString("indexingAllDocs"); /** - * The indexer is indexing selective, reset documents in the datasource. The documents being indexed are defined on - * indexer status. + * The indexer is indexing selective, reset documents in the datasource. The + * documents being indexed are defined on indexer status. */ + @Generated public static final IndexingMode INDEXING_RESET_DOCS = fromString("indexingResetDocs"); /** @@ -29,6 +30,7 @@ public final class IndexingMode extends ExpandableStringEnum { * * @deprecated Use the {@link #fromString(String)} factory method. */ + @Generated @Deprecated public IndexingMode() { } @@ -39,6 +41,7 @@ public IndexingMode() { * @param name a name to look for. * @return the corresponding IndexingMode. */ + @Generated public static IndexingMode fromString(String name) { return fromString(name, IndexingMode.class); } @@ -48,6 +51,7 @@ public static IndexingMode fromString(String name) { * * @return known IndexingMode values. */ + @Generated public static Collection values() { return values(IndexingMode.class); } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/IndexingParameters.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/IndexingParameters.java similarity index 67% rename from sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/IndexingParameters.java rename to sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/IndexingParameters.java index 336d4d8661a2..8672989fdb40 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/IndexingParameters.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/IndexingParameters.java @@ -1,72 +1,79 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. -package com.azure.search.documents.indexes.models; +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.search.documents.models; import com.azure.core.annotation.Fluent; +import com.azure.core.annotation.Generated; import com.azure.json.JsonReader; import com.azure.json.JsonSerializable; import com.azure.json.JsonToken; import com.azure.json.JsonWriter; -import com.azure.search.documents.implementation.util.MappingUtils; import java.io.IOException; -import java.util.Map; /** * Represents parameters for indexer execution. */ @Fluent public final class IndexingParameters implements JsonSerializable { - /* - * 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. + * 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. */ + @Generated private Integer batchSize; /* - * The maximum number of items that can fail indexing for indexer execution to still be considered successful. -1 - * means no limit. Default is 0. + * The maximum number of items that can fail indexing for indexer execution to + * still be considered successful. -1 means no limit. Default is 0. */ + @Generated private Integer maxFailedItems; /* - * 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. + * 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. */ + @Generated private Integer maxFailedItemsPerBatch; /* - * A dictionary of indexer-specific configuration properties. Each name is the name of a specific property. Each - * value must be of a primitive type. + * A dictionary of indexer-specific configuration properties. Each name is the + * name of a specific property. Each value must be of a primitive type. */ + @Generated private IndexingParametersConfiguration configuration; /** * Creates an instance of IndexingParameters class. */ + @Generated public IndexingParameters() { } /** - * Get the batchSize property: 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. - * + * Get the batchSize property: 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. + * * @return the batchSize value. */ + @Generated public Integer getBatchSize() { return this.batchSize; } /** - * Set the batchSize property: 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. - * + * Set the batchSize property: 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. + * * @param batchSize the batchSize value to set. * @return the IndexingParameters object itself. */ + @Generated public IndexingParameters setBatchSize(Integer batchSize) { this.batchSize = batchSize; return this; @@ -75,9 +82,10 @@ public IndexingParameters setBatchSize(Integer batchSize) { /** * Get the maxFailedItems property: The maximum number of items that can fail indexing for indexer execution to * still be considered successful. -1 means no limit. Default is 0. - * + * * @return the maxFailedItems value. */ + @Generated public Integer getMaxFailedItems() { return this.maxFailedItems; } @@ -85,10 +93,11 @@ public Integer getMaxFailedItems() { /** * Set the maxFailedItems property: The maximum number of items that can fail indexing for indexer execution to * still be considered successful. -1 means no limit. Default is 0. - * + * * @param maxFailedItems the maxFailedItems value to set. * @return the IndexingParameters object itself. */ + @Generated public IndexingParameters setMaxFailedItems(Integer maxFailedItems) { this.maxFailedItems = maxFailedItems; return this; @@ -96,52 +105,58 @@ public IndexingParameters setMaxFailedItems(Integer maxFailedItems) { /** * Get the maxFailedItemsPerBatch property: 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. - * + * the + * batch to still be considered successful. -1 means no limit. Default is 0. + * * @return the maxFailedItemsPerBatch value. */ + @Generated public Integer getMaxFailedItemsPerBatch() { return this.maxFailedItemsPerBatch; } /** * Set the maxFailedItemsPerBatch property: 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. - * + * the + * batch to still be considered successful. -1 means no limit. Default is 0. + * * @param maxFailedItemsPerBatch the maxFailedItemsPerBatch value to set. * @return the IndexingParameters object itself. */ + @Generated public IndexingParameters setMaxFailedItemsPerBatch(Integer maxFailedItemsPerBatch) { this.maxFailedItemsPerBatch = maxFailedItemsPerBatch; return this; } /** - * Get the configuration property: A dictionary of indexer-specific configuration properties. Each name is the name - * of a specific property. Each value must be of a primitive type. - * + * Get the configuration property: A dictionary of indexer-specific configuration properties. Each name is the + * name of a specific property. Each value must be of a primitive type. + * * @return the configuration value. */ - public IndexingParametersConfiguration getIndexingParametersConfiguration() { + @Generated + public IndexingParametersConfiguration getConfiguration() { return this.configuration; } /** - * Set the configuration property: A dictionary of indexer-specific configuration properties. Each name is the name - * of a specific property. Each value must be of a primitive type. - * + * Set the configuration property: A dictionary of indexer-specific configuration properties. Each name is the + * name of a specific property. Each value must be of a primitive type. + * * @param configuration the configuration value to set. * @return the IndexingParameters object itself. */ - public IndexingParameters setIndexingParametersConfiguration(IndexingParametersConfiguration configuration) { + @Generated + public IndexingParameters setConfiguration(IndexingParametersConfiguration configuration) { this.configuration = configuration; - this.configurationMap = MappingUtils.indexingParametersConfigurationToMap(configuration); return this; } /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); @@ -154,18 +169,20 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of IndexingParameters from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of IndexingParameters if the JsonReader was pointing to an instance of it, or null if it was * pointing to JSON null. * @throws IOException If an error occurs while reading the IndexingParameters. */ + @Generated public static IndexingParameters fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { IndexingParameters deserializedIndexingParameters = new IndexingParameters(); while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); + if ("batchSize".equals(fieldName)) { deserializedIndexingParameters.batchSize = reader.getNullable(JsonReader::getInt); } else if ("maxFailedItems".equals(fieldName)) { @@ -178,32 +195,8 @@ public static IndexingParameters fromJson(JsonReader jsonReader) throws IOExcept reader.skipChildren(); } } + return deserializedIndexingParameters; }); } - - private Map configurationMap; - - /** - * Get the configuration property: A dictionary of indexer-specific configuration properties. Each name is the name - * of a specific property. Each value must be of a primitive type. - * - * @return the configuration value. - */ - public Map getConfiguration() { - return this.configurationMap; - } - - /** - * Set the configuration property: A dictionary of indexer-specific configuration properties. Each name is the name - * of a specific property. Each value must be of a primitive type. - * - * @param configuration the configuration value to set. - * @return the IndexingParameters object itself. - */ - public IndexingParameters setConfiguration(Map configuration) { - this.configurationMap = configuration; - this.configuration = MappingUtils.mapToIndexingParametersConfiguration(configuration); - return this; - } } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/IndexingParametersConfiguration.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/IndexingParametersConfiguration.java similarity index 75% rename from sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/IndexingParametersConfiguration.java rename to sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/IndexingParametersConfiguration.java index 9f0e8bec1381..514c8b2870e3 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/IndexingParametersConfiguration.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/IndexingParametersConfiguration.java @@ -1,12 +1,12 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) TypeSpec Code Generator. -package com.azure.search.documents.indexes.models; +package com.azure.search.documents.models; import com.azure.core.annotation.Fluent; +import com.azure.core.annotation.Generated; +import com.azure.core.util.BinaryData; import com.azure.json.JsonReader; import com.azure.json.JsonSerializable; import com.azure.json.JsonToken; @@ -16,125 +16,157 @@ import java.util.Map; /** - * A dictionary of indexer-specific configuration properties. Each name is the name of a specific property. Each value - * must be of a primitive type. + * A dictionary of indexer-specific configuration properties. Each name is the + * name of a specific property. Each value must be of a primitive type. */ @Fluent public final class IndexingParametersConfiguration implements JsonSerializable { /* * Represents the parsing mode for indexing from an Azure blob data source. */ + @Generated private BlobIndexerParsingMode parsingMode; /* - * 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. + * 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. */ + @Generated private String excludedFileNameExtensions; /* - * 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. + * 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. */ + @Generated private String indexedFileNameExtensions; /* - * 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. + * 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. */ + @Generated private Boolean failOnUnsupportedContentType; /* - * For Azure blobs, set to false if you want to continue indexing if a document fails indexing. + * For Azure blobs, set to false if you want to continue indexing if a document + * fails indexing. */ + @Generated private Boolean failOnUnprocessableDocument; /* - * 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 + * 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. */ + @Generated private Boolean indexStorageMetadataOnlyForOversizedDocuments; /* - * For CSV blobs, specifies a comma-delimited list of column headers, useful for mapping source fields to - * destination fields in an index. + * For CSV blobs, specifies a comma-delimited list of column headers, useful for + * mapping source fields to destination fields in an index. */ + @Generated private String delimitedTextHeaders; /* - * For CSV blobs, specifies the end-of-line single-character delimiter for CSV files where each line starts a new - * document (for example, "|"). + * For CSV blobs, specifies the end-of-line single-character delimiter for CSV + * files where each line starts a new document (for example, "|"). */ + @Generated private String delimitedTextDelimiter; /* - * For CSV blobs, indicates that the first (non-blank) line of each blob contains headers. + * For CSV blobs, indicates that the first (non-blank) line of each blob contains + * headers. */ + @Generated private Boolean firstLineContainsHeaders; /* - * 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`. + * 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`. */ + @Generated private MarkdownParsingSubmode markdownParsingSubmode; /* - * Specifies the max header depth that will be considered while grouping markdown content. Default is `h6`. + * Specifies the max header depth that will be considered while grouping markdown + * content. Default is `h6`. */ + @Generated private MarkdownHeaderDepth markdownHeaderDepth; /* - * For JSON arrays, given a structured or semi-structured document, you can specify a path to the array using this - * property. + * For JSON arrays, given a structured or semi-structured document, you can + * specify a path to the array using this property. */ + @Generated private String documentRoot; /* - * 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. + * 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. */ + @Generated private BlobIndexerDataToExtract dataToExtract; /* - * 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. + * 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. */ + @Generated private BlobIndexerImageAction imageAction; /* - * 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. + * 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. */ + @Generated private Boolean allowSkillsetToReadFileData; /* * Determines algorithm for text extraction from PDF files in Azure blob storage. */ - private BlobIndexerPdfTextRotationAlgorithm pdfTextRotationAlgorithm; + @Generated + private BlobIndexerPDFTextRotationAlgorithm pdfTextRotationAlgorithm; /* * Specifies the environment in which the indexer should execute. */ + @Generated private IndexerExecutionEnvironment executionEnvironment; /* - * Increases the timeout beyond the 5-minute default for Azure SQL database data sources, specified in the format - * "hh:mm:ss". + * Increases the timeout beyond the 5-minute default for Azure SQL database data + * sources, specified in the format "hh:mm:ss". */ + @Generated private String queryTimeout; /* - * A dictionary of indexer-specific configuration properties. Each name is the name of a specific property. Each - * value must be of a primitive type. + * A dictionary of indexer-specific configuration properties. Each name is the + * name of a specific property. Each value must be of a primitive type. */ - private Map additionalProperties; + @Generated + private Map additionalProperties; /** * Creates an instance of IndexingParametersConfiguration class. */ + @Generated public IndexingParametersConfiguration() { } @@ -143,6 +175,7 @@ public IndexingParametersConfiguration() { * * @return the parsingMode value. */ + @Generated public BlobIndexerParsingMode getParsingMode() { return this.parsingMode; } @@ -153,6 +186,7 @@ public BlobIndexerParsingMode getParsingMode() { * @param parsingMode the parsingMode value to set. * @return the IndexingParametersConfiguration object itself. */ + @Generated public IndexingParametersConfiguration setParsingMode(BlobIndexerParsingMode parsingMode) { this.parsingMode = parsingMode; return this; @@ -160,23 +194,27 @@ public IndexingParametersConfiguration setParsingMode(BlobIndexerParsingMode par /** * Get the excludedFileNameExtensions property: 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. + * processing from + * Azure blob storage. For example, you could exclude ".png, .mp4" to skip over + * those files during indexing. * * @return the excludedFileNameExtensions value. */ + @Generated public String getExcludedFileNameExtensions() { return this.excludedFileNameExtensions; } /** * Set the excludedFileNameExtensions property: 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. + * processing from + * Azure blob storage. For example, you could exclude ".png, .mp4" to skip over + * those files during indexing. * * @param excludedFileNameExtensions the excludedFileNameExtensions value to set. * @return the IndexingParametersConfiguration object itself. */ + @Generated public IndexingParametersConfiguration setExcludedFileNameExtensions(String excludedFileNameExtensions) { this.excludedFileNameExtensions = excludedFileNameExtensions; return this; @@ -184,23 +222,29 @@ public IndexingParametersConfiguration setExcludedFileNameExtensions(String excl /** * Get the indexedFileNameExtensions property: 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. + * from + * Azure blob storage. For example, you could focus indexing on specific + * application files ".docx, .pptx, .msg" to specifically include those file + * types. * * @return the indexedFileNameExtensions value. */ + @Generated public String getIndexedFileNameExtensions() { return this.indexedFileNameExtensions; } /** * Set the indexedFileNameExtensions property: 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. + * from + * Azure blob storage. For example, you could focus indexing on specific + * application files ".docx, .pptx, .msg" to specifically include those file + * types. * * @param indexedFileNameExtensions the indexedFileNameExtensions value to set. * @return the IndexingParametersConfiguration object itself. */ + @Generated public IndexingParametersConfiguration setIndexedFileNameExtensions(String indexedFileNameExtensions) { this.indexedFileNameExtensions = indexedFileNameExtensions; return this; @@ -208,23 +252,27 @@ public IndexingParametersConfiguration setIndexedFileNameExtensions(String index /** * Get the failOnUnsupportedContentType property: 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. + * when an + * unsupported content type is encountered, and you don't know all the content + * types (file extensions) in advance. * * @return the failOnUnsupportedContentType value. */ + @Generated public Boolean isFailOnUnsupportedContentType() { return this.failOnUnsupportedContentType; } /** * Set the failOnUnsupportedContentType property: 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. + * when an + * unsupported content type is encountered, and you don't know all the content + * types (file extensions) in advance. * * @param failOnUnsupportedContentType the failOnUnsupportedContentType value to set. * @return the IndexingParametersConfiguration object itself. */ + @Generated public IndexingParametersConfiguration setFailOnUnsupportedContentType(Boolean failOnUnsupportedContentType) { this.failOnUnsupportedContentType = failOnUnsupportedContentType; return this; @@ -232,21 +280,25 @@ public IndexingParametersConfiguration setFailOnUnsupportedContentType(Boolean f /** * Get the failOnUnprocessableDocument property: For Azure blobs, set to false if you want to continue indexing if a - * document fails indexing. + * document + * fails indexing. * * @return the failOnUnprocessableDocument value. */ + @Generated public Boolean isFailOnUnprocessableDocument() { return this.failOnUnprocessableDocument; } /** * Set the failOnUnprocessableDocument property: For Azure blobs, set to false if you want to continue indexing if a - * document fails indexing. + * document + * fails indexing. * * @param failOnUnprocessableDocument the failOnUnprocessableDocument value to set. * @return the IndexingParametersConfiguration object itself. */ + @Generated public IndexingParametersConfiguration setFailOnUnprocessableDocument(Boolean failOnUnprocessableDocument) { this.failOnUnprocessableDocument = failOnUnprocessableDocument; return this; @@ -254,24 +306,30 @@ public IndexingParametersConfiguration setFailOnUnprocessableDocument(Boolean fa /** * Get the indexStorageMetadataOnlyForOversizedDocuments property: 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. + * 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. * * @return the indexStorageMetadataOnlyForOversizedDocuments value. */ + @Generated public Boolean isIndexStorageMetadataOnlyForOversizedDocuments() { return this.indexStorageMetadataOnlyForOversizedDocuments; } /** * Set the indexStorageMetadataOnlyForOversizedDocuments property: 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. + * 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. * * @param indexStorageMetadataOnlyForOversizedDocuments the indexStorageMetadataOnlyForOversizedDocuments value to * set. * @return the IndexingParametersConfiguration object itself. */ + @Generated public IndexingParametersConfiguration setIndexStorageMetadataOnlyForOversizedDocuments(Boolean indexStorageMetadataOnlyForOversizedDocuments) { this.indexStorageMetadataOnlyForOversizedDocuments = indexStorageMetadataOnlyForOversizedDocuments; @@ -280,21 +338,25 @@ public Boolean isIndexStorageMetadataOnlyForOversizedDocuments() { /** * Get the delimitedTextHeaders property: For CSV blobs, specifies a comma-delimited list of column headers, useful - * for mapping source fields to destination fields in an index. + * for + * mapping source fields to destination fields in an index. * * @return the delimitedTextHeaders value. */ + @Generated public String getDelimitedTextHeaders() { return this.delimitedTextHeaders; } /** * Set the delimitedTextHeaders property: For CSV blobs, specifies a comma-delimited list of column headers, useful - * for mapping source fields to destination fields in an index. + * for + * mapping source fields to destination fields in an index. * * @param delimitedTextHeaders the delimitedTextHeaders value to set. * @return the IndexingParametersConfiguration object itself. */ + @Generated public IndexingParametersConfiguration setDelimitedTextHeaders(String delimitedTextHeaders) { this.delimitedTextHeaders = delimitedTextHeaders; return this; @@ -302,21 +364,25 @@ public IndexingParametersConfiguration setDelimitedTextHeaders(String delimitedT /** * Get the delimitedTextDelimiter property: For CSV blobs, specifies the end-of-line single-character delimiter for - * CSV files where each line starts a new document (for example, "|"). + * CSV + * files where each line starts a new document (for example, "|"). * * @return the delimitedTextDelimiter value. */ + @Generated public String getDelimitedTextDelimiter() { return this.delimitedTextDelimiter; } /** * Set the delimitedTextDelimiter property: For CSV blobs, specifies the end-of-line single-character delimiter for - * CSV files where each line starts a new document (for example, "|"). + * CSV + * files where each line starts a new document (for example, "|"). * * @param delimitedTextDelimiter the delimitedTextDelimiter value to set. * @return the IndexingParametersConfiguration object itself. */ + @Generated public IndexingParametersConfiguration setDelimitedTextDelimiter(String delimitedTextDelimiter) { this.delimitedTextDelimiter = delimitedTextDelimiter; return this; @@ -324,21 +390,25 @@ public IndexingParametersConfiguration setDelimitedTextDelimiter(String delimite /** * Get the firstLineContainsHeaders property: For CSV blobs, indicates that the first (non-blank) line of each blob - * contains headers. + * contains + * headers. * * @return the firstLineContainsHeaders value. */ + @Generated public Boolean isFirstLineContainsHeaders() { return this.firstLineContainsHeaders; } /** * Set the firstLineContainsHeaders property: For CSV blobs, indicates that the first (non-blank) line of each blob - * contains headers. + * contains + * headers. * * @param firstLineContainsHeaders the firstLineContainsHeaders value to set. * @return the IndexingParametersConfiguration object itself. */ + @Generated public IndexingParametersConfiguration setFirstLineContainsHeaders(Boolean firstLineContainsHeaders) { this.firstLineContainsHeaders = firstLineContainsHeaders; return this; @@ -346,21 +416,27 @@ public IndexingParametersConfiguration setFirstLineContainsHeaders(Boolean first /** * Get the markdownParsingSubmode property: 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`. + * be + * parsed into exactly one search document or multiple search documents. Default + * is `oneToMany`. * * @return the markdownParsingSubmode value. */ + @Generated public MarkdownParsingSubmode getMarkdownParsingSubmode() { return this.markdownParsingSubmode; } /** * Set the markdownParsingSubmode property: 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`. + * be + * parsed into exactly one search document or multiple search documents. Default + * is `oneToMany`. * * @param markdownParsingSubmode the markdownParsingSubmode value to set. * @return the IndexingParametersConfiguration object itself. */ + @Generated public IndexingParametersConfiguration setMarkdownParsingSubmode(MarkdownParsingSubmode markdownParsingSubmode) { this.markdownParsingSubmode = markdownParsingSubmode; return this; @@ -368,91 +444,103 @@ public IndexingParametersConfiguration setMarkdownParsingSubmode(MarkdownParsing /** * Get the markdownHeaderDepth property: Specifies the max header depth that will be considered while grouping - * markdown content. Default is `h6`. + * markdown + * content. Default is `h6`. * * @return the markdownHeaderDepth value. */ + @Generated public MarkdownHeaderDepth getMarkdownHeaderDepth() { return this.markdownHeaderDepth; } /** * Set the markdownHeaderDepth property: Specifies the max header depth that will be considered while grouping - * markdown content. Default is `h6`. + * markdown + * content. Default is `h6`. * * @param markdownHeaderDepth the markdownHeaderDepth value to set. * @return the IndexingParametersConfiguration object itself. */ + @Generated public IndexingParametersConfiguration setMarkdownHeaderDepth(MarkdownHeaderDepth markdownHeaderDepth) { this.markdownHeaderDepth = markdownHeaderDepth; return this; } /** - * Get the documentRoot property: For JSON arrays, given a structured or semi-structured document, you can specify a - * path to the array using this property. + * Get the documentRoot property: For JSON arrays, given a structured or semi-structured document, you can + * specify a path to the array using this property. * * @return the documentRoot value. */ + @Generated public String getDocumentRoot() { return this.documentRoot; } /** - * Set the documentRoot property: For JSON arrays, given a structured or semi-structured document, you can specify a - * path to the array using this property. + * Set the documentRoot property: For JSON arrays, given a structured or semi-structured document, you can + * specify a path to the array using this property. * * @param documentRoot the documentRoot value to set. * @return the IndexingParametersConfiguration object itself. */ + @Generated public IndexingParametersConfiguration setDocumentRoot(String documentRoot) { this.documentRoot = documentRoot; return this; } /** - * Get the dataToExtract property: 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. + * Get the dataToExtract property: 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. * * @return the dataToExtract value. */ + @Generated public BlobIndexerDataToExtract getDataToExtract() { return this.dataToExtract; } /** - * Set the dataToExtract property: 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. + * Set the dataToExtract property: 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. * * @param dataToExtract the dataToExtract value to set. * @return the IndexingParametersConfiguration object itself. */ + @Generated public IndexingParametersConfiguration setDataToExtract(BlobIndexerDataToExtract dataToExtract) { this.dataToExtract = dataToExtract; return this; } /** - * Get the imageAction property: 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. + * Get the imageAction property: 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. * * @return the imageAction value. */ + @Generated public BlobIndexerImageAction getImageAction() { return this.imageAction; } /** - * Set the imageAction property: 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. + * Set the imageAction property: 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. * * @param imageAction the imageAction value to set. * @return the IndexingParametersConfiguration object itself. */ + @Generated public IndexingParametersConfiguration setImageAction(BlobIndexerImageAction imageAction) { this.imageAction = imageAction; return this; @@ -460,23 +548,27 @@ public IndexingParametersConfiguration setImageAction(BlobIndexerImageAction ima /** * Get the allowSkillsetToReadFileData property: 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. + * 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. * * @return the allowSkillsetToReadFileData value. */ + @Generated public Boolean isAllowSkillsetToReadFileData() { return this.allowSkillsetToReadFileData; } /** * Set the allowSkillsetToReadFileData property: 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. + * 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. * * @param allowSkillsetToReadFileData the allowSkillsetToReadFileData value to set. * @return the IndexingParametersConfiguration object itself. */ + @Generated public IndexingParametersConfiguration setAllowSkillsetToReadFileData(Boolean allowSkillsetToReadFileData) { this.allowSkillsetToReadFileData = allowSkillsetToReadFileData; return this; @@ -488,7 +580,8 @@ public IndexingParametersConfiguration setAllowSkillsetToReadFileData(Boolean al * * @return the pdfTextRotationAlgorithm value. */ - public BlobIndexerPdfTextRotationAlgorithm getPdfTextRotationAlgorithm() { + @Generated + public BlobIndexerPDFTextRotationAlgorithm getPdfTextRotationAlgorithm() { return this.pdfTextRotationAlgorithm; } @@ -499,8 +592,9 @@ public BlobIndexerPdfTextRotationAlgorithm getPdfTextRotationAlgorithm() { * @param pdfTextRotationAlgorithm the pdfTextRotationAlgorithm value to set. * @return the IndexingParametersConfiguration object itself. */ + @Generated public IndexingParametersConfiguration - setPdfTextRotationAlgorithm(BlobIndexerPdfTextRotationAlgorithm pdfTextRotationAlgorithm) { + setPdfTextRotationAlgorithm(BlobIndexerPDFTextRotationAlgorithm pdfTextRotationAlgorithm) { this.pdfTextRotationAlgorithm = pdfTextRotationAlgorithm; return this; } @@ -510,6 +604,7 @@ public BlobIndexerPdfTextRotationAlgorithm getPdfTextRotationAlgorithm() { * * @return the executionEnvironment value. */ + @Generated public IndexerExecutionEnvironment getExecutionEnvironment() { return this.executionEnvironment; } @@ -520,6 +615,7 @@ public IndexerExecutionEnvironment getExecutionEnvironment() { * @param executionEnvironment the executionEnvironment value to set. * @return the IndexingParametersConfiguration object itself. */ + @Generated public IndexingParametersConfiguration setExecutionEnvironment(IndexerExecutionEnvironment executionEnvironment) { this.executionEnvironment = executionEnvironment; return this; @@ -531,6 +627,7 @@ public IndexingParametersConfiguration setExecutionEnvironment(IndexerExecutionE * * @return the queryTimeout value. */ + @Generated public String getQueryTimeout() { return this.queryTimeout; } @@ -542,6 +639,7 @@ public String getQueryTimeout() { * @param queryTimeout the queryTimeout value to set. * @return the IndexingParametersConfiguration object itself. */ + @Generated public IndexingParametersConfiguration setQueryTimeout(String queryTimeout) { this.queryTimeout = queryTimeout; return this; @@ -549,22 +647,26 @@ public IndexingParametersConfiguration setQueryTimeout(String queryTimeout) { /** * Get the additionalProperties property: A dictionary of indexer-specific configuration properties. Each name is - * the name of a specific property. Each value must be of a primitive type. + * the + * name of a specific property. Each value must be of a primitive type. * * @return the additionalProperties value. */ - public Map getAdditionalProperties() { + @Generated + public Map getAdditionalProperties() { return this.additionalProperties; } /** * Set the additionalProperties property: A dictionary of indexer-specific configuration properties. Each name is - * the name of a specific property. Each value must be of a primitive type. + * the + * name of a specific property. Each value must be of a primitive type. * * @param additionalProperties the additionalProperties value to set. * @return the IndexingParametersConfiguration object itself. */ - public IndexingParametersConfiguration setAdditionalProperties(Map additionalProperties) { + @Generated + public IndexingParametersConfiguration setAdditionalProperties(Map additionalProperties) { this.additionalProperties = additionalProperties; return this; } @@ -572,6 +674,7 @@ public IndexingParametersConfiguration setAdditionalProperties(Map additionalProperty : additionalProperties.entrySet()) { - jsonWriter.writeUntypedField(additionalProperty.getKey(), additionalProperty.getValue()); + for (Map.Entry additionalProperty : additionalProperties.entrySet()) { + jsonWriter.writeFieldName(additionalProperty.getKey()); + if (additionalProperty.getValue() == null) { + jsonWriter.writeNull(); + } else { + additionalProperty.getValue().writeTo(jsonWriter); + } } } return jsonWriter.writeEndObject(); @@ -614,11 +722,12 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { * null if it was pointing to JSON null. * @throws IOException If an error occurs while reading the IndexingParametersConfiguration. */ + @Generated public static IndexingParametersConfiguration fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { IndexingParametersConfiguration deserializedIndexingParametersConfiguration = new IndexingParametersConfiguration(); - Map additionalProperties = null; + Map additionalProperties = null; while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); @@ -665,7 +774,7 @@ public static IndexingParametersConfiguration fromJson(JsonReader jsonReader) th = reader.getNullable(JsonReader::getBoolean); } else if ("pdfTextRotationAlgorithm".equals(fieldName)) { deserializedIndexingParametersConfiguration.pdfTextRotationAlgorithm - = BlobIndexerPdfTextRotationAlgorithm.fromString(reader.getString()); + = BlobIndexerPDFTextRotationAlgorithm.fromString(reader.getString()); } else if ("executionEnvironment".equals(fieldName)) { deserializedIndexingParametersConfiguration.executionEnvironment = IndexerExecutionEnvironment.fromString(reader.getString()); @@ -676,7 +785,8 @@ public static IndexingParametersConfiguration fromJson(JsonReader jsonReader) th additionalProperties = new LinkedHashMap<>(); } - additionalProperties.put(fieldName, reader.readUntyped()); + additionalProperties.put(fieldName, + reader.getNullable(nonNullReader -> BinaryData.fromObject(nonNullReader.readUntyped()))); } } deserializedIndexingParametersConfiguration.additionalProperties = additionalProperties; diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/IndexingResult.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/IndexingResult.java index 095b7858a024..9a7e5d25b019 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/IndexingResult.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/IndexingResult.java @@ -1,57 +1,61 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) TypeSpec Code Generator. + package com.azure.search.documents.models; +import com.azure.core.annotation.Generated; import com.azure.core.annotation.Immutable; import com.azure.json.JsonReader; import com.azure.json.JsonSerializable; import com.azure.json.JsonToken; import com.azure.json.JsonWriter; import java.io.IOException; -import java.io.Serializable; -import java.util.ArrayList; -import java.util.List; /** * Status of an indexing operation for a single document. */ @Immutable -public final class IndexingResult implements JsonSerializable, Serializable { - - /** +public final class IndexingResult implements JsonSerializable { + /* * The key of a document that was in the indexing request. */ + @Generated private final String key; - /** - * The error message explaining why the indexing operation failed for the document identified by the key; null if - * indexing succeeded. + /* + * The error message explaining why the indexing operation failed for the document + * identified by the key; null if indexing succeeded. */ + @Generated private String errorMessage; - /** - * A value indicating whether the indexing operation succeeded for the document identified by the key. + /* + * A value indicating whether the indexing operation succeeded for the document + * identified by the key. */ + @Generated private final boolean succeeded; - /** - * 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. + /* + * 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. */ + @Generated private final int statusCode; /** * Creates an instance of IndexingResult class. - * + * * @param key the key value to set. * @param succeeded the succeeded value to set. * @param statusCode the statusCode value to set. */ - public IndexingResult(String key, boolean succeeded, int statusCode) { + @Generated + private IndexingResult(String key, boolean succeeded, int statusCode) { this.key = key; this.succeeded = succeeded; this.statusCode = statusCode; @@ -59,9 +63,10 @@ public IndexingResult(String key, boolean succeeded, int statusCode) { /** * Get the key property: The key of a document that was in the indexing request. - * + * * @return the key value. */ + @Generated public String getKey() { return this.key; } @@ -69,9 +74,10 @@ public String getKey() { /** * Get the errorMessage property: The error message explaining why the indexing operation failed for the document * identified by the key; null if indexing succeeded. - * + * * @return the errorMessage value. */ + @Generated public String getErrorMessage() { return this.errorMessage; } @@ -79,21 +85,24 @@ public String getErrorMessage() { /** * Get the succeeded property: A value indicating whether the indexing operation succeeded for the document * identified by the key. - * + * * @return the succeeded value. */ + @Generated public boolean isSucceeded() { return this.succeeded; } /** * Get the statusCode property: 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. - * + * 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. + * * @return the statusCode value. */ + @Generated public int getStatusCode() { return this.statusCode; } @@ -101,67 +110,53 @@ public int getStatusCode() { /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); + jsonWriter.writeStringField("key", this.key); + jsonWriter.writeBooleanField("status", this.succeeded); + jsonWriter.writeIntField("statusCode", this.statusCode); + jsonWriter.writeStringField("errorMessage", this.errorMessage); return jsonWriter.writeEndObject(); } /** * Reads an instance of IndexingResult from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of IndexingResult if the JsonReader was pointing to an instance of it, or null if it was * pointing to JSON null. * @throws IllegalStateException If the deserialized JSON object was missing any required properties. * @throws IOException If an error occurs while reading the IndexingResult. */ + @Generated public static IndexingResult fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { - boolean keyFound = false; String key = null; - boolean succeededFound = false; boolean succeeded = false; - boolean statusCodeFound = false; int statusCode = 0; String errorMessage = null; while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); + if ("key".equals(fieldName)) { key = reader.getString(); - keyFound = true; } else if ("status".equals(fieldName)) { succeeded = reader.getBoolean(); - succeededFound = true; } else if ("statusCode".equals(fieldName)) { statusCode = reader.getInt(); - statusCodeFound = true; } else if ("errorMessage".equals(fieldName)) { errorMessage = reader.getString(); } else { reader.skipChildren(); } } - if (keyFound && succeededFound && statusCodeFound) { - IndexingResult deserializedIndexingResult = new IndexingResult(key, succeeded, statusCode); - deserializedIndexingResult.errorMessage = errorMessage; - return deserializedIndexingResult; - } - List missingProperties = new ArrayList<>(); - if (!keyFound) { - missingProperties.add("key"); - } - if (!succeededFound) { - missingProperties.add("status"); - } - if (!statusCodeFound) { - missingProperties.add("statusCode"); - } - throw new IllegalStateException( - "Missing required property/properties: " + String.join(", ", missingProperties)); + IndexingResult deserializedIndexingResult = new IndexingResult(key, succeeded, statusCode); + deserializedIndexingResult.errorMessage = errorMessage; + + return deserializedIndexingResult; }); } - - private static final long serialVersionUID = -8604424005271188140L; } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/IndexingSchedule.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/IndexingSchedule.java similarity index 85% rename from sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/IndexingSchedule.java rename to sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/IndexingSchedule.java index 56637b0a482c..ade334292441 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/IndexingSchedule.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/IndexingSchedule.java @@ -1,12 +1,11 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) TypeSpec Code Generator. -package com.azure.search.documents.indexes.models; +package com.azure.search.documents.models; import com.azure.core.annotation.Fluent; +import com.azure.core.annotation.Generated; import com.azure.core.util.CoreUtils; import com.azure.json.JsonReader; import com.azure.json.JsonSerializable; @@ -25,11 +24,13 @@ public final class IndexingSchedule implements JsonSerializable { - boolean intervalFound = false; Duration interval = null; OffsetDateTime startTime = null; while (reader.nextToken() != JsonToken.END_OBJECT) { @@ -102,7 +108,6 @@ public static IndexingSchedule fromJson(JsonReader jsonReader) throws IOExceptio if ("interval".equals(fieldName)) { interval = reader.getNullable(nonNullReader -> Duration.parse(nonNullReader.getString())); - intervalFound = true; } else if ("startTime".equals(fieldName)) { startTime = reader .getNullable(nonNullReader -> CoreUtils.parseBestOffsetDateTime(nonNullReader.getString())); @@ -110,13 +115,10 @@ public static IndexingSchedule fromJson(JsonReader jsonReader) throws IOExceptio reader.skipChildren(); } } - if (intervalFound) { - IndexingSchedule deserializedIndexingSchedule = new IndexingSchedule(interval); - deserializedIndexingSchedule.startTime = startTime; + IndexingSchedule deserializedIndexingSchedule = new IndexingSchedule(interval); + deserializedIndexingSchedule.startTime = startTime; - return deserializedIndexingSchedule; - } - throw new IllegalStateException("Missing required property: interval"); + return deserializedIndexingSchedule; }); } } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/InputFieldMappingEntry.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/InputFieldMappingEntry.java similarity index 79% rename from sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/InputFieldMappingEntry.java rename to sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/InputFieldMappingEntry.java index f3df94a089fc..f35230184d49 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/InputFieldMappingEntry.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/InputFieldMappingEntry.java @@ -1,17 +1,16 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. -package com.azure.search.documents.indexes.models; +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.search.documents.models; import com.azure.core.annotation.Fluent; +import com.azure.core.annotation.Generated; import com.azure.json.JsonReader; import com.azure.json.JsonSerializable; import com.azure.json.JsonToken; import com.azure.json.JsonWriter; import java.io.IOException; -import java.util.Arrays; import java.util.List; /** @@ -19,60 +18,67 @@ */ @Fluent public final class InputFieldMappingEntry implements JsonSerializable { - /* * The name of the input. */ + @Generated private final String name; /* * The source of the input. */ + @Generated private String source; /* * The source context used for selecting recursive inputs. */ + @Generated private String sourceContext; /* * The recursive inputs used when creating a complex type. */ + @Generated private List inputs; /** * Creates an instance of InputFieldMappingEntry class. - * + * * @param name the name value to set. */ + @Generated public InputFieldMappingEntry(String name) { this.name = name; } /** * Get the name property: The name of the input. - * + * * @return the name value. */ + @Generated public String getName() { return this.name; } /** * Get the source property: The source of the input. - * + * * @return the source value. */ + @Generated public String getSource() { return this.source; } /** * Set the source property: The source of the input. - * + * * @param source the source value to set. * @return the InputFieldMappingEntry object itself. */ + @Generated public InputFieldMappingEntry setSource(String source) { this.source = source; return this; @@ -80,19 +86,21 @@ public InputFieldMappingEntry setSource(String source) { /** * Get the sourceContext property: The source context used for selecting recursive inputs. - * + * * @return the sourceContext value. */ + @Generated public String getSourceContext() { return this.sourceContext; } /** * Set the sourceContext property: The source context used for selecting recursive inputs. - * + * * @param sourceContext the sourceContext value to set. * @return the InputFieldMappingEntry object itself. */ + @Generated public InputFieldMappingEntry setSourceContext(String sourceContext) { this.sourceContext = sourceContext; return this; @@ -100,19 +108,21 @@ public InputFieldMappingEntry setSourceContext(String sourceContext) { /** * Get the inputs property: The recursive inputs used when creating a complex type. - * + * * @return the inputs value. */ + @Generated public List getInputs() { return this.inputs; } /** * Set the inputs property: The recursive inputs used when creating a complex type. - * + * * @param inputs the inputs value to set. * @return the InputFieldMappingEntry object itself. */ + @Generated public InputFieldMappingEntry setInputs(List inputs) { this.inputs = inputs; return this; @@ -121,6 +131,7 @@ public InputFieldMappingEntry setInputs(List inputs) { /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); @@ -133,16 +144,16 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of InputFieldMappingEntry from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of InputFieldMappingEntry if the JsonReader was pointing to an instance of it, or null if it * was pointing to JSON null. * @throws IllegalStateException If the deserialized JSON object was missing any required properties. * @throws IOException If an error occurs while reading the InputFieldMappingEntry. */ + @Generated public static InputFieldMappingEntry fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { - boolean nameFound = false; String name = null; String source = null; String sourceContext = null; @@ -150,9 +161,9 @@ public static InputFieldMappingEntry fromJson(JsonReader jsonReader) throws IOEx while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); + if ("name".equals(fieldName)) { name = reader.getString(); - nameFound = true; } else if ("source".equals(fieldName)) { source = reader.getString(); } else if ("sourceContext".equals(fieldName)) { @@ -163,25 +174,12 @@ public static InputFieldMappingEntry fromJson(JsonReader jsonReader) throws IOEx reader.skipChildren(); } } - if (nameFound) { - InputFieldMappingEntry deserializedInputFieldMappingEntry = new InputFieldMappingEntry(name); - deserializedInputFieldMappingEntry.source = source; - deserializedInputFieldMappingEntry.sourceContext = sourceContext; - deserializedInputFieldMappingEntry.inputs = inputs; - return deserializedInputFieldMappingEntry; - } - throw new IllegalStateException("Missing required property: name"); - }); - } + InputFieldMappingEntry deserializedInputFieldMappingEntry = new InputFieldMappingEntry(name); + deserializedInputFieldMappingEntry.source = source; + deserializedInputFieldMappingEntry.sourceContext = sourceContext; + deserializedInputFieldMappingEntry.inputs = inputs; - /** - * Set the inputs property: The recursive inputs used when creating a complex type. - * - * @param inputs the inputs value to set. - * @return the InputFieldMappingEntry object itself. - */ - public InputFieldMappingEntry setInputs(InputFieldMappingEntry... inputs) { - this.inputs = (inputs == null) ? null : Arrays.asList(inputs); - return this; + return deserializedInputFieldMappingEntry; + }); } } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/KeepTokenFilter.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/KeepTokenFilter.java similarity index 73% rename from sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/KeepTokenFilter.java rename to sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/KeepTokenFilter.java index 73c0c6427325..414e78a15371 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/KeepTokenFilter.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/KeepTokenFilter.java @@ -1,56 +1,59 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. -package com.azure.search.documents.indexes.models; +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.search.documents.models; import com.azure.core.annotation.Fluent; +import com.azure.core.annotation.Generated; import com.azure.json.JsonReader; import com.azure.json.JsonToken; import com.azure.json.JsonWriter; import java.io.IOException; -import java.util.ArrayList; import java.util.List; /** - * A token filter that only keeps tokens with text contained in a specified list of words. This token filter is - * implemented using Apache Lucene. + * A token filter that only keeps tokens with text contained in a specified list + * of words. This token filter is implemented using Apache Lucene. */ @Fluent public final class KeepTokenFilter extends TokenFilter { - /* - * A URI fragment specifying the type of token filter. + * The discriminator for derived types. */ + @Generated private String odataType = "#Microsoft.Azure.Search.KeepTokenFilter"; /* * The list of words to keep. */ + @Generated private final List keepWords; /* * A value indicating whether to lower case all words first. Default is false. */ + @Generated private Boolean lowerCaseKeepWords; /** * Creates an instance of KeepTokenFilter class. - * + * * @param name the name value to set. * @param keepWords the keepWords value to set. */ + @Generated public KeepTokenFilter(String name, List keepWords) { super(name); this.keepWords = keepWords; } /** - * Get the odataType property: A URI fragment specifying the type of token filter. - * + * Get the odataType property: The discriminator for derived types. + * * @return the odataType value. */ + @Generated @Override public String getOdataType() { return this.odataType; @@ -58,28 +61,31 @@ public String getOdataType() { /** * Get the keepWords property: The list of words to keep. - * + * * @return the keepWords value. */ + @Generated public List getKeepWords() { return this.keepWords; } /** * Get the lowerCaseKeepWords property: A value indicating whether to lower case all words first. Default is false. - * + * * @return the lowerCaseKeepWords value. */ - public Boolean areLowerCaseKeepWords() { + @Generated + public Boolean isLowerCaseKeepWords() { return this.lowerCaseKeepWords; } /** * Set the lowerCaseKeepWords property: A value indicating whether to lower case all words first. Default is false. - * + * * @param lowerCaseKeepWords the lowerCaseKeepWords value to set. * @return the KeepTokenFilter object itself. */ + @Generated public KeepTokenFilter setLowerCaseKeepWords(Boolean lowerCaseKeepWords) { this.lowerCaseKeepWords = lowerCaseKeepWords; return this; @@ -88,6 +94,7 @@ public KeepTokenFilter setLowerCaseKeepWords(Boolean lowerCaseKeepWords) { /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); @@ -100,30 +107,28 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of KeepTokenFilter from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of KeepTokenFilter if the JsonReader was pointing to an instance of it, or null if it was * pointing to JSON null. * @throws IllegalStateException If the deserialized JSON object was missing any required properties. * @throws IOException If an error occurs while reading the KeepTokenFilter. */ + @Generated public static KeepTokenFilter fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { - boolean nameFound = false; String name = null; - boolean keepWordsFound = false; List keepWords = null; String odataType = "#Microsoft.Azure.Search.KeepTokenFilter"; Boolean lowerCaseKeepWords = null; while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); + if ("name".equals(fieldName)) { name = reader.getString(); - nameFound = true; } else if ("keepWords".equals(fieldName)) { keepWords = reader.readArray(reader1 -> reader1.getString()); - keepWordsFound = true; } else if ("@odata.type".equals(fieldName)) { odataType = reader.getString(); } else if ("keepWordsCase".equals(fieldName)) { @@ -132,21 +137,11 @@ public static KeepTokenFilter fromJson(JsonReader jsonReader) throws IOException reader.skipChildren(); } } - if (nameFound && keepWordsFound) { - KeepTokenFilter deserializedKeepTokenFilter = new KeepTokenFilter(name, keepWords); - deserializedKeepTokenFilter.odataType = odataType; - deserializedKeepTokenFilter.lowerCaseKeepWords = lowerCaseKeepWords; - return deserializedKeepTokenFilter; - } - List missingProperties = new ArrayList<>(); - if (!nameFound) { - missingProperties.add("name"); - } - if (!keepWordsFound) { - missingProperties.add("keepWords"); - } - throw new IllegalStateException( - "Missing required property/properties: " + String.join(", ", missingProperties)); + KeepTokenFilter deserializedKeepTokenFilter = new KeepTokenFilter(name, keepWords); + deserializedKeepTokenFilter.odataType = odataType; + deserializedKeepTokenFilter.lowerCaseKeepWords = lowerCaseKeepWords; + + return deserializedKeepTokenFilter; }); } } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/KeyPhraseExtractionSkill.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/KeyPhraseExtractionSkill.java similarity index 76% rename from sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/KeyPhraseExtractionSkill.java rename to sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/KeyPhraseExtractionSkill.java index 9036cc4f3862..fc6ce387a704 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/KeyPhraseExtractionSkill.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/KeyPhraseExtractionSkill.java @@ -1,17 +1,15 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) TypeSpec Code Generator. -package com.azure.search.documents.indexes.models; +package com.azure.search.documents.models; import com.azure.core.annotation.Fluent; +import com.azure.core.annotation.Generated; import com.azure.json.JsonReader; import com.azure.json.JsonToken; import com.azure.json.JsonWriter; import java.io.IOException; -import java.util.ArrayList; import java.util.List; /** @@ -20,24 +18,30 @@ @Fluent public final class KeyPhraseExtractionSkill extends SearchIndexerSkill { /* - * A URI fragment specifying the type of skill. + * The discriminator for derived types. */ + @Generated private String odataType = "#Microsoft.Skills.Text.KeyPhraseExtractionSkill"; /* * A value indicating which language code to use. Default is `en`. */ + @Generated private KeyPhraseExtractionSkillLanguage defaultLanguageCode; /* - * A number indicating how many key phrases to return. If absent, all identified key phrases will be returned. + * A number indicating how many key phrases to return. If absent, all identified + * key phrases will be returned. */ + @Generated private Integer maxKeyPhraseCount; /* - * 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. + * 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. */ + @Generated private String modelVersion; /** @@ -46,15 +50,17 @@ public final class KeyPhraseExtractionSkill extends SearchIndexerSkill { * @param inputs the inputs value to set. * @param outputs the outputs value to set. */ + @Generated public KeyPhraseExtractionSkill(List inputs, List outputs) { super(inputs, outputs); } /** - * Get the odataType property: A URI fragment specifying the type of skill. + * Get the odataType property: The discriminator for derived types. * * @return the odataType value. */ + @Generated @Override public String getOdataType() { return this.odataType; @@ -65,6 +71,7 @@ public String getOdataType() { * * @return the defaultLanguageCode value. */ + @Generated public KeyPhraseExtractionSkillLanguage getDefaultLanguageCode() { return this.defaultLanguageCode; } @@ -75,6 +82,7 @@ public KeyPhraseExtractionSkillLanguage getDefaultLanguageCode() { * @param defaultLanguageCode the defaultLanguageCode value to set. * @return the KeyPhraseExtractionSkill object itself. */ + @Generated public KeyPhraseExtractionSkill setDefaultLanguageCode(KeyPhraseExtractionSkillLanguage defaultLanguageCode) { this.defaultLanguageCode = defaultLanguageCode; return this; @@ -86,6 +94,7 @@ public KeyPhraseExtractionSkill setDefaultLanguageCode(KeyPhraseExtractionSkillL * * @return the maxKeyPhraseCount value. */ + @Generated public Integer getMaxKeyPhraseCount() { return this.maxKeyPhraseCount; } @@ -97,30 +106,33 @@ public Integer getMaxKeyPhraseCount() { * @param maxKeyPhraseCount the maxKeyPhraseCount value to set. * @return the KeyPhraseExtractionSkill object itself. */ + @Generated public KeyPhraseExtractionSkill setMaxKeyPhraseCount(Integer maxKeyPhraseCount) { this.maxKeyPhraseCount = maxKeyPhraseCount; return this; } /** - * Get the modelVersion property: 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. + * Get the modelVersion property: 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. * * @return the modelVersion value. */ + @Generated public String getModelVersion() { return this.modelVersion; } /** - * Set the modelVersion property: 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. + * Set the modelVersion property: 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. * * @param modelVersion the modelVersion value to set. * @return the KeyPhraseExtractionSkill object itself. */ + @Generated public KeyPhraseExtractionSkill setModelVersion(String modelVersion) { this.modelVersion = modelVersion; return this; @@ -129,6 +141,7 @@ public KeyPhraseExtractionSkill setModelVersion(String modelVersion) { /** * {@inheritDoc} */ + @Generated @Override public KeyPhraseExtractionSkill setName(String name) { super.setName(name); @@ -138,6 +151,7 @@ public KeyPhraseExtractionSkill setName(String name) { /** * {@inheritDoc} */ + @Generated @Override public KeyPhraseExtractionSkill setDescription(String description) { super.setDescription(description); @@ -147,6 +161,7 @@ public KeyPhraseExtractionSkill setDescription(String description) { /** * {@inheritDoc} */ + @Generated @Override public KeyPhraseExtractionSkill setContext(String context) { super.setContext(context); @@ -156,6 +171,7 @@ public KeyPhraseExtractionSkill setContext(String context) { /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); @@ -181,11 +197,10 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { * @throws IllegalStateException If the deserialized JSON object was missing any required properties. * @throws IOException If an error occurs while reading the KeyPhraseExtractionSkill. */ + @Generated public static KeyPhraseExtractionSkill fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { - boolean inputsFound = false; List inputs = null; - boolean outputsFound = false; List outputs = null; String name = null; String description = null; @@ -200,10 +215,8 @@ public static KeyPhraseExtractionSkill fromJson(JsonReader jsonReader) throws IO if ("inputs".equals(fieldName)) { inputs = reader.readArray(reader1 -> InputFieldMappingEntry.fromJson(reader1)); - inputsFound = true; } else if ("outputs".equals(fieldName)) { outputs = reader.readArray(reader1 -> OutputFieldMappingEntry.fromJson(reader1)); - outputsFound = true; } else if ("name".equals(fieldName)) { name = reader.getString(); } else if ("description".equals(fieldName)) { @@ -222,29 +235,17 @@ public static KeyPhraseExtractionSkill fromJson(JsonReader jsonReader) throws IO reader.skipChildren(); } } - if (inputsFound && outputsFound) { - KeyPhraseExtractionSkill deserializedKeyPhraseExtractionSkill - = new KeyPhraseExtractionSkill(inputs, outputs); - deserializedKeyPhraseExtractionSkill.setName(name); - deserializedKeyPhraseExtractionSkill.setDescription(description); - deserializedKeyPhraseExtractionSkill.setContext(context); - deserializedKeyPhraseExtractionSkill.odataType = odataType; - deserializedKeyPhraseExtractionSkill.defaultLanguageCode = defaultLanguageCode; - deserializedKeyPhraseExtractionSkill.maxKeyPhraseCount = maxKeyPhraseCount; - deserializedKeyPhraseExtractionSkill.modelVersion = modelVersion; - - return deserializedKeyPhraseExtractionSkill; - } - List missingProperties = new ArrayList<>(); - if (!inputsFound) { - missingProperties.add("inputs"); - } - if (!outputsFound) { - missingProperties.add("outputs"); - } - - throw new IllegalStateException( - "Missing required property/properties: " + String.join(", ", missingProperties)); + KeyPhraseExtractionSkill deserializedKeyPhraseExtractionSkill + = new KeyPhraseExtractionSkill(inputs, outputs); + deserializedKeyPhraseExtractionSkill.setName(name); + deserializedKeyPhraseExtractionSkill.setDescription(description); + deserializedKeyPhraseExtractionSkill.setContext(context); + deserializedKeyPhraseExtractionSkill.odataType = odataType; + deserializedKeyPhraseExtractionSkill.defaultLanguageCode = defaultLanguageCode; + deserializedKeyPhraseExtractionSkill.maxKeyPhraseCount = maxKeyPhraseCount; + deserializedKeyPhraseExtractionSkill.modelVersion = modelVersion; + + return deserializedKeyPhraseExtractionSkill; }); } } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/KeyPhraseExtractionSkillLanguage.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/KeyPhraseExtractionSkillLanguage.java similarity index 87% rename from sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/KeyPhraseExtractionSkillLanguage.java rename to sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/KeyPhraseExtractionSkillLanguage.java index 77db10b4e55c..5d10c3e034ba 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/KeyPhraseExtractionSkillLanguage.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/KeyPhraseExtractionSkillLanguage.java @@ -1,11 +1,10 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) TypeSpec Code Generator. -package com.azure.search.documents.indexes.models; +package com.azure.search.documents.models; +import com.azure.core.annotation.Generated; import com.azure.core.util.ExpandableStringEnum; import java.util.Collection; @@ -16,81 +15,97 @@ public final class KeyPhraseExtractionSkillLanguage extends ExpandableStringEnum /** * Danish. */ + @Generated public static final KeyPhraseExtractionSkillLanguage DA = fromString("da"); /** * Dutch. */ + @Generated public static final KeyPhraseExtractionSkillLanguage NL = fromString("nl"); /** * English. */ + @Generated public static final KeyPhraseExtractionSkillLanguage EN = fromString("en"); /** * Finnish. */ + @Generated public static final KeyPhraseExtractionSkillLanguage FI = fromString("fi"); /** * French. */ + @Generated public static final KeyPhraseExtractionSkillLanguage FR = fromString("fr"); /** * German. */ + @Generated public static final KeyPhraseExtractionSkillLanguage DE = fromString("de"); /** * Italian. */ + @Generated public static final KeyPhraseExtractionSkillLanguage IT = fromString("it"); /** * Japanese. */ + @Generated public static final KeyPhraseExtractionSkillLanguage JA = fromString("ja"); /** * Korean. */ + @Generated public static final KeyPhraseExtractionSkillLanguage KO = fromString("ko"); /** * Norwegian (Bokmaal). */ + @Generated public static final KeyPhraseExtractionSkillLanguage NO = fromString("no"); /** * Polish. */ + @Generated public static final KeyPhraseExtractionSkillLanguage PL = fromString("pl"); /** * Portuguese (Portugal). */ + @Generated public static final KeyPhraseExtractionSkillLanguage PT_PT = fromString("pt-PT"); /** * Portuguese (Brazil). */ + @Generated public static final KeyPhraseExtractionSkillLanguage PT_BR = fromString("pt-BR"); /** * Russian. */ + @Generated public static final KeyPhraseExtractionSkillLanguage RU = fromString("ru"); /** * Spanish. */ + @Generated public static final KeyPhraseExtractionSkillLanguage ES = fromString("es"); /** * Swedish. */ + @Generated public static final KeyPhraseExtractionSkillLanguage SV = fromString("sv"); /** @@ -98,6 +113,7 @@ public final class KeyPhraseExtractionSkillLanguage extends ExpandableStringEnum * * @deprecated Use the {@link #fromString(String)} factory method. */ + @Generated @Deprecated public KeyPhraseExtractionSkillLanguage() { } @@ -108,6 +124,7 @@ public KeyPhraseExtractionSkillLanguage() { * @param name a name to look for. * @return the corresponding KeyPhraseExtractionSkillLanguage. */ + @Generated public static KeyPhraseExtractionSkillLanguage fromString(String name) { return fromString(name, KeyPhraseExtractionSkillLanguage.class); } @@ -117,6 +134,7 @@ public static KeyPhraseExtractionSkillLanguage fromString(String name) { * * @return known KeyPhraseExtractionSkillLanguage values. */ + @Generated public static Collection values() { return values(KeyPhraseExtractionSkillLanguage.class); } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/KeywordMarkerTokenFilter.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/KeywordMarkerTokenFilter.java similarity index 62% rename from sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/KeywordMarkerTokenFilter.java rename to sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/KeywordMarkerTokenFilter.java index 2ee8cd3517f7..0317bcae16b2 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/KeywordMarkerTokenFilter.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/KeywordMarkerTokenFilter.java @@ -1,17 +1,15 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) TypeSpec Code Generator. -package com.azure.search.documents.indexes.models; +package com.azure.search.documents.models; import com.azure.core.annotation.Fluent; +import com.azure.core.annotation.Generated; import com.azure.json.JsonReader; import com.azure.json.JsonToken; import com.azure.json.JsonWriter; import java.io.IOException; -import java.util.ArrayList; import java.util.List; /** @@ -20,20 +18,23 @@ @Fluent public final class KeywordMarkerTokenFilter extends TokenFilter { /* - * A URI fragment specifying the type of token filter. + * The discriminator for derived types. */ + @Generated private String odataType = "#Microsoft.Azure.Search.KeywordMarkerTokenFilter"; /* * A list of words to mark as keywords. */ + @Generated private final List keywords; /* - * A value indicating whether to ignore case. If true, all words are converted to lower case first. Default is - * false. + * A value indicating whether to ignore case. If true, all words are converted to + * lower case first. Default is false. */ - private Boolean caseIgnored; + @Generated + private Boolean ignoreCase; /** * Creates an instance of KeywordMarkerTokenFilter class. @@ -41,16 +42,18 @@ public final class KeywordMarkerTokenFilter extends TokenFilter { * @param name the name value to set. * @param keywords the keywords value to set. */ + @Generated public KeywordMarkerTokenFilter(String name, List keywords) { super(name); this.keywords = keywords; } /** - * Get the odataType property: A URI fragment specifying the type of token filter. + * Get the odataType property: The discriminator for derived types. * * @return the odataType value. */ + @Generated @Override public String getOdataType() { return this.odataType; @@ -61,42 +64,46 @@ public String getOdataType() { * * @return the keywords value. */ + @Generated public List getKeywords() { return this.keywords; } /** - * Get the caseIgnored property: A value indicating whether to ignore case. If true, all words are converted to + * Get the ignoreCase property: A value indicating whether to ignore case. If true, all words are converted to * lower case first. Default is false. * - * @return the caseIgnored value. + * @return the ignoreCase value. */ - public Boolean isCaseIgnored() { - return this.caseIgnored; + @Generated + public Boolean isIgnoreCase() { + return this.ignoreCase; } /** - * Set the caseIgnored property: A value indicating whether to ignore case. If true, all words are converted to + * Set the ignoreCase property: A value indicating whether to ignore case. If true, all words are converted to * lower case first. Default is false. * - * @param caseIgnored the caseIgnored value to set. + * @param ignoreCase the ignoreCase value to set. * @return the KeywordMarkerTokenFilter object itself. */ - public KeywordMarkerTokenFilter setCaseIgnored(Boolean caseIgnored) { - this.caseIgnored = caseIgnored; + @Generated + public KeywordMarkerTokenFilter setIgnoreCase(Boolean ignoreCase) { + this.ignoreCase = ignoreCase; return this; } /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); jsonWriter.writeStringField("name", getName()); jsonWriter.writeArrayField("keywords", this.keywords, (writer, element) -> writer.writeString(element)); jsonWriter.writeStringField("@odata.type", this.odataType); - jsonWriter.writeBooleanField("ignoreCase", this.caseIgnored); + jsonWriter.writeBooleanField("ignoreCase", this.ignoreCase); return jsonWriter.writeEndObject(); } @@ -109,50 +116,35 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { * @throws IllegalStateException If the deserialized JSON object was missing any required properties. * @throws IOException If an error occurs while reading the KeywordMarkerTokenFilter. */ + @Generated public static KeywordMarkerTokenFilter fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { - boolean nameFound = false; String name = null; - boolean keywordsFound = false; List keywords = null; String odataType = "#Microsoft.Azure.Search.KeywordMarkerTokenFilter"; - Boolean caseIgnored = null; + Boolean ignoreCase = null; while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); if ("name".equals(fieldName)) { name = reader.getString(); - nameFound = true; } else if ("keywords".equals(fieldName)) { keywords = reader.readArray(reader1 -> reader1.getString()); - keywordsFound = true; } else if ("@odata.type".equals(fieldName)) { odataType = reader.getString(); } else if ("ignoreCase".equals(fieldName)) { - caseIgnored = reader.getNullable(JsonReader::getBoolean); + ignoreCase = reader.getNullable(JsonReader::getBoolean); } else { reader.skipChildren(); } } - if (nameFound && keywordsFound) { - KeywordMarkerTokenFilter deserializedKeywordMarkerTokenFilter - = new KeywordMarkerTokenFilter(name, keywords); - deserializedKeywordMarkerTokenFilter.odataType = odataType; - deserializedKeywordMarkerTokenFilter.caseIgnored = caseIgnored; - - return deserializedKeywordMarkerTokenFilter; - } - List missingProperties = new ArrayList<>(); - if (!nameFound) { - missingProperties.add("name"); - } - if (!keywordsFound) { - missingProperties.add("keywords"); - } + KeywordMarkerTokenFilter deserializedKeywordMarkerTokenFilter + = new KeywordMarkerTokenFilter(name, keywords); + deserializedKeywordMarkerTokenFilter.odataType = odataType; + deserializedKeywordMarkerTokenFilter.ignoreCase = ignoreCase; - throw new IllegalStateException( - "Missing required property/properties: " + String.join(", ", missingProperties)); + return deserializedKeywordMarkerTokenFilter; }); } } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/implementation/models/KeywordTokenizerV2.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/KeywordTokenizerV2.java similarity index 77% rename from sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/implementation/models/KeywordTokenizerV2.java rename to sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/KeywordTokenizerV2.java index b12557c6f984..574cc1a8c893 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/implementation/models/KeywordTokenizerV2.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/KeywordTokenizerV2.java @@ -1,32 +1,33 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) TypeSpec Code Generator. -package com.azure.search.documents.indexes.implementation.models; +package com.azure.search.documents.models; import com.azure.core.annotation.Fluent; +import com.azure.core.annotation.Generated; import com.azure.json.JsonReader; import com.azure.json.JsonToken; import com.azure.json.JsonWriter; -import com.azure.search.documents.indexes.models.LexicalTokenizer; import java.io.IOException; /** - * Emits the entire input as a single token. This tokenizer is implemented using Apache Lucene. + * Emits the entire input as a single token. This tokenizer is implemented using + * Apache Lucene. */ @Fluent public final class KeywordTokenizerV2 extends LexicalTokenizer { /* - * A URI fragment specifying the type of tokenizer. + * The discriminator for derived types. */ + @Generated private String odataType = "#Microsoft.Azure.Search.KeywordTokenizerV2"; /* - * 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. + * 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. */ + @Generated private Integer maxTokenLength; /** @@ -34,15 +35,17 @@ public final class KeywordTokenizerV2 extends LexicalTokenizer { * * @param name the name value to set. */ + @Generated public KeywordTokenizerV2(String name) { super(name); } /** - * Get the odataType property: A URI fragment specifying the type of tokenizer. + * Get the odataType property: The discriminator for derived types. * * @return the odataType value. */ + @Generated @Override public String getOdataType() { return this.odataType; @@ -54,6 +57,7 @@ public String getOdataType() { * * @return the maxTokenLength value. */ + @Generated public Integer getMaxTokenLength() { return this.maxTokenLength; } @@ -65,6 +69,7 @@ public Integer getMaxTokenLength() { * @param maxTokenLength the maxTokenLength value to set. * @return the KeywordTokenizerV2 object itself. */ + @Generated public KeywordTokenizerV2 setMaxTokenLength(Integer maxTokenLength) { this.maxTokenLength = maxTokenLength; return this; @@ -73,6 +78,7 @@ public KeywordTokenizerV2 setMaxTokenLength(Integer maxTokenLength) { /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); @@ -91,9 +97,9 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { * @throws IllegalStateException If the deserialized JSON object was missing any required properties. * @throws IOException If an error occurs while reading the KeywordTokenizerV2. */ + @Generated public static KeywordTokenizerV2 fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { - boolean nameFound = false; String name = null; String odataType = "#Microsoft.Azure.Search.KeywordTokenizerV2"; Integer maxTokenLength = null; @@ -103,7 +109,6 @@ public static KeywordTokenizerV2 fromJson(JsonReader jsonReader) throws IOExcept if ("name".equals(fieldName)) { name = reader.getString(); - nameFound = true; } else if ("@odata.type".equals(fieldName)) { odataType = reader.getString(); } else if ("maxTokenLength".equals(fieldName)) { @@ -112,14 +117,11 @@ public static KeywordTokenizerV2 fromJson(JsonReader jsonReader) throws IOExcept reader.skipChildren(); } } - if (nameFound) { - KeywordTokenizerV2 deserializedKeywordTokenizerV2 = new KeywordTokenizerV2(name); - deserializedKeywordTokenizerV2.odataType = odataType; - deserializedKeywordTokenizerV2.maxTokenLength = maxTokenLength; + KeywordTokenizerV2 deserializedKeywordTokenizerV2 = new KeywordTokenizerV2(name); + deserializedKeywordTokenizerV2.odataType = odataType; + deserializedKeywordTokenizerV2.maxTokenLength = maxTokenLength; - return deserializedKeywordTokenizerV2; - } - throw new IllegalStateException("Missing required property: name"); + return deserializedKeywordTokenizerV2; }); } } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/LanguageDetectionSkill.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/LanguageDetectionSkill.java similarity index 72% rename from sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/LanguageDetectionSkill.java rename to sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/LanguageDetectionSkill.java index ddfc7554d2e5..c084873562e8 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/LanguageDetectionSkill.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/LanguageDetectionSkill.java @@ -1,39 +1,43 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) TypeSpec Code Generator. -package com.azure.search.documents.indexes.models; +package com.azure.search.documents.models; import com.azure.core.annotation.Fluent; +import com.azure.core.annotation.Generated; import com.azure.json.JsonReader; import com.azure.json.JsonToken; import com.azure.json.JsonWriter; import java.io.IOException; -import java.util.ArrayList; import java.util.List; /** - * 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. + * 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. */ @Fluent public final class LanguageDetectionSkill extends SearchIndexerSkill { /* - * A URI fragment specifying the type of skill. + * The discriminator for derived types. */ + @Generated private String odataType = "#Microsoft.Skills.Text.LanguageDetectionSkill"; /* - * A country code to use as a hint to the language detection model if it cannot disambiguate the language. + * A country code to use as a hint to the language detection model if it cannot + * disambiguate the language. */ + @Generated private String defaultCountryHint; /* - * 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. + * 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. */ + @Generated private String modelVersion; /** @@ -42,15 +46,17 @@ public final class LanguageDetectionSkill extends SearchIndexerSkill { * @param inputs the inputs value to set. * @param outputs the outputs value to set. */ + @Generated public LanguageDetectionSkill(List inputs, List outputs) { super(inputs, outputs); } /** - * Get the odataType property: A URI fragment specifying the type of skill. + * Get the odataType property: The discriminator for derived types. * * @return the odataType value. */ + @Generated @Override public String getOdataType() { return this.odataType; @@ -62,6 +68,7 @@ public String getOdataType() { * * @return the defaultCountryHint value. */ + @Generated public String getDefaultCountryHint() { return this.defaultCountryHint; } @@ -73,30 +80,33 @@ public String getDefaultCountryHint() { * @param defaultCountryHint the defaultCountryHint value to set. * @return the LanguageDetectionSkill object itself. */ + @Generated public LanguageDetectionSkill setDefaultCountryHint(String defaultCountryHint) { this.defaultCountryHint = defaultCountryHint; return this; } /** - * Get the modelVersion property: 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. + * Get the modelVersion property: 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. * * @return the modelVersion value. */ + @Generated public String getModelVersion() { return this.modelVersion; } /** - * Set the modelVersion property: 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. + * Set the modelVersion property: 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. * * @param modelVersion the modelVersion value to set. * @return the LanguageDetectionSkill object itself. */ + @Generated public LanguageDetectionSkill setModelVersion(String modelVersion) { this.modelVersion = modelVersion; return this; @@ -105,6 +115,7 @@ public LanguageDetectionSkill setModelVersion(String modelVersion) { /** * {@inheritDoc} */ + @Generated @Override public LanguageDetectionSkill setName(String name) { super.setName(name); @@ -114,6 +125,7 @@ public LanguageDetectionSkill setName(String name) { /** * {@inheritDoc} */ + @Generated @Override public LanguageDetectionSkill setDescription(String description) { super.setDescription(description); @@ -123,6 +135,7 @@ public LanguageDetectionSkill setDescription(String description) { /** * {@inheritDoc} */ + @Generated @Override public LanguageDetectionSkill setContext(String context) { super.setContext(context); @@ -132,6 +145,7 @@ public LanguageDetectionSkill setContext(String context) { /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); @@ -155,11 +169,10 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { * @throws IllegalStateException If the deserialized JSON object was missing any required properties. * @throws IOException If an error occurs while reading the LanguageDetectionSkill. */ + @Generated public static LanguageDetectionSkill fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { - boolean inputsFound = false; List inputs = null; - boolean outputsFound = false; List outputs = null; String name = null; String description = null; @@ -173,10 +186,8 @@ public static LanguageDetectionSkill fromJson(JsonReader jsonReader) throws IOEx if ("inputs".equals(fieldName)) { inputs = reader.readArray(reader1 -> InputFieldMappingEntry.fromJson(reader1)); - inputsFound = true; } else if ("outputs".equals(fieldName)) { outputs = reader.readArray(reader1 -> OutputFieldMappingEntry.fromJson(reader1)); - outputsFound = true; } else if ("name".equals(fieldName)) { name = reader.getString(); } else if ("description".equals(fieldName)) { @@ -193,27 +204,15 @@ public static LanguageDetectionSkill fromJson(JsonReader jsonReader) throws IOEx reader.skipChildren(); } } - if (inputsFound && outputsFound) { - LanguageDetectionSkill deserializedLanguageDetectionSkill = new LanguageDetectionSkill(inputs, outputs); - deserializedLanguageDetectionSkill.setName(name); - deserializedLanguageDetectionSkill.setDescription(description); - deserializedLanguageDetectionSkill.setContext(context); - deserializedLanguageDetectionSkill.odataType = odataType; - deserializedLanguageDetectionSkill.defaultCountryHint = defaultCountryHint; - deserializedLanguageDetectionSkill.modelVersion = modelVersion; - - return deserializedLanguageDetectionSkill; - } - List missingProperties = new ArrayList<>(); - if (!inputsFound) { - missingProperties.add("inputs"); - } - if (!outputsFound) { - missingProperties.add("outputs"); - } - - throw new IllegalStateException( - "Missing required property/properties: " + String.join(", ", missingProperties)); + LanguageDetectionSkill deserializedLanguageDetectionSkill = new LanguageDetectionSkill(inputs, outputs); + deserializedLanguageDetectionSkill.setName(name); + deserializedLanguageDetectionSkill.setDescription(description); + deserializedLanguageDetectionSkill.setContext(context); + deserializedLanguageDetectionSkill.odataType = odataType; + deserializedLanguageDetectionSkill.defaultCountryHint = defaultCountryHint; + deserializedLanguageDetectionSkill.modelVersion = modelVersion; + + return deserializedLanguageDetectionSkill; }); } } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/LengthTokenFilter.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/LengthTokenFilter.java similarity index 78% rename from sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/LengthTokenFilter.java rename to sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/LengthTokenFilter.java index e43cb81bb8f7..c77da8d81437 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/LengthTokenFilter.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/LengthTokenFilter.java @@ -1,35 +1,39 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) TypeSpec Code Generator. -package com.azure.search.documents.indexes.models; +package com.azure.search.documents.models; import com.azure.core.annotation.Fluent; +import com.azure.core.annotation.Generated; import com.azure.json.JsonReader; import com.azure.json.JsonToken; import com.azure.json.JsonWriter; import java.io.IOException; /** - * Removes words that are too long or too short. This token filter is implemented using Apache Lucene. + * Removes words that are too long or too short. This token filter is implemented + * using Apache Lucene. */ @Fluent public final class LengthTokenFilter extends TokenFilter { /* - * A URI fragment specifying the type of token filter. + * The discriminator for derived types. */ + @Generated private String odataType = "#Microsoft.Azure.Search.LengthTokenFilter"; /* - * The minimum length in characters. Default is 0. Maximum is 300. Must be less than the value of max. + * The minimum length in characters. Default is 0. Maximum is 300. Must be less + * than the value of max. */ + @Generated private Integer minLength; /* * The maximum length in characters. Default and maximum is 300. */ + @Generated private Integer maxLength; /** @@ -37,37 +41,41 @@ public final class LengthTokenFilter extends TokenFilter { * * @param name the name value to set. */ + @Generated public LengthTokenFilter(String name) { super(name); } /** - * Get the odataType property: A URI fragment specifying the type of token filter. + * Get the odataType property: The discriminator for derived types. * * @return the odataType value. */ + @Generated @Override public String getOdataType() { return this.odataType; } /** - * Get the minLength property: The minimum length in characters. Default is 0. Maximum is 300. Must be less than the - * value of max. + * Get the minLength property: The minimum length in characters. Default is 0. Maximum is 300. Must be less + * than the value of max. * * @return the minLength value. */ + @Generated public Integer getMinLength() { return this.minLength; } /** - * Set the minLength property: The minimum length in characters. Default is 0. Maximum is 300. Must be less than the - * value of max. + * Set the minLength property: The minimum length in characters. Default is 0. Maximum is 300. Must be less + * than the value of max. * * @param minLength the minLength value to set. * @return the LengthTokenFilter object itself. */ + @Generated public LengthTokenFilter setMinLength(Integer minLength) { this.minLength = minLength; return this; @@ -78,6 +86,7 @@ public LengthTokenFilter setMinLength(Integer minLength) { * * @return the maxLength value. */ + @Generated public Integer getMaxLength() { return this.maxLength; } @@ -88,6 +97,7 @@ public Integer getMaxLength() { * @param maxLength the maxLength value to set. * @return the LengthTokenFilter object itself. */ + @Generated public LengthTokenFilter setMaxLength(Integer maxLength) { this.maxLength = maxLength; return this; @@ -96,6 +106,7 @@ public LengthTokenFilter setMaxLength(Integer maxLength) { /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); @@ -115,9 +126,9 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { * @throws IllegalStateException If the deserialized JSON object was missing any required properties. * @throws IOException If an error occurs while reading the LengthTokenFilter. */ + @Generated public static LengthTokenFilter fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { - boolean nameFound = false; String name = null; String odataType = "#Microsoft.Azure.Search.LengthTokenFilter"; Integer minLength = null; @@ -128,7 +139,6 @@ public static LengthTokenFilter fromJson(JsonReader jsonReader) throws IOExcepti if ("name".equals(fieldName)) { name = reader.getString(); - nameFound = true; } else if ("@odata.type".equals(fieldName)) { odataType = reader.getString(); } else if ("min".equals(fieldName)) { @@ -139,15 +149,12 @@ public static LengthTokenFilter fromJson(JsonReader jsonReader) throws IOExcepti reader.skipChildren(); } } - if (nameFound) { - LengthTokenFilter deserializedLengthTokenFilter = new LengthTokenFilter(name); - deserializedLengthTokenFilter.odataType = odataType; - deserializedLengthTokenFilter.minLength = minLength; - deserializedLengthTokenFilter.maxLength = maxLength; + LengthTokenFilter deserializedLengthTokenFilter = new LengthTokenFilter(name); + deserializedLengthTokenFilter.odataType = odataType; + deserializedLengthTokenFilter.minLength = minLength; + deserializedLengthTokenFilter.maxLength = maxLength; - return deserializedLengthTokenFilter; - } - throw new IllegalStateException("Missing required property: name"); + return deserializedLengthTokenFilter; }); } } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/LexicalAnalyzer.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/LexicalAnalyzer.java similarity index 80% rename from sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/LexicalAnalyzer.java rename to sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/LexicalAnalyzer.java index 14414881850c..4c2b9d2d98eb 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/LexicalAnalyzer.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/LexicalAnalyzer.java @@ -1,11 +1,10 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) TypeSpec Code Generator. -package com.azure.search.documents.indexes.models; +package com.azure.search.documents.models; +import com.azure.core.annotation.Generated; import com.azure.core.annotation.Immutable; import com.azure.json.JsonReader; import com.azure.json.JsonSerializable; @@ -19,14 +18,17 @@ @Immutable public class LexicalAnalyzer implements JsonSerializable { /* - * A URI fragment specifying the type of analyzer. + * The discriminator for derived types. */ + @Generated private String odataType = "LexicalAnalyzer"; /* - * 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. + * 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. */ + @Generated private final String name; /** @@ -34,25 +36,29 @@ public class LexicalAnalyzer implements JsonSerializable { * * @param name the name value to set. */ + @Generated public LexicalAnalyzer(String name) { this.name = name; } /** - * Get the odataType property: A URI fragment specifying the type of analyzer. + * Get the odataType property: The discriminator for derived types. * * @return the odataType value. */ + @Generated public String getOdataType() { return this.odataType; } /** - * Get the name property: 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. + * Get the name property: 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. * * @return the name value. */ + @Generated public String getName() { return this.name; } @@ -60,6 +66,7 @@ public String getName() { /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); @@ -77,6 +84,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { * @throws IllegalStateException If the deserialized JSON object was missing any required properties. * @throws IOException If an error occurs while reading the LexicalAnalyzer. */ + @Generated public static LexicalAnalyzer fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { String discriminatorValue = null; @@ -108,9 +116,9 @@ public static LexicalAnalyzer fromJson(JsonReader jsonReader) throws IOException }); } + @Generated static LexicalAnalyzer fromJsonKnownDiscriminator(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { - boolean nameFound = false; String name = null; String odataType = null; while (reader.nextToken() != JsonToken.END_OBJECT) { @@ -119,20 +127,16 @@ static LexicalAnalyzer fromJsonKnownDiscriminator(JsonReader jsonReader) throws if ("name".equals(fieldName)) { name = reader.getString(); - nameFound = true; } else if ("@odata.type".equals(fieldName)) { odataType = reader.getString(); } else { reader.skipChildren(); } } - if (nameFound) { - LexicalAnalyzer deserializedLexicalAnalyzer = new LexicalAnalyzer(name); - deserializedLexicalAnalyzer.odataType = odataType; + LexicalAnalyzer deserializedLexicalAnalyzer = new LexicalAnalyzer(name); + deserializedLexicalAnalyzer.odataType = odataType; - return deserializedLexicalAnalyzer; - } - throw new IllegalStateException("Missing required property: name"); + return deserializedLexicalAnalyzer; }); } } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/LexicalAnalyzerName.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/LexicalAnalyzerName.java similarity index 89% rename from sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/LexicalAnalyzerName.java rename to sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/LexicalAnalyzerName.java index 468892e83eb5..d9d3b4b281e1 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/LexicalAnalyzerName.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/LexicalAnalyzerName.java @@ -1,11 +1,10 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) TypeSpec Code Generator. -package com.azure.search.documents.indexes.models; +package com.azure.search.documents.models; +import com.azure.core.annotation.Generated; import com.azure.core.util.ExpandableStringEnum; import java.util.Collection; @@ -16,473 +15,567 @@ public final class LexicalAnalyzerName extends ExpandableStringEnum values() { return values(LexicalAnalyzerName.class); } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/LexicalNormalizer.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/LexicalNormalizer.java similarity index 72% rename from sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/LexicalNormalizer.java rename to sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/LexicalNormalizer.java index 8689929abf06..ffeaef643ab7 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/LexicalNormalizer.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/LexicalNormalizer.java @@ -1,11 +1,10 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) TypeSpec Code Generator. -package com.azure.search.documents.indexes.models; +package com.azure.search.documents.models; +import com.azure.core.annotation.Generated; import com.azure.core.annotation.Immutable; import com.azure.json.JsonReader; import com.azure.json.JsonSerializable; @@ -19,15 +18,17 @@ @Immutable public class LexicalNormalizer implements JsonSerializable { /* - * A URI fragment specifying the type of normalizer. + * The discriminator for derived types. */ + @Generated private String odataType = "LexicalNormalizer"; /* - * 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'. + * 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. */ + @Generated private final String name; /** @@ -35,26 +36,29 @@ public class LexicalNormalizer implements JsonSerializable { * * @param name the name value to set. */ + @Generated public LexicalNormalizer(String name) { this.name = name; } /** - * Get the odataType property: A URI fragment specifying the type of normalizer. + * Get the odataType property: The discriminator for derived types. * * @return the odataType value. */ + @Generated public String getOdataType() { return this.odataType; } /** - * Get the name property: 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'. + * Get the name property: 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. * * @return the name value. */ + @Generated public String getName() { return this.name; } @@ -62,6 +66,7 @@ public String getName() { /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); @@ -79,6 +84,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { * @throws IllegalStateException If the deserialized JSON object was missing any required properties. * @throws IOException If an error occurs while reading the LexicalNormalizer. */ + @Generated public static LexicalNormalizer fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { String discriminatorValue = null; @@ -104,9 +110,9 @@ public static LexicalNormalizer fromJson(JsonReader jsonReader) throws IOExcepti }); } + @Generated static LexicalNormalizer fromJsonKnownDiscriminator(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { - boolean nameFound = false; String name = null; String odataType = null; while (reader.nextToken() != JsonToken.END_OBJECT) { @@ -115,20 +121,16 @@ static LexicalNormalizer fromJsonKnownDiscriminator(JsonReader jsonReader) throw if ("name".equals(fieldName)) { name = reader.getString(); - nameFound = true; } else if ("@odata.type".equals(fieldName)) { odataType = reader.getString(); } else { reader.skipChildren(); } } - if (nameFound) { - LexicalNormalizer deserializedLexicalNormalizer = new LexicalNormalizer(name); - deserializedLexicalNormalizer.odataType = odataType; + LexicalNormalizer deserializedLexicalNormalizer = new LexicalNormalizer(name); + deserializedLexicalNormalizer.odataType = odataType; - return deserializedLexicalNormalizer; - } - throw new IllegalStateException("Missing required property: name"); + return deserializedLexicalNormalizer; }); } } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/LexicalNormalizerName.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/LexicalNormalizerName.java similarity index 84% rename from sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/LexicalNormalizerName.java rename to sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/LexicalNormalizerName.java index f199df6d4e87..154a649b9281 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/LexicalNormalizerName.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/LexicalNormalizerName.java @@ -1,11 +1,10 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) TypeSpec Code Generator. -package com.azure.search.documents.indexes.models; +package com.azure.search.documents.models; +import com.azure.core.annotation.Generated; import com.azure.core.util.ExpandableStringEnum; import java.util.Collection; @@ -14,34 +13,41 @@ */ public final class LexicalNormalizerName extends ExpandableStringEnum { /** - * 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 + * 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. */ + @Generated public static final LexicalNormalizerName ASCII_FOLDING = fromString("asciifolding"); /** - * Removes elisions. For example, "l'avion" (the plane) will be converted to "avion" (plane). See + * 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. */ + @Generated public static final LexicalNormalizerName ELISION = fromString("elision"); /** * Normalizes token text to lowercase. See * https://lucene.apache.org/core/6_6_1/analyzers-common/org/apache/lucene/analysis/core/LowerCaseFilter.html. */ + @Generated public static final LexicalNormalizerName LOWERCASE = fromString("lowercase"); /** * 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. */ + @Generated public static final LexicalNormalizerName STANDARD = fromString("standard"); /** * Normalizes token text to uppercase. See * https://lucene.apache.org/core/6_6_1/analyzers-common/org/apache/lucene/analysis/core/UpperCaseFilter.html. */ + @Generated public static final LexicalNormalizerName UPPERCASE = fromString("uppercase"); /** @@ -49,6 +55,7 @@ public final class LexicalNormalizerName extends ExpandableStringEnum values() { return values(LexicalNormalizerName.class); } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/LexicalTokenizer.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/LexicalTokenizer.java similarity index 74% rename from sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/LexicalTokenizer.java rename to sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/LexicalTokenizer.java index 7eca644c2a23..86a3b70e1e3a 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/LexicalTokenizer.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/LexicalTokenizer.java @@ -1,20 +1,15 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) TypeSpec Code Generator. -package com.azure.search.documents.indexes.models; +package com.azure.search.documents.models; +import com.azure.core.annotation.Generated; import com.azure.core.annotation.Immutable; import com.azure.json.JsonReader; import com.azure.json.JsonSerializable; import com.azure.json.JsonToken; import com.azure.json.JsonWriter; -import com.azure.search.documents.indexes.implementation.models.KeywordTokenizerV1; -import com.azure.search.documents.indexes.implementation.models.KeywordTokenizerV2; -import com.azure.search.documents.indexes.implementation.models.LuceneStandardTokenizerV1; -import com.azure.search.documents.indexes.implementation.models.LuceneStandardTokenizerV2; import java.io.IOException; /** @@ -23,14 +18,17 @@ @Immutable public class LexicalTokenizer implements JsonSerializable { /* - * A URI fragment specifying the type of tokenizer. + * The discriminator for derived types. */ + @Generated private String odataType = "LexicalTokenizer"; /* - * 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. + * 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. */ + @Generated private final String name; /** @@ -38,25 +36,29 @@ public class LexicalTokenizer implements JsonSerializable { * * @param name the name value to set. */ + @Generated public LexicalTokenizer(String name) { this.name = name; } /** - * Get the odataType property: A URI fragment specifying the type of tokenizer. + * Get the odataType property: The discriminator for derived types. * * @return the odataType value. */ + @Generated public String getOdataType() { return this.odataType; } /** - * Get the name property: 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. + * Get the name property: 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. * * @return the name value. */ + @Generated public String getName() { return this.name; } @@ -64,6 +66,7 @@ public String getName() { /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); @@ -81,6 +84,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { * @throws IllegalStateException If the deserialized JSON object was missing any required properties. * @throws IOException If an error occurs while reading the LexicalTokenizer. */ + @Generated public static LexicalTokenizer fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { String discriminatorValue = null; @@ -109,18 +113,14 @@ public static LexicalTokenizer fromJson(JsonReader jsonReader) throws IOExceptio return MicrosoftLanguageStemmingTokenizer.fromJson(readerToUse.reset()); } else if ("#Microsoft.Azure.Search.NGramTokenizer".equals(discriminatorValue)) { return NGramTokenizer.fromJson(readerToUse.reset()); + } else if ("#Microsoft.Azure.Search.PathHierarchyTokenizerV2".equals(discriminatorValue)) { + return PathHierarchyTokenizerV2.fromJson(readerToUse.reset()); } else if ("#Microsoft.Azure.Search.PatternTokenizer".equals(discriminatorValue)) { return PatternTokenizer.fromJson(readerToUse.reset()); } else if ("#Microsoft.Azure.Search.StandardTokenizerV2".equals(discriminatorValue)) { return LuceneStandardTokenizerV2.fromJson(readerToUse.reset()); } else if ("#Microsoft.Azure.Search.UaxUrlEmailTokenizer".equals(discriminatorValue)) { return UaxUrlEmailTokenizer.fromJson(readerToUse.reset()); - } else if ("#Microsoft.Azure.Search.PathHierarchyTokenizerV2".equals(discriminatorValue)) { - return PathHierarchyTokenizer.fromJson(readerToUse.reset()); - } else if ("#Microsoft.Azure.Search.StandardTokenizer".equals(discriminatorValue)) { - return LuceneStandardTokenizerV1.fromJson(readerToUse.reset()); - } else if ("#Microsoft.Azure.Search.KeywordTokenizer".equals(discriminatorValue)) { - return KeywordTokenizerV1.fromJson(readerToUse.reset()); } else { return fromJsonKnownDiscriminator(readerToUse.reset()); } @@ -128,9 +128,9 @@ public static LexicalTokenizer fromJson(JsonReader jsonReader) throws IOExceptio }); } + @Generated static LexicalTokenizer fromJsonKnownDiscriminator(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { - boolean nameFound = false; String name = null; String odataType = null; while (reader.nextToken() != JsonToken.END_OBJECT) { @@ -139,20 +139,16 @@ static LexicalTokenizer fromJsonKnownDiscriminator(JsonReader jsonReader) throws if ("name".equals(fieldName)) { name = reader.getString(); - nameFound = true; } else if ("@odata.type".equals(fieldName)) { odataType = reader.getString(); } else { reader.skipChildren(); } } - if (nameFound) { - LexicalTokenizer deserializedLexicalTokenizer = new LexicalTokenizer(name); - deserializedLexicalTokenizer.odataType = odataType; + LexicalTokenizer deserializedLexicalTokenizer = new LexicalTokenizer(name); + deserializedLexicalTokenizer.odataType = odataType; - return deserializedLexicalTokenizer; - } - throw new IllegalStateException("Missing required property: name"); + return deserializedLexicalTokenizer; }); } } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/LexicalTokenizerName.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/LexicalTokenizerName.java similarity index 89% rename from sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/LexicalTokenizerName.java rename to sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/LexicalTokenizerName.java index 3ec9164420a8..297600fa7e36 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/LexicalTokenizerName.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/LexicalTokenizerName.java @@ -1,11 +1,10 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) TypeSpec Code Generator. -package com.azure.search.documents.indexes.models; +package com.azure.search.documents.models; +import com.azure.core.annotation.Generated; import com.azure.core.util.ExpandableStringEnum; import java.util.Collection; @@ -14,43 +13,52 @@ */ public final class LexicalTokenizerName extends ExpandableStringEnum { /** - * Grammar-based tokenizer that is suitable for processing most European-language documents. See + * 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. */ + @Generated public static final LexicalTokenizerName CLASSIC = fromString("classic"); /** * 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. */ + @Generated public static final LexicalTokenizerName EDGE_NGRAM = fromString("edgeNGram"); /** * 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. */ + @Generated public static final LexicalTokenizerName KEYWORD = fromString("keyword_v2"); /** * Divides text at non-letters. See * http://lucene.apache.org/core/4_10_3/analyzers-common/org/apache/lucene/analysis/core/LetterTokenizer.html. */ + @Generated public static final LexicalTokenizerName LETTER = fromString("letter"); /** * 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. */ + @Generated public static final LexicalTokenizerName LOWERCASE = fromString("lowercase"); /** * Divides text using language-specific rules. */ + @Generated public static final LexicalTokenizerName MICROSOFT_LANGUAGE_TOKENIZER = fromString("microsoft_language_tokenizer"); /** - * Divides text using language-specific rules and reduces words to their base forms. + * Divides text using language-specific rules and reduces words to their base + * forms. */ + @Generated public static final LexicalTokenizerName MICROSOFT_LANGUAGE_STEMMING_TOKENIZER = fromString("microsoft_language_stemming_tokenizer"); @@ -58,36 +66,43 @@ public final class LexicalTokenizerName extends ExpandableStringEnum values() { return values(LexicalTokenizerName.class); } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/LimitTokenFilter.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/LimitTokenFilter.java similarity index 66% rename from sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/LimitTokenFilter.java rename to sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/LimitTokenFilter.java index c5f5cea57a4c..1f15c94d69da 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/LimitTokenFilter.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/LimitTokenFilter.java @@ -1,52 +1,57 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. -package com.azure.search.documents.indexes.models; +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.search.documents.models; import com.azure.core.annotation.Fluent; +import com.azure.core.annotation.Generated; import com.azure.json.JsonReader; import com.azure.json.JsonToken; import com.azure.json.JsonWriter; import java.io.IOException; /** - * Limits the number of tokens while indexing. This token filter is implemented using Apache Lucene. + * Limits the number of tokens while indexing. This token filter is implemented + * using Apache Lucene. */ @Fluent public final class LimitTokenFilter extends TokenFilter { - /* - * A URI fragment specifying the type of token filter. + * The discriminator for derived types. */ + @Generated private String odataType = "#Microsoft.Azure.Search.LimitTokenFilter"; /* * The maximum number of tokens to produce. Default is 1. */ + @Generated private Integer maxTokenCount; /* - * A value indicating whether all tokens from the input must be consumed even if maxTokenCount is reached. Default - * is false. + * A value indicating whether all tokens from the input must be consumed even if + * maxTokenCount is reached. Default is false. */ - private Boolean allTokensConsumed; + @Generated + private Boolean consumeAllTokens; /** * Creates an instance of LimitTokenFilter class. - * + * * @param name the name value to set. */ + @Generated public LimitTokenFilter(String name) { super(name); } /** - * Get the odataType property: A URI fragment specifying the type of token filter. - * + * Get the odataType property: The discriminator for derived types. + * * @return the odataType value. */ + @Generated @Override public String getOdataType() { return this.odataType; @@ -54,99 +59,102 @@ public String getOdataType() { /** * Get the maxTokenCount property: The maximum number of tokens to produce. Default is 1. - * + * * @return the maxTokenCount value. */ + @Generated public Integer getMaxTokenCount() { return this.maxTokenCount; } /** * Set the maxTokenCount property: The maximum number of tokens to produce. Default is 1. - * + * * @param maxTokenCount the maxTokenCount value to set. * @return the LimitTokenFilter object itself. */ + @Generated public LimitTokenFilter setMaxTokenCount(Integer maxTokenCount) { this.maxTokenCount = maxTokenCount; return this; } /** - * Get the allTokensConsumed property: A value indicating whether all tokens from the input must be consumed even if + * Get the consumeAllTokens property: A value indicating whether all tokens from the input must be consumed even if * maxTokenCount is reached. Default is false. - * - * @return the allTokensConsumed value. + * + * @return the consumeAllTokens value. */ - public Boolean areAllTokensConsumed() { - return this.allTokensConsumed; + @Generated + public Boolean isConsumeAllTokens() { + return this.consumeAllTokens; } /** - * Set the allTokensConsumed property: A value indicating whether all tokens from the input must be consumed even if + * Set the consumeAllTokens property: A value indicating whether all tokens from the input must be consumed even if * maxTokenCount is reached. Default is false. - * - * @param allTokensConsumed the allTokensConsumed value to set. + * + * @param consumeAllTokens the consumeAllTokens value to set. * @return the LimitTokenFilter object itself. */ - public LimitTokenFilter setAllTokensConsumed(Boolean allTokensConsumed) { - this.allTokensConsumed = allTokensConsumed; + @Generated + public LimitTokenFilter setConsumeAllTokens(Boolean consumeAllTokens) { + this.consumeAllTokens = consumeAllTokens; return this; } /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); jsonWriter.writeStringField("name", getName()); jsonWriter.writeStringField("@odata.type", this.odataType); jsonWriter.writeNumberField("maxTokenCount", this.maxTokenCount); - jsonWriter.writeBooleanField("consumeAllTokens", this.allTokensConsumed); + jsonWriter.writeBooleanField("consumeAllTokens", this.consumeAllTokens); return jsonWriter.writeEndObject(); } /** * Reads an instance of LimitTokenFilter from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of LimitTokenFilter if the JsonReader was pointing to an instance of it, or null if it was * pointing to JSON null. * @throws IllegalStateException If the deserialized JSON object was missing any required properties. * @throws IOException If an error occurs while reading the LimitTokenFilter. */ + @Generated public static LimitTokenFilter fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { - boolean nameFound = false; String name = null; String odataType = "#Microsoft.Azure.Search.LimitTokenFilter"; Integer maxTokenCount = null; - Boolean allTokensConsumed = null; + Boolean consumeAllTokens = null; while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); + if ("name".equals(fieldName)) { name = reader.getString(); - nameFound = true; } else if ("@odata.type".equals(fieldName)) { odataType = reader.getString(); } else if ("maxTokenCount".equals(fieldName)) { maxTokenCount = reader.getNullable(JsonReader::getInt); } else if ("consumeAllTokens".equals(fieldName)) { - allTokensConsumed = reader.getNullable(JsonReader::getBoolean); + consumeAllTokens = reader.getNullable(JsonReader::getBoolean); } else { reader.skipChildren(); } } - if (nameFound) { - LimitTokenFilter deserializedLimitTokenFilter = new LimitTokenFilter(name); - deserializedLimitTokenFilter.odataType = odataType; - deserializedLimitTokenFilter.maxTokenCount = maxTokenCount; - deserializedLimitTokenFilter.allTokensConsumed = allTokensConsumed; - return deserializedLimitTokenFilter; - } - throw new IllegalStateException("Missing required property: name"); + LimitTokenFilter deserializedLimitTokenFilter = new LimitTokenFilter(name); + deserializedLimitTokenFilter.odataType = odataType; + deserializedLimitTokenFilter.maxTokenCount = maxTokenCount; + deserializedLimitTokenFilter.consumeAllTokens = consumeAllTokens; + + return deserializedLimitTokenFilter; }); } } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/implementation/models/ListDataSourcesResult.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/ListDataSourcesResult.java similarity index 68% rename from sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/implementation/models/ListDataSourcesResult.java rename to sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/ListDataSourcesResult.java index fb6d0891ab83..ab9896d91415 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/implementation/models/ListDataSourcesResult.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/ListDataSourcesResult.java @@ -1,36 +1,37 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) TypeSpec Code Generator. -package com.azure.search.documents.indexes.implementation.models; +package com.azure.search.documents.models; +import com.azure.core.annotation.Generated; import com.azure.core.annotation.Immutable; import com.azure.json.JsonReader; import com.azure.json.JsonSerializable; import com.azure.json.JsonToken; import com.azure.json.JsonWriter; -import com.azure.search.documents.indexes.models.SearchIndexerDataSourceConnection; import java.io.IOException; import java.util.List; /** - * Response from a List Datasources request. If successful, it includes the full definitions of all datasources. + * Response from a List Datasources request. If successful, it includes the full + * definitions of all datasources. */ @Immutable public final class ListDataSourcesResult implements JsonSerializable { /* * The datasources in the Search service. */ - private final List dataSources; + @Generated + private final List dataSources; /** * Creates an instance of ListDataSourcesResult class. * * @param dataSources the dataSources value to set. */ - public ListDataSourcesResult(List dataSources) { + @Generated + private ListDataSourcesResult(List dataSources) { this.dataSources = dataSources; } @@ -39,16 +40,19 @@ public ListDataSourcesResult(List dataSources * * @return the dataSources value. */ - public List getDataSources() { + @Generated + public List getDataSources() { return this.dataSources; } /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); + jsonWriter.writeArrayField("value", this.dataSources, (writer, element) -> writer.writeJson(element)); return jsonWriter.writeEndObject(); } @@ -61,25 +65,21 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { * @throws IllegalStateException If the deserialized JSON object was missing any required properties. * @throws IOException If an error occurs while reading the ListDataSourcesResult. */ + @Generated public static ListDataSourcesResult fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { - boolean dataSourcesFound = false; - List dataSources = null; + List dataSources = null; while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); if ("value".equals(fieldName)) { - dataSources = reader.readArray(reader1 -> SearchIndexerDataSourceConnection.fromJson(reader1)); - dataSourcesFound = true; + dataSources = reader.readArray(reader1 -> SearchIndexerDataSource.fromJson(reader1)); } else { reader.skipChildren(); } } - if (dataSourcesFound) { - return new ListDataSourcesResult(dataSources); - } - throw new IllegalStateException("Missing required property: value"); + return new ListDataSourcesResult(dataSources); }); } } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/implementation/models/ListIndexersResult.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/ListIndexersResult.java similarity index 77% rename from sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/implementation/models/ListIndexersResult.java rename to sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/ListIndexersResult.java index bc40469d78d8..93cbdde8b482 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/implementation/models/ListIndexersResult.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/ListIndexersResult.java @@ -1,28 +1,28 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) TypeSpec Code Generator. -package com.azure.search.documents.indexes.implementation.models; +package com.azure.search.documents.models; +import com.azure.core.annotation.Generated; import com.azure.core.annotation.Immutable; import com.azure.json.JsonReader; import com.azure.json.JsonSerializable; import com.azure.json.JsonToken; import com.azure.json.JsonWriter; -import com.azure.search.documents.indexes.models.SearchIndexer; import java.io.IOException; import java.util.List; /** - * Response from a List Indexers request. If successful, it includes the full definitions of all indexers. + * Response from a List Indexers request. If successful, it includes the full + * definitions of all indexers. */ @Immutable public final class ListIndexersResult implements JsonSerializable { /* * The indexers in the Search service. */ + @Generated private final List indexers; /** @@ -30,7 +30,8 @@ public final class ListIndexersResult implements JsonSerializable indexers) { + @Generated + private ListIndexersResult(List indexers) { this.indexers = indexers; } @@ -39,6 +40,7 @@ public ListIndexersResult(List indexers) { * * @return the indexers value. */ + @Generated public List getIndexers() { return this.indexers; } @@ -46,9 +48,11 @@ public List getIndexers() { /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); + jsonWriter.writeArrayField("value", this.indexers, (writer, element) -> writer.writeJson(element)); return jsonWriter.writeEndObject(); } @@ -61,9 +65,9 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { * @throws IllegalStateException If the deserialized JSON object was missing any required properties. * @throws IOException If an error occurs while reading the ListIndexersResult. */ + @Generated public static ListIndexersResult fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { - boolean indexersFound = false; List indexers = null; while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); @@ -71,15 +75,11 @@ public static ListIndexersResult fromJson(JsonReader jsonReader) throws IOExcept if ("value".equals(fieldName)) { indexers = reader.readArray(reader1 -> SearchIndexer.fromJson(reader1)); - indexersFound = true; } else { reader.skipChildren(); } } - if (indexersFound) { - return new ListIndexersResult(indexers); - } - throw new IllegalStateException("Missing required property: value"); + return new ListIndexersResult(indexers); }); } } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/implementation/models/ListSkillsetsResult.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/ListSkillsetsResult.java similarity index 77% rename from sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/implementation/models/ListSkillsetsResult.java rename to sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/ListSkillsetsResult.java index 144ad28a9ca5..db15a3f4ffbb 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/implementation/models/ListSkillsetsResult.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/ListSkillsetsResult.java @@ -1,28 +1,28 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) TypeSpec Code Generator. -package com.azure.search.documents.indexes.implementation.models; +package com.azure.search.documents.models; +import com.azure.core.annotation.Generated; import com.azure.core.annotation.Immutable; import com.azure.json.JsonReader; import com.azure.json.JsonSerializable; import com.azure.json.JsonToken; import com.azure.json.JsonWriter; -import com.azure.search.documents.indexes.models.SearchIndexerSkillset; import java.io.IOException; import java.util.List; /** - * Response from a list skillset request. If successful, it includes the full definitions of all skillsets. + * Response from a list skillset request. If successful, it includes the full + * definitions of all skillsets. */ @Immutable public final class ListSkillsetsResult implements JsonSerializable { /* * The skillsets defined in the Search service. */ + @Generated private final List skillsets; /** @@ -30,7 +30,8 @@ public final class ListSkillsetsResult implements JsonSerializable skillsets) { + @Generated + private ListSkillsetsResult(List skillsets) { this.skillsets = skillsets; } @@ -39,6 +40,7 @@ public ListSkillsetsResult(List skillsets) { * * @return the skillsets value. */ + @Generated public List getSkillsets() { return this.skillsets; } @@ -46,9 +48,11 @@ public List getSkillsets() { /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); + jsonWriter.writeArrayField("value", this.skillsets, (writer, element) -> writer.writeJson(element)); return jsonWriter.writeEndObject(); } @@ -61,9 +65,9 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { * @throws IllegalStateException If the deserialized JSON object was missing any required properties. * @throws IOException If an error occurs while reading the ListSkillsetsResult. */ + @Generated public static ListSkillsetsResult fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { - boolean skillsetsFound = false; List skillsets = null; while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); @@ -71,15 +75,11 @@ public static ListSkillsetsResult fromJson(JsonReader jsonReader) throws IOExcep if ("value".equals(fieldName)) { skillsets = reader.readArray(reader1 -> SearchIndexerSkillset.fromJson(reader1)); - skillsetsFound = true; } else { reader.skipChildren(); } } - if (skillsetsFound) { - return new ListSkillsetsResult(skillsets); - } - throw new IllegalStateException("Missing required property: value"); + return new ListSkillsetsResult(skillsets); }); } } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/implementation/models/ListSynonymMapsResult.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/ListSynonymMapsResult.java similarity index 77% rename from sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/implementation/models/ListSynonymMapsResult.java rename to sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/ListSynonymMapsResult.java index 79d18ad94f36..49a6c15d5cc3 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/implementation/models/ListSynonymMapsResult.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/ListSynonymMapsResult.java @@ -1,28 +1,28 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) TypeSpec Code Generator. -package com.azure.search.documents.indexes.implementation.models; +package com.azure.search.documents.models; +import com.azure.core.annotation.Generated; import com.azure.core.annotation.Immutable; import com.azure.json.JsonReader; import com.azure.json.JsonSerializable; import com.azure.json.JsonToken; import com.azure.json.JsonWriter; -import com.azure.search.documents.indexes.models.SynonymMap; import java.io.IOException; import java.util.List; /** - * Response from a List SynonymMaps request. If successful, it includes the full definitions of all synonym maps. + * Response from a List SynonymMaps request. If successful, it includes the full + * definitions of all synonym maps. */ @Immutable public final class ListSynonymMapsResult implements JsonSerializable { /* * The synonym maps in the Search service. */ + @Generated private final List synonymMaps; /** @@ -30,7 +30,8 @@ public final class ListSynonymMapsResult implements JsonSerializable synonymMaps) { + @Generated + private ListSynonymMapsResult(List synonymMaps) { this.synonymMaps = synonymMaps; } @@ -39,6 +40,7 @@ public ListSynonymMapsResult(List synonymMaps) { * * @return the synonymMaps value. */ + @Generated public List getSynonymMaps() { return this.synonymMaps; } @@ -46,9 +48,11 @@ public List getSynonymMaps() { /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); + jsonWriter.writeArrayField("value", this.synonymMaps, (writer, element) -> writer.writeJson(element)); return jsonWriter.writeEndObject(); } @@ -61,9 +65,9 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { * @throws IllegalStateException If the deserialized JSON object was missing any required properties. * @throws IOException If an error occurs while reading the ListSynonymMapsResult. */ + @Generated public static ListSynonymMapsResult fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { - boolean synonymMapsFound = false; List synonymMaps = null; while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); @@ -71,15 +75,11 @@ public static ListSynonymMapsResult fromJson(JsonReader jsonReader) throws IOExc if ("value".equals(fieldName)) { synonymMaps = reader.readArray(reader1 -> SynonymMap.fromJson(reader1)); - synonymMapsFound = true; } else { reader.skipChildren(); } } - if (synonymMapsFound) { - return new ListSynonymMapsResult(synonymMaps); - } - throw new IllegalStateException("Missing required property: value"); + return new ListSynonymMapsResult(synonymMaps); }); } } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/LookupDocument.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/LookupDocument.java new file mode 100644 index 000000000000..2cc7e7e3765f --- /dev/null +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/LookupDocument.java @@ -0,0 +1,95 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.search.documents.models; + +import com.azure.core.annotation.Generated; +import com.azure.core.annotation.Immutable; +import com.azure.core.util.BinaryData; +import com.azure.json.JsonReader; +import com.azure.json.JsonSerializable; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import java.io.IOException; +import java.util.LinkedHashMap; +import java.util.Map; + +/** + * A document retrieved via a document lookup operation. + */ +@Immutable +public final class LookupDocument implements JsonSerializable { + /* + * A document retrieved via a document lookup operation. + */ + @Generated + private Map additionalProperties; + + /** + * Creates an instance of LookupDocument class. + */ + @Generated + private LookupDocument() { + } + + /** + * Get the additionalProperties property: A document retrieved via a document lookup operation. + * + * @return the additionalProperties value. + */ + @Generated + public Map getAdditionalProperties() { + return this.additionalProperties; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + if (additionalProperties != null) { + for (Map.Entry additionalProperty : additionalProperties.entrySet()) { + jsonWriter.writeFieldName(additionalProperty.getKey()); + if (additionalProperty.getValue() == null) { + jsonWriter.writeNull(); + } else { + additionalProperty.getValue().writeTo(jsonWriter); + } + } + } + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of LookupDocument from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of LookupDocument if the JsonReader was pointing to an instance of it, or null if it was + * pointing to JSON null. + * @throws IOException If an error occurs while reading the LookupDocument. + */ + @Generated + public static LookupDocument fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + LookupDocument deserializedLookupDocument = new LookupDocument(); + Map additionalProperties = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if (additionalProperties == null) { + additionalProperties = new LinkedHashMap<>(); + } + + additionalProperties.put(fieldName, + reader.getNullable(nonNullReader -> BinaryData.fromObject(nonNullReader.readUntyped()))); + } + deserializedLookupDocument.additionalProperties = additionalProperties; + + return deserializedLookupDocument; + }); + } +} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/LuceneStandardAnalyzer.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/LuceneStandardAnalyzer.java similarity index 74% rename from sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/LuceneStandardAnalyzer.java rename to sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/LuceneStandardAnalyzer.java index 264464e6f623..f66ed258530d 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/LuceneStandardAnalyzer.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/LuceneStandardAnalyzer.java @@ -1,54 +1,58 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. -package com.azure.search.documents.indexes.models; +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.search.documents.models; import com.azure.core.annotation.Fluent; +import com.azure.core.annotation.Generated; import com.azure.json.JsonReader; import com.azure.json.JsonToken; import com.azure.json.JsonWriter; import java.io.IOException; -import java.util.Arrays; import java.util.List; /** - * Standard Apache Lucene analyzer; Composed of the standard tokenizer, lowercase filter and stop filter. + * Standard Apache Lucene analyzer; Composed of the standard tokenizer, lowercase + * filter and stop filter. */ @Fluent public final class LuceneStandardAnalyzer extends LexicalAnalyzer { - /* - * A URI fragment specifying the type of analyzer. + * The discriminator for derived types. */ + @Generated private String odataType = "#Microsoft.Azure.Search.StandardAnalyzer"; /* - * 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. + * 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. */ + @Generated private Integer maxTokenLength; /* * A list of stopwords. */ + @Generated private List stopwords; /** * Creates an instance of LuceneStandardAnalyzer class. - * + * * @param name the name value to set. */ + @Generated public LuceneStandardAnalyzer(String name) { super(name); } /** - * Get the odataType property: A URI fragment specifying the type of analyzer. - * + * Get the odataType property: The discriminator for derived types. + * * @return the odataType value. */ + @Generated @Override public String getOdataType() { return this.odataType; @@ -57,9 +61,10 @@ public String getOdataType() { /** * Get the maxTokenLength property: 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. - * + * * @return the maxTokenLength value. */ + @Generated public Integer getMaxTokenLength() { return this.maxTokenLength; } @@ -67,10 +72,11 @@ public Integer getMaxTokenLength() { /** * Set the maxTokenLength property: 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. - * + * * @param maxTokenLength the maxTokenLength value to set. * @return the LuceneStandardAnalyzer object itself. */ + @Generated public LuceneStandardAnalyzer setMaxTokenLength(Integer maxTokenLength) { this.maxTokenLength = maxTokenLength; return this; @@ -78,19 +84,21 @@ public LuceneStandardAnalyzer setMaxTokenLength(Integer maxTokenLength) { /** * Get the stopwords property: A list of stopwords. - * + * * @return the stopwords value. */ + @Generated public List getStopwords() { return this.stopwords; } /** * Set the stopwords property: A list of stopwords. - * + * * @param stopwords the stopwords value to set. * @return the LuceneStandardAnalyzer object itself. */ + @Generated public LuceneStandardAnalyzer setStopwords(List stopwords) { this.stopwords = stopwords; return this; @@ -99,6 +107,7 @@ public LuceneStandardAnalyzer setStopwords(List stopwords) { /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); @@ -111,16 +120,16 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of LuceneStandardAnalyzer from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of LuceneStandardAnalyzer if the JsonReader was pointing to an instance of it, or null if it * was pointing to JSON null. * @throws IllegalStateException If the deserialized JSON object was missing any required properties. * @throws IOException If an error occurs while reading the LuceneStandardAnalyzer. */ + @Generated public static LuceneStandardAnalyzer fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { - boolean nameFound = false; String name = null; String odataType = "#Microsoft.Azure.Search.StandardAnalyzer"; Integer maxTokenLength = null; @@ -128,9 +137,9 @@ public static LuceneStandardAnalyzer fromJson(JsonReader jsonReader) throws IOEx while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); + if ("name".equals(fieldName)) { name = reader.getString(); - nameFound = true; } else if ("@odata.type".equals(fieldName)) { odataType = reader.getString(); } else if ("maxTokenLength".equals(fieldName)) { @@ -141,25 +150,12 @@ public static LuceneStandardAnalyzer fromJson(JsonReader jsonReader) throws IOEx reader.skipChildren(); } } - if (nameFound) { - LuceneStandardAnalyzer deserializedLuceneStandardAnalyzer = new LuceneStandardAnalyzer(name); - deserializedLuceneStandardAnalyzer.odataType = odataType; - deserializedLuceneStandardAnalyzer.maxTokenLength = maxTokenLength; - deserializedLuceneStandardAnalyzer.stopwords = stopwords; - return deserializedLuceneStandardAnalyzer; - } - throw new IllegalStateException("Missing required property: name"); - }); - } + LuceneStandardAnalyzer deserializedLuceneStandardAnalyzer = new LuceneStandardAnalyzer(name); + deserializedLuceneStandardAnalyzer.odataType = odataType; + deserializedLuceneStandardAnalyzer.maxTokenLength = maxTokenLength; + deserializedLuceneStandardAnalyzer.stopwords = stopwords; - /** - * Set the stopwords property: A list of stopwords. - * - * @param stopwords the stopwords value to set. - * @return the LuceneStandardAnalyzer object itself. - */ - public LuceneStandardAnalyzer setStopwords(String... stopwords) { - this.stopwords = (stopwords == null) ? null : Arrays.asList(stopwords); - return this; + return deserializedLuceneStandardAnalyzer; + }); } } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/implementation/models/LuceneStandardTokenizerV2.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/LuceneStandardTokenizerV2.java similarity index 76% rename from sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/implementation/models/LuceneStandardTokenizerV2.java rename to sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/LuceneStandardTokenizerV2.java index 0fb35c5a970b..6595b05ca2a4 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/implementation/models/LuceneStandardTokenizerV2.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/LuceneStandardTokenizerV2.java @@ -1,32 +1,33 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) TypeSpec Code Generator. -package com.azure.search.documents.indexes.implementation.models; +package com.azure.search.documents.models; import com.azure.core.annotation.Fluent; +import com.azure.core.annotation.Generated; import com.azure.json.JsonReader; import com.azure.json.JsonToken; import com.azure.json.JsonWriter; -import com.azure.search.documents.indexes.models.LexicalTokenizer; import java.io.IOException; /** - * Breaks text following the Unicode Text Segmentation rules. This tokenizer is implemented using Apache Lucene. + * Breaks text following the Unicode Text Segmentation rules. This tokenizer is + * implemented using Apache Lucene. */ @Fluent public final class LuceneStandardTokenizerV2 extends LexicalTokenizer { /* - * A URI fragment specifying the type of tokenizer. + * The discriminator for derived types. */ + @Generated private String odataType = "#Microsoft.Azure.Search.StandardTokenizerV2"; /* - * 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. + * 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. */ + @Generated private Integer maxTokenLength; /** @@ -34,15 +35,17 @@ public final class LuceneStandardTokenizerV2 extends LexicalTokenizer { * * @param name the name value to set. */ + @Generated public LuceneStandardTokenizerV2(String name) { super(name); } /** - * Get the odataType property: A URI fragment specifying the type of tokenizer. + * Get the odataType property: The discriminator for derived types. * * @return the odataType value. */ + @Generated @Override public String getOdataType() { return this.odataType; @@ -54,6 +57,7 @@ public String getOdataType() { * * @return the maxTokenLength value. */ + @Generated public Integer getMaxTokenLength() { return this.maxTokenLength; } @@ -65,6 +69,7 @@ public Integer getMaxTokenLength() { * @param maxTokenLength the maxTokenLength value to set. * @return the LuceneStandardTokenizerV2 object itself. */ + @Generated public LuceneStandardTokenizerV2 setMaxTokenLength(Integer maxTokenLength) { this.maxTokenLength = maxTokenLength; return this; @@ -73,6 +78,7 @@ public LuceneStandardTokenizerV2 setMaxTokenLength(Integer maxTokenLength) { /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); @@ -91,9 +97,9 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { * @throws IllegalStateException If the deserialized JSON object was missing any required properties. * @throws IOException If an error occurs while reading the LuceneStandardTokenizerV2. */ + @Generated public static LuceneStandardTokenizerV2 fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { - boolean nameFound = false; String name = null; String odataType = "#Microsoft.Azure.Search.StandardTokenizerV2"; Integer maxTokenLength = null; @@ -103,7 +109,6 @@ public static LuceneStandardTokenizerV2 fromJson(JsonReader jsonReader) throws I if ("name".equals(fieldName)) { name = reader.getString(); - nameFound = true; } else if ("@odata.type".equals(fieldName)) { odataType = reader.getString(); } else if ("maxTokenLength".equals(fieldName)) { @@ -112,14 +117,11 @@ public static LuceneStandardTokenizerV2 fromJson(JsonReader jsonReader) throws I reader.skipChildren(); } } - if (nameFound) { - LuceneStandardTokenizerV2 deserializedLuceneStandardTokenizerV2 = new LuceneStandardTokenizerV2(name); - deserializedLuceneStandardTokenizerV2.odataType = odataType; - deserializedLuceneStandardTokenizerV2.maxTokenLength = maxTokenLength; + LuceneStandardTokenizerV2 deserializedLuceneStandardTokenizerV2 = new LuceneStandardTokenizerV2(name); + deserializedLuceneStandardTokenizerV2.odataType = odataType; + deserializedLuceneStandardTokenizerV2.maxTokenLength = maxTokenLength; - return deserializedLuceneStandardTokenizerV2; - } - throw new IllegalStateException("Missing required property: name"); + return deserializedLuceneStandardTokenizerV2; }); } } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/MagnitudeScoringFunction.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/MagnitudeScoringFunction.java similarity index 69% rename from sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/MagnitudeScoringFunction.java rename to sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/MagnitudeScoringFunction.java index 900af19e0ffc..491569f165c1 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/MagnitudeScoringFunction.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/MagnitudeScoringFunction.java @@ -1,18 +1,15 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) TypeSpec Code Generator. -package com.azure.search.documents.indexes.models; +package com.azure.search.documents.models; import com.azure.core.annotation.Fluent; +import com.azure.core.annotation.Generated; import com.azure.json.JsonReader; import com.azure.json.JsonToken; import com.azure.json.JsonWriter; import java.io.IOException; -import java.util.ArrayList; -import java.util.List; /** * Defines a function that boosts scores based on the magnitude of a numeric field. @@ -20,14 +17,15 @@ @Fluent public final class MagnitudeScoringFunction extends ScoringFunction { /* - * Indicates the type of function to use. Valid values include magnitude, freshness, distance, and tag. The function - * type must be lower case. + * Type of ScoringFunction. */ + @Generated private String type = "magnitude"; /* * Parameter values for the magnitude scoring function. */ + @Generated private final MagnitudeScoringParameters parameters; /** @@ -37,17 +35,18 @@ public final class MagnitudeScoringFunction extends ScoringFunction { * @param boost the boost value to set. * @param parameters the parameters value to set. */ + @Generated public MagnitudeScoringFunction(String fieldName, double boost, MagnitudeScoringParameters parameters) { super(fieldName, boost); this.parameters = parameters; } /** - * Get the type property: Indicates the type of function to use. Valid values include magnitude, freshness, - * distance, and tag. The function type must be lower case. + * Get the type property: Type of ScoringFunction. * * @return the type value. */ + @Generated @Override public String getType() { return this.type; @@ -58,6 +57,7 @@ public String getType() { * * @return the parameters value. */ + @Generated public MagnitudeScoringParameters getParameters() { return this.parameters; } @@ -65,6 +65,7 @@ public MagnitudeScoringParameters getParameters() { /** * {@inheritDoc} */ + @Generated @Override public MagnitudeScoringFunction setInterpolation(ScoringFunctionInterpolation interpolation) { super.setInterpolation(interpolation); @@ -74,6 +75,7 @@ public MagnitudeScoringFunction setInterpolation(ScoringFunctionInterpolation in /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); @@ -94,14 +96,12 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { * @throws IllegalStateException If the deserialized JSON object was missing any required properties. * @throws IOException If an error occurs while reading the MagnitudeScoringFunction. */ + @Generated public static MagnitudeScoringFunction fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { - boolean fieldNameFound = false; String fieldName = null; - boolean boostFound = false; double boost = 0.0; ScoringFunctionInterpolation interpolation = null; - boolean parametersFound = false; MagnitudeScoringParameters parameters = null; String type = "magnitude"; while (reader.nextToken() != JsonToken.END_OBJECT) { @@ -110,42 +110,24 @@ public static MagnitudeScoringFunction fromJson(JsonReader jsonReader) throws IO if ("fieldName".equals(jsonFieldName)) { fieldName = reader.getString(); - fieldNameFound = true; } else if ("boost".equals(jsonFieldName)) { boost = reader.getDouble(); - boostFound = true; } else if ("interpolation".equals(jsonFieldName)) { interpolation = ScoringFunctionInterpolation.fromString(reader.getString()); } else if ("magnitude".equals(jsonFieldName)) { parameters = MagnitudeScoringParameters.fromJson(reader); - parametersFound = true; } else if ("type".equals(jsonFieldName)) { type = reader.getString(); } else { reader.skipChildren(); } } - if (fieldNameFound && boostFound && parametersFound) { - MagnitudeScoringFunction deserializedMagnitudeScoringFunction - = new MagnitudeScoringFunction(fieldName, boost, parameters); - deserializedMagnitudeScoringFunction.setInterpolation(interpolation); - deserializedMagnitudeScoringFunction.type = type; + MagnitudeScoringFunction deserializedMagnitudeScoringFunction + = new MagnitudeScoringFunction(fieldName, boost, parameters); + deserializedMagnitudeScoringFunction.setInterpolation(interpolation); + deserializedMagnitudeScoringFunction.type = type; - return deserializedMagnitudeScoringFunction; - } - List missingProperties = new ArrayList<>(); - if (!fieldNameFound) { - missingProperties.add("fieldName"); - } - if (!boostFound) { - missingProperties.add("boost"); - } - if (!parametersFound) { - missingProperties.add("magnitude"); - } - - throw new IllegalStateException( - "Missing required property/properties: " + String.join(", ", missingProperties)); + return deserializedMagnitudeScoringFunction; }); } } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/MagnitudeScoringParameters.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/MagnitudeScoringParameters.java similarity index 73% rename from sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/MagnitudeScoringParameters.java rename to sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/MagnitudeScoringParameters.java index 79dff0fecfc9..9de849074af3 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/MagnitudeScoringParameters.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/MagnitudeScoringParameters.java @@ -1,47 +1,48 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. -package com.azure.search.documents.indexes.models; +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.search.documents.models; import com.azure.core.annotation.Fluent; +import com.azure.core.annotation.Generated; import com.azure.json.JsonReader; import com.azure.json.JsonSerializable; import com.azure.json.JsonToken; import com.azure.json.JsonWriter; import java.io.IOException; -import java.util.ArrayList; -import java.util.List; /** * Provides parameter values to a magnitude scoring function. */ @Fluent public final class MagnitudeScoringParameters implements JsonSerializable { - /* * The field value at which boosting starts. */ + @Generated private final double boostingRangeStart; /* * The field value at which boosting ends. */ + @Generated private final double boostingRangeEnd; /* - * A value indicating whether to apply a constant boost for field values beyond the range end value; default is - * false. + * A value indicating whether to apply a constant boost for field values beyond + * the range end value; default is false. */ + @Generated private Boolean shouldBoostBeyondRangeByConstant; /** * Creates an instance of MagnitudeScoringParameters class. - * + * * @param boostingRangeStart the boostingRangeStart value to set. * @param boostingRangeEnd the boostingRangeEnd value to set. */ + @Generated public MagnitudeScoringParameters(double boostingRangeStart, double boostingRangeEnd) { this.boostingRangeStart = boostingRangeStart; this.boostingRangeEnd = boostingRangeEnd; @@ -49,39 +50,45 @@ public MagnitudeScoringParameters(double boostingRangeStart, double boostingRang /** * Get the boostingRangeStart property: The field value at which boosting starts. - * + * * @return the boostingRangeStart value. */ + @Generated public double getBoostingRangeStart() { return this.boostingRangeStart; } /** * Get the boostingRangeEnd property: The field value at which boosting ends. - * + * * @return the boostingRangeEnd value. */ + @Generated public double getBoostingRangeEnd() { return this.boostingRangeEnd; } /** * Get the shouldBoostBeyondRangeByConstant property: A value indicating whether to apply a constant boost for field - * values beyond the range end value; default is false. - * + * values beyond + * the range end value; default is false. + * * @return the shouldBoostBeyondRangeByConstant value. */ - public Boolean shouldBoostBeyondRangeByConstant() { + @Generated + public Boolean isShouldBoostBeyondRangeByConstant() { return this.shouldBoostBeyondRangeByConstant; } /** * Set the shouldBoostBeyondRangeByConstant property: A value indicating whether to apply a constant boost for field - * values beyond the range end value; default is false. - * + * values beyond + * the range end value; default is false. + * * @param shouldBoostBeyondRangeByConstant the shouldBoostBeyondRangeByConstant value to set. * @return the MagnitudeScoringParameters object itself. */ + @Generated public MagnitudeScoringParameters setShouldBoostBeyondRangeByConstant(Boolean shouldBoostBeyondRangeByConstant) { this.shouldBoostBeyondRangeByConstant = shouldBoostBeyondRangeByConstant; return this; @@ -90,6 +97,7 @@ public MagnitudeScoringParameters setShouldBoostBeyondRangeByConstant(Boolean sh /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); @@ -101,51 +109,38 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of MagnitudeScoringParameters from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of MagnitudeScoringParameters if the JsonReader was pointing to an instance of it, or null if * it was pointing to JSON null. * @throws IllegalStateException If the deserialized JSON object was missing any required properties. * @throws IOException If an error occurs while reading the MagnitudeScoringParameters. */ + @Generated public static MagnitudeScoringParameters fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { - boolean boostingRangeStartFound = false; double boostingRangeStart = 0.0; - boolean boostingRangeEndFound = false; double boostingRangeEnd = 0.0; Boolean shouldBoostBeyondRangeByConstant = null; while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); + if ("boostingRangeStart".equals(fieldName)) { boostingRangeStart = reader.getDouble(); - boostingRangeStartFound = true; } else if ("boostingRangeEnd".equals(fieldName)) { boostingRangeEnd = reader.getDouble(); - boostingRangeEndFound = true; } else if ("constantBoostBeyondRange".equals(fieldName)) { shouldBoostBeyondRangeByConstant = reader.getNullable(JsonReader::getBoolean); } else { reader.skipChildren(); } } - if (boostingRangeStartFound && boostingRangeEndFound) { - MagnitudeScoringParameters deserializedMagnitudeScoringParameters - = new MagnitudeScoringParameters(boostingRangeStart, boostingRangeEnd); - deserializedMagnitudeScoringParameters.shouldBoostBeyondRangeByConstant - = shouldBoostBeyondRangeByConstant; - return deserializedMagnitudeScoringParameters; - } - List missingProperties = new ArrayList<>(); - if (!boostingRangeStartFound) { - missingProperties.add("boostingRangeStart"); - } - if (!boostingRangeEndFound) { - missingProperties.add("boostingRangeEnd"); - } - throw new IllegalStateException( - "Missing required property/properties: " + String.join(", ", missingProperties)); + MagnitudeScoringParameters deserializedMagnitudeScoringParameters + = new MagnitudeScoringParameters(boostingRangeStart, boostingRangeEnd); + deserializedMagnitudeScoringParameters.shouldBoostBeyondRangeByConstant = shouldBoostBeyondRangeByConstant; + + return deserializedMagnitudeScoringParameters; }); } } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/MappingCharFilter.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/MappingCharFilter.java similarity index 68% rename from sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/MappingCharFilter.java rename to sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/MappingCharFilter.java index ee7edb0550db..3a137e84d6de 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/MappingCharFilter.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/MappingCharFilter.java @@ -1,35 +1,36 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) TypeSpec Code Generator. -package com.azure.search.documents.indexes.models; +package com.azure.search.documents.models; +import com.azure.core.annotation.Generated; import com.azure.core.annotation.Immutable; import com.azure.json.JsonReader; import com.azure.json.JsonToken; import com.azure.json.JsonWriter; import java.io.IOException; -import java.util.ArrayList; import java.util.List; /** - * 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. + * 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. */ @Immutable public final class MappingCharFilter extends CharFilter { /* - * A URI fragment specifying the type of char filter. + * The discriminator for derived types. */ + @Generated private String odataType = "#Microsoft.Azure.Search.MappingCharFilter"; /* - * A list of mappings of the following format: "a=>b" (all occurrences of the character "a" will be replaced with - * character "b"). + * A list of mappings of the following format: "a=>b" (all occurrences of the + * character "a" will be replaced with character "b"). */ + @Generated private final List mappings; /** @@ -38,16 +39,18 @@ public final class MappingCharFilter extends CharFilter { * @param name the name value to set. * @param mappings the mappings value to set. */ + @Generated public MappingCharFilter(String name, List mappings) { super(name); this.mappings = mappings; } /** - * Get the odataType property: A URI fragment specifying the type of char filter. + * Get the odataType property: The discriminator for derived types. * * @return the odataType value. */ + @Generated @Override public String getOdataType() { return this.odataType; @@ -59,6 +62,7 @@ public String getOdataType() { * * @return the mappings value. */ + @Generated public List getMappings() { return this.mappings; } @@ -66,6 +70,7 @@ public List getMappings() { /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); @@ -84,11 +89,10 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { * @throws IllegalStateException If the deserialized JSON object was missing any required properties. * @throws IOException If an error occurs while reading the MappingCharFilter. */ + @Generated public static MappingCharFilter fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { - boolean nameFound = false; String name = null; - boolean mappingsFound = false; List mappings = null; String odataType = "#Microsoft.Azure.Search.MappingCharFilter"; while (reader.nextToken() != JsonToken.END_OBJECT) { @@ -97,32 +101,18 @@ public static MappingCharFilter fromJson(JsonReader jsonReader) throws IOExcepti if ("name".equals(fieldName)) { name = reader.getString(); - nameFound = true; } else if ("mappings".equals(fieldName)) { mappings = reader.readArray(reader1 -> reader1.getString()); - mappingsFound = true; } else if ("@odata.type".equals(fieldName)) { odataType = reader.getString(); } else { reader.skipChildren(); } } - if (nameFound && mappingsFound) { - MappingCharFilter deserializedMappingCharFilter = new MappingCharFilter(name, mappings); - deserializedMappingCharFilter.odataType = odataType; - - return deserializedMappingCharFilter; - } - List missingProperties = new ArrayList<>(); - if (!nameFound) { - missingProperties.add("name"); - } - if (!mappingsFound) { - missingProperties.add("mappings"); - } + MappingCharFilter deserializedMappingCharFilter = new MappingCharFilter(name, mappings); + deserializedMappingCharFilter.odataType = odataType; - throw new IllegalStateException( - "Missing required property/properties: " + String.join(", ", missingProperties)); + return deserializedMappingCharFilter; }); } } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/MarkdownHeaderDepth.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/MarkdownHeaderDepth.java similarity index 76% rename from sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/MarkdownHeaderDepth.java rename to sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/MarkdownHeaderDepth.java index bfa27ad396f1..ad6687fcc558 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/MarkdownHeaderDepth.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/MarkdownHeaderDepth.java @@ -1,47 +1,58 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) TypeSpec Code Generator. -package com.azure.search.documents.indexes.models; +package com.azure.search.documents.models; +import com.azure.core.annotation.Generated; import com.azure.core.util.ExpandableStringEnum; import java.util.Collection; /** - * Specifies the max header depth that will be considered while grouping markdown content. Default is `h6`. + * Specifies the max header depth that will be considered while grouping markdown + * content. Default is `h6`. */ public final class MarkdownHeaderDepth extends ExpandableStringEnum { /** - * Indicates that headers up to a level of h1 will be considered while grouping markdown content. + * Indicates that headers up to a level of h1 will be considered while grouping + * markdown content. */ + @Generated public static final MarkdownHeaderDepth H1 = fromString("h1"); /** - * Indicates that headers up to a level of h2 will be considered while grouping markdown content. + * Indicates that headers up to a level of h2 will be considered while grouping + * markdown content. */ + @Generated public static final MarkdownHeaderDepth H2 = fromString("h2"); /** - * Indicates that headers up to a level of h3 will be considered while grouping markdown content. + * Indicates that headers up to a level of h3 will be considered while grouping + * markdown content. */ + @Generated public static final MarkdownHeaderDepth H3 = fromString("h3"); /** - * Indicates that headers up to a level of h4 will be considered while grouping markdown content. + * Indicates that headers up to a level of h4 will be considered while grouping + * markdown content. */ + @Generated public static final MarkdownHeaderDepth H4 = fromString("h4"); /** - * Indicates that headers up to a level of h5 will be considered while grouping markdown content. + * Indicates that headers up to a level of h5 will be considered while grouping + * markdown content. */ + @Generated public static final MarkdownHeaderDepth H5 = fromString("h5"); /** - * Indicates that headers up to a level of h6 will be considered while grouping markdown content. This is the - * default. + * Indicates that headers up to a level of h6 will be considered while grouping + * markdown content. This is the default. */ + @Generated public static final MarkdownHeaderDepth H6 = fromString("h6"); /** @@ -49,6 +60,7 @@ public final class MarkdownHeaderDepth extends ExpandableStringEnum values() { return values(MarkdownHeaderDepth.class); } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/MarkdownParsingSubmode.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/MarkdownParsingSubmode.java similarity index 74% rename from sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/MarkdownParsingSubmode.java rename to sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/MarkdownParsingSubmode.java index 9143e2eed252..5976576d3de1 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/MarkdownParsingSubmode.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/MarkdownParsingSubmode.java @@ -1,29 +1,32 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) TypeSpec Code Generator. -package com.azure.search.documents.indexes.models; +package com.azure.search.documents.models; +import com.azure.core.annotation.Generated; import com.azure.core.util.ExpandableStringEnum; import java.util.Collection; /** - * 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`. + * 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`. */ public final class MarkdownParsingSubmode extends ExpandableStringEnum { /** - * Indicates that each section of the markdown file (up to a specified depth) will be parsed into individual search - * documents. This can result in a single markdown file producing multiple search documents. This is the default + * Indicates that each section of the markdown file (up to a specified depth) will + * be parsed into individual search documents. This can result in a single + * markdown file producing multiple search documents. This is the default * sub-mode. */ + @Generated public static final MarkdownParsingSubmode ONE_TO_MANY = fromString("oneToMany"); /** * Indicates that each markdown file will be parsed into a single search document. */ + @Generated public static final MarkdownParsingSubmode ONE_TO_ONE = fromString("oneToOne"); /** @@ -31,6 +34,7 @@ public final class MarkdownParsingSubmode extends ExpandableStringEnum values() { return values(MarkdownParsingSubmode.class); } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/MergeSkill.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/MergeSkill.java similarity index 78% rename from sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/MergeSkill.java rename to sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/MergeSkill.java index 38a09bf9698e..5633ac06e818 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/MergeSkill.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/MergeSkill.java @@ -1,38 +1,41 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) TypeSpec Code Generator. -package com.azure.search.documents.indexes.models; +package com.azure.search.documents.models; import com.azure.core.annotation.Fluent; +import com.azure.core.annotation.Generated; import com.azure.json.JsonReader; import com.azure.json.JsonToken; import com.azure.json.JsonWriter; import java.io.IOException; -import java.util.ArrayList; import java.util.List; /** - * A skill for merging two or more strings into a single unified string, with an optional user-defined delimiter - * separating each component part. + * A skill for merging two or more strings into a single unified string, with an + * optional user-defined delimiter separating each component part. */ @Fluent public final class MergeSkill extends SearchIndexerSkill { /* - * A URI fragment specifying the type of skill. + * The discriminator for derived types. */ + @Generated private String odataType = "#Microsoft.Skills.Text.MergeSkill"; /* - * The tag indicates the start of the merged text. By default, the tag is an empty space. + * The tag indicates the start of the merged text. By default, the tag is an empty + * space. */ + @Generated private String insertPreTag; /* - * The tag indicates the end of the merged text. By default, the tag is an empty space. + * The tag indicates the end of the merged text. By default, the tag is an empty + * space. */ + @Generated private String insertPostTag; /** @@ -41,15 +44,17 @@ public final class MergeSkill extends SearchIndexerSkill { * @param inputs the inputs value to set. * @param outputs the outputs value to set. */ + @Generated public MergeSkill(List inputs, List outputs) { super(inputs, outputs); } /** - * Get the odataType property: A URI fragment specifying the type of skill. + * Get the odataType property: The discriminator for derived types. * * @return the odataType value. */ + @Generated @Override public String getOdataType() { return this.odataType; @@ -61,6 +66,7 @@ public String getOdataType() { * * @return the insertPreTag value. */ + @Generated public String getInsertPreTag() { return this.insertPreTag; } @@ -72,6 +78,7 @@ public String getInsertPreTag() { * @param insertPreTag the insertPreTag value to set. * @return the MergeSkill object itself. */ + @Generated public MergeSkill setInsertPreTag(String insertPreTag) { this.insertPreTag = insertPreTag; return this; @@ -83,6 +90,7 @@ public MergeSkill setInsertPreTag(String insertPreTag) { * * @return the insertPostTag value. */ + @Generated public String getInsertPostTag() { return this.insertPostTag; } @@ -94,6 +102,7 @@ public String getInsertPostTag() { * @param insertPostTag the insertPostTag value to set. * @return the MergeSkill object itself. */ + @Generated public MergeSkill setInsertPostTag(String insertPostTag) { this.insertPostTag = insertPostTag; return this; @@ -102,6 +111,7 @@ public MergeSkill setInsertPostTag(String insertPostTag) { /** * {@inheritDoc} */ + @Generated @Override public MergeSkill setName(String name) { super.setName(name); @@ -111,6 +121,7 @@ public MergeSkill setName(String name) { /** * {@inheritDoc} */ + @Generated @Override public MergeSkill setDescription(String description) { super.setDescription(description); @@ -120,6 +131,7 @@ public MergeSkill setDescription(String description) { /** * {@inheritDoc} */ + @Generated @Override public MergeSkill setContext(String context) { super.setContext(context); @@ -129,6 +141,7 @@ public MergeSkill setContext(String context) { /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); @@ -152,11 +165,10 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { * @throws IllegalStateException If the deserialized JSON object was missing any required properties. * @throws IOException If an error occurs while reading the MergeSkill. */ + @Generated public static MergeSkill fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { - boolean inputsFound = false; List inputs = null; - boolean outputsFound = false; List outputs = null; String name = null; String description = null; @@ -170,10 +182,8 @@ public static MergeSkill fromJson(JsonReader jsonReader) throws IOException { if ("inputs".equals(fieldName)) { inputs = reader.readArray(reader1 -> InputFieldMappingEntry.fromJson(reader1)); - inputsFound = true; } else if ("outputs".equals(fieldName)) { outputs = reader.readArray(reader1 -> OutputFieldMappingEntry.fromJson(reader1)); - outputsFound = true; } else if ("name".equals(fieldName)) { name = reader.getString(); } else if ("description".equals(fieldName)) { @@ -190,27 +200,15 @@ public static MergeSkill fromJson(JsonReader jsonReader) throws IOException { reader.skipChildren(); } } - if (inputsFound && outputsFound) { - MergeSkill deserializedMergeSkill = new MergeSkill(inputs, outputs); - deserializedMergeSkill.setName(name); - deserializedMergeSkill.setDescription(description); - deserializedMergeSkill.setContext(context); - deserializedMergeSkill.odataType = odataType; - deserializedMergeSkill.insertPreTag = insertPreTag; - deserializedMergeSkill.insertPostTag = insertPostTag; - - return deserializedMergeSkill; - } - List missingProperties = new ArrayList<>(); - if (!inputsFound) { - missingProperties.add("inputs"); - } - if (!outputsFound) { - missingProperties.add("outputs"); - } - - throw new IllegalStateException( - "Missing required property/properties: " + String.join(", ", missingProperties)); + MergeSkill deserializedMergeSkill = new MergeSkill(inputs, outputs); + deserializedMergeSkill.setName(name); + deserializedMergeSkill.setDescription(description); + deserializedMergeSkill.setContext(context); + deserializedMergeSkill.odataType = odataType; + deserializedMergeSkill.insertPreTag = insertPreTag; + deserializedMergeSkill.insertPostTag = insertPostTag; + + return deserializedMergeSkill; }); } } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/MicrosoftLanguageStemmingTokenizer.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/MicrosoftLanguageStemmingTokenizer.java similarity index 64% rename from sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/MicrosoftLanguageStemmingTokenizer.java rename to sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/MicrosoftLanguageStemmingTokenizer.java index 847a2e748099..5775e72de41b 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/MicrosoftLanguageStemmingTokenizer.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/MicrosoftLanguageStemmingTokenizer.java @@ -1,59 +1,66 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. -package com.azure.search.documents.indexes.models; +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.search.documents.models; import com.azure.core.annotation.Fluent; +import com.azure.core.annotation.Generated; import com.azure.json.JsonReader; import com.azure.json.JsonToken; import com.azure.json.JsonWriter; import java.io.IOException; /** - * Divides text using language-specific rules and reduces words to their base forms. + * Divides text using language-specific rules and reduces words to their base + * forms. */ @Fluent public final class MicrosoftLanguageStemmingTokenizer extends LexicalTokenizer { - /* - * A URI fragment specifying the type of tokenizer. + * The discriminator for derived types. */ + @Generated private String odataType = "#Microsoft.Azure.Search.MicrosoftLanguageStemmingTokenizer"; /* - * 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. + * 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. */ + @Generated private Integer maxTokenLength; /* - * 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. + * 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. */ - private Boolean isSearchTokenizerUsed; + @Generated + private Boolean isSearchTokenizer; /* * The language to use. The default is English. */ + @Generated private MicrosoftStemmingTokenizerLanguage language; /** * Creates an instance of MicrosoftLanguageStemmingTokenizer class. - * + * * @param name the name value to set. */ + @Generated public MicrosoftLanguageStemmingTokenizer(String name) { super(name); } /** - * Get the odataType property: A URI fragment specifying the type of tokenizer. - * + * Get the odataType property: The discriminator for derived types. + * * @return the odataType value. */ + @Generated @Override public String getOdataType() { return this.odataType; @@ -61,65 +68,75 @@ public String getOdataType() { /** * Get the maxTokenLength property: 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. - * + * 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. + * * @return the maxTokenLength value. */ + @Generated public Integer getMaxTokenLength() { return this.maxTokenLength; } /** * Set the maxTokenLength property: 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. - * + * 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. + * * @param maxTokenLength the maxTokenLength value to set. * @return the MicrosoftLanguageStemmingTokenizer object itself. */ + @Generated public MicrosoftLanguageStemmingTokenizer setMaxTokenLength(Integer maxTokenLength) { this.maxTokenLength = maxTokenLength; return this; } /** - * Get the isSearchTokenizerUsed property: 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. - * - * @return the isSearchTokenizerUsed value. + * Get the isSearchTokenizer property: 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. + * + * @return the isSearchTokenizer value. */ + @Generated public Boolean isSearchTokenizer() { - return this.isSearchTokenizerUsed; + return this.isSearchTokenizer; } /** - * Set the isSearchTokenizerUsed property: 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. - * - * @param isSearchTokenizerUsed the isSearchTokenizerUsed value to set. + * Set the isSearchTokenizer property: 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. + * + * @param isSearchTokenizer the isSearchTokenizer value to set. * @return the MicrosoftLanguageStemmingTokenizer object itself. */ - public MicrosoftLanguageStemmingTokenizer setIsSearchTokenizerUsed(Boolean isSearchTokenizerUsed) { - this.isSearchTokenizerUsed = isSearchTokenizerUsed; + @Generated + public MicrosoftLanguageStemmingTokenizer setIsSearchTokenizer(Boolean isSearchTokenizer) { + this.isSearchTokenizer = isSearchTokenizer; return this; } /** * Get the language property: The language to use. The default is English. - * + * * @return the language value. */ + @Generated public MicrosoftStemmingTokenizerLanguage getLanguage() { return this.language; } /** * Set the language property: The language to use. The default is English. - * + * * @param language the language value to set. * @return the MicrosoftLanguageStemmingTokenizer object itself. */ + @Generated public MicrosoftLanguageStemmingTokenizer setLanguage(MicrosoftStemmingTokenizerLanguage language) { this.language = language; return this; @@ -128,62 +145,61 @@ public MicrosoftLanguageStemmingTokenizer setLanguage(MicrosoftStemmingTokenizer /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); jsonWriter.writeStringField("name", getName()); jsonWriter.writeStringField("@odata.type", this.odataType); jsonWriter.writeNumberField("maxTokenLength", this.maxTokenLength); - jsonWriter.writeBooleanField("isSearchTokenizer", this.isSearchTokenizerUsed); + jsonWriter.writeBooleanField("isSearchTokenizer", this.isSearchTokenizer); jsonWriter.writeStringField("language", this.language == null ? null : this.language.toString()); return jsonWriter.writeEndObject(); } /** * Reads an instance of MicrosoftLanguageStemmingTokenizer from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of MicrosoftLanguageStemmingTokenizer if the JsonReader was pointing to an instance of it, or * null if it was pointing to JSON null. * @throws IllegalStateException If the deserialized JSON object was missing any required properties. * @throws IOException If an error occurs while reading the MicrosoftLanguageStemmingTokenizer. */ + @Generated public static MicrosoftLanguageStemmingTokenizer fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { - boolean nameFound = false; String name = null; String odataType = "#Microsoft.Azure.Search.MicrosoftLanguageStemmingTokenizer"; Integer maxTokenLength = null; - Boolean isSearchTokenizerUsed = null; + Boolean isSearchTokenizer = null; MicrosoftStemmingTokenizerLanguage language = null; while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); + if ("name".equals(fieldName)) { name = reader.getString(); - nameFound = true; } else if ("@odata.type".equals(fieldName)) { odataType = reader.getString(); } else if ("maxTokenLength".equals(fieldName)) { maxTokenLength = reader.getNullable(JsonReader::getInt); } else if ("isSearchTokenizer".equals(fieldName)) { - isSearchTokenizerUsed = reader.getNullable(JsonReader::getBoolean); + isSearchTokenizer = reader.getNullable(JsonReader::getBoolean); } else if ("language".equals(fieldName)) { language = MicrosoftStemmingTokenizerLanguage.fromString(reader.getString()); } else { reader.skipChildren(); } } - if (nameFound) { - MicrosoftLanguageStemmingTokenizer deserializedMicrosoftLanguageStemmingTokenizer - = new MicrosoftLanguageStemmingTokenizer(name); - deserializedMicrosoftLanguageStemmingTokenizer.odataType = odataType; - deserializedMicrosoftLanguageStemmingTokenizer.maxTokenLength = maxTokenLength; - deserializedMicrosoftLanguageStemmingTokenizer.isSearchTokenizerUsed = isSearchTokenizerUsed; - deserializedMicrosoftLanguageStemmingTokenizer.language = language; - return deserializedMicrosoftLanguageStemmingTokenizer; - } - throw new IllegalStateException("Missing required property: name"); + MicrosoftLanguageStemmingTokenizer deserializedMicrosoftLanguageStemmingTokenizer + = new MicrosoftLanguageStemmingTokenizer(name); + deserializedMicrosoftLanguageStemmingTokenizer.odataType = odataType; + deserializedMicrosoftLanguageStemmingTokenizer.maxTokenLength = maxTokenLength; + deserializedMicrosoftLanguageStemmingTokenizer.isSearchTokenizer = isSearchTokenizer; + deserializedMicrosoftLanguageStemmingTokenizer.language = language; + + return deserializedMicrosoftLanguageStemmingTokenizer; }); } } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/MicrosoftLanguageTokenizer.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/MicrosoftLanguageTokenizer.java similarity index 74% rename from sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/MicrosoftLanguageTokenizer.java rename to sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/MicrosoftLanguageTokenizer.java index 98a6281ca21b..28eac0325da9 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/MicrosoftLanguageTokenizer.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/MicrosoftLanguageTokenizer.java @@ -1,12 +1,11 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) TypeSpec Code Generator. -package com.azure.search.documents.indexes.models; +package com.azure.search.documents.models; import com.azure.core.annotation.Fluent; +import com.azure.core.annotation.Generated; import com.azure.json.JsonReader; import com.azure.json.JsonToken; import com.azure.json.JsonWriter; @@ -18,26 +17,31 @@ @Fluent public final class MicrosoftLanguageTokenizer extends LexicalTokenizer { /* - * A URI fragment specifying the type of tokenizer. + * The discriminator for derived types. */ + @Generated private String odataType = "#Microsoft.Azure.Search.MicrosoftLanguageTokenizer"; /* - * 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. + * 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. */ + @Generated private Integer maxTokenLength; /* - * 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. + * 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. */ + @Generated private Boolean isSearchTokenizer; /* * The language to use. The default is English. */ + @Generated private MicrosoftTokenizerLanguage language; /** @@ -45,15 +49,17 @@ public final class MicrosoftLanguageTokenizer extends LexicalTokenizer { * * @param name the name value to set. */ + @Generated public MicrosoftLanguageTokenizer(String name) { super(name); } /** - * Get the odataType property: A URI fragment specifying the type of tokenizer. + * Get the odataType property: The discriminator for derived types. * * @return the odataType value. */ + @Generated @Override public String getOdataType() { return this.odataType; @@ -61,23 +67,27 @@ public String getOdataType() { /** * Get the maxTokenLength property: 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. + * 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. * * @return the maxTokenLength value. */ + @Generated public Integer getMaxTokenLength() { return this.maxTokenLength; } /** * Set the maxTokenLength property: 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. + * 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. * * @param maxTokenLength the maxTokenLength value to set. * @return the MicrosoftLanguageTokenizer object itself. */ + @Generated public MicrosoftLanguageTokenizer setMaxTokenLength(Integer maxTokenLength) { this.maxTokenLength = maxTokenLength; return this; @@ -85,21 +95,25 @@ public MicrosoftLanguageTokenizer setMaxTokenLength(Integer maxTokenLength) { /** * Get the isSearchTokenizer property: 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. + * search + * tokenizer, set to false if used as the indexing tokenizer. Default is false. * * @return the isSearchTokenizer value. */ + @Generated public Boolean isSearchTokenizer() { return this.isSearchTokenizer; } /** * Set the isSearchTokenizer property: 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. + * search + * tokenizer, set to false if used as the indexing tokenizer. Default is false. * * @param isSearchTokenizer the isSearchTokenizer value to set. * @return the MicrosoftLanguageTokenizer object itself. */ + @Generated public MicrosoftLanguageTokenizer setIsSearchTokenizer(Boolean isSearchTokenizer) { this.isSearchTokenizer = isSearchTokenizer; return this; @@ -110,6 +124,7 @@ public MicrosoftLanguageTokenizer setIsSearchTokenizer(Boolean isSearchTokenizer * * @return the language value. */ + @Generated public MicrosoftTokenizerLanguage getLanguage() { return this.language; } @@ -120,6 +135,7 @@ public MicrosoftTokenizerLanguage getLanguage() { * @param language the language value to set. * @return the MicrosoftLanguageTokenizer object itself. */ + @Generated public MicrosoftLanguageTokenizer setLanguage(MicrosoftTokenizerLanguage language) { this.language = language; return this; @@ -128,6 +144,7 @@ public MicrosoftLanguageTokenizer setLanguage(MicrosoftTokenizerLanguage languag /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); @@ -148,9 +165,9 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { * @throws IllegalStateException If the deserialized JSON object was missing any required properties. * @throws IOException If an error occurs while reading the MicrosoftLanguageTokenizer. */ + @Generated public static MicrosoftLanguageTokenizer fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { - boolean nameFound = false; String name = null; String odataType = "#Microsoft.Azure.Search.MicrosoftLanguageTokenizer"; Integer maxTokenLength = null; @@ -162,7 +179,6 @@ public static MicrosoftLanguageTokenizer fromJson(JsonReader jsonReader) throws if ("name".equals(fieldName)) { name = reader.getString(); - nameFound = true; } else if ("@odata.type".equals(fieldName)) { odataType = reader.getString(); } else if ("maxTokenLength".equals(fieldName)) { @@ -175,17 +191,13 @@ public static MicrosoftLanguageTokenizer fromJson(JsonReader jsonReader) throws reader.skipChildren(); } } - if (nameFound) { - MicrosoftLanguageTokenizer deserializedMicrosoftLanguageTokenizer - = new MicrosoftLanguageTokenizer(name); - deserializedMicrosoftLanguageTokenizer.odataType = odataType; - deserializedMicrosoftLanguageTokenizer.maxTokenLength = maxTokenLength; - deserializedMicrosoftLanguageTokenizer.isSearchTokenizer = isSearchTokenizer; - deserializedMicrosoftLanguageTokenizer.language = language; - - return deserializedMicrosoftLanguageTokenizer; - } - throw new IllegalStateException("Missing required property: name"); + MicrosoftLanguageTokenizer deserializedMicrosoftLanguageTokenizer = new MicrosoftLanguageTokenizer(name); + deserializedMicrosoftLanguageTokenizer.odataType = odataType; + deserializedMicrosoftLanguageTokenizer.maxTokenLength = maxTokenLength; + deserializedMicrosoftLanguageTokenizer.isSearchTokenizer = isSearchTokenizer; + deserializedMicrosoftLanguageTokenizer.language = language; + + return deserializedMicrosoftLanguageTokenizer; }); } } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/MicrosoftStemmingTokenizerLanguage.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/MicrosoftStemmingTokenizerLanguage.java new file mode 100644 index 000000000000..a4c6cb11d57c --- /dev/null +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/MicrosoftStemmingTokenizerLanguage.java @@ -0,0 +1,315 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.search.documents.models; + +import com.azure.core.annotation.Generated; +import com.azure.core.util.ExpandableStringEnum; +import java.util.Collection; + +/** + * Lists the languages supported by the Microsoft language stemming tokenizer. + */ +public final class MicrosoftStemmingTokenizerLanguage extends ExpandableStringEnum { + /** + * Selects the Microsoft stemming tokenizer for Arabic. + */ + @Generated + public static final MicrosoftStemmingTokenizerLanguage ARABIC = fromString("arabic"); + + /** + * Selects the Microsoft stemming tokenizer for Bangla. + */ + @Generated + public static final MicrosoftStemmingTokenizerLanguage BANGLA = fromString("bangla"); + + /** + * Selects the Microsoft stemming tokenizer for Bulgarian. + */ + @Generated + public static final MicrosoftStemmingTokenizerLanguage BULGARIAN = fromString("bulgarian"); + + /** + * Selects the Microsoft stemming tokenizer for Catalan. + */ + @Generated + public static final MicrosoftStemmingTokenizerLanguage CATALAN = fromString("catalan"); + + /** + * Selects the Microsoft stemming tokenizer for Croatian. + */ + @Generated + public static final MicrosoftStemmingTokenizerLanguage CROATIAN = fromString("croatian"); + + /** + * Selects the Microsoft stemming tokenizer for Czech. + */ + @Generated + public static final MicrosoftStemmingTokenizerLanguage CZECH = fromString("czech"); + + /** + * Selects the Microsoft stemming tokenizer for Danish. + */ + @Generated + public static final MicrosoftStemmingTokenizerLanguage DANISH = fromString("danish"); + + /** + * Selects the Microsoft stemming tokenizer for Dutch. + */ + @Generated + public static final MicrosoftStemmingTokenizerLanguage DUTCH = fromString("dutch"); + + /** + * Selects the Microsoft stemming tokenizer for English. + */ + @Generated + public static final MicrosoftStemmingTokenizerLanguage ENGLISH = fromString("english"); + + /** + * Selects the Microsoft stemming tokenizer for Estonian. + */ + @Generated + public static final MicrosoftStemmingTokenizerLanguage ESTONIAN = fromString("estonian"); + + /** + * Selects the Microsoft stemming tokenizer for Finnish. + */ + @Generated + public static final MicrosoftStemmingTokenizerLanguage FINNISH = fromString("finnish"); + + /** + * Selects the Microsoft stemming tokenizer for French. + */ + @Generated + public static final MicrosoftStemmingTokenizerLanguage FRENCH = fromString("french"); + + /** + * Selects the Microsoft stemming tokenizer for German. + */ + @Generated + public static final MicrosoftStemmingTokenizerLanguage GERMAN = fromString("german"); + + /** + * Selects the Microsoft stemming tokenizer for Greek. + */ + @Generated + public static final MicrosoftStemmingTokenizerLanguage GREEK = fromString("greek"); + + /** + * Selects the Microsoft stemming tokenizer for Gujarati. + */ + @Generated + public static final MicrosoftStemmingTokenizerLanguage GUJARATI = fromString("gujarati"); + + /** + * Selects the Microsoft stemming tokenizer for Hebrew. + */ + @Generated + public static final MicrosoftStemmingTokenizerLanguage HEBREW = fromString("hebrew"); + + /** + * Selects the Microsoft stemming tokenizer for Hindi. + */ + @Generated + public static final MicrosoftStemmingTokenizerLanguage HINDI = fromString("hindi"); + + /** + * Selects the Microsoft stemming tokenizer for Hungarian. + */ + @Generated + public static final MicrosoftStemmingTokenizerLanguage HUNGARIAN = fromString("hungarian"); + + /** + * Selects the Microsoft stemming tokenizer for Icelandic. + */ + @Generated + public static final MicrosoftStemmingTokenizerLanguage ICELANDIC = fromString("icelandic"); + + /** + * Selects the Microsoft stemming tokenizer for Indonesian. + */ + @Generated + public static final MicrosoftStemmingTokenizerLanguage INDONESIAN = fromString("indonesian"); + + /** + * Selects the Microsoft stemming tokenizer for Italian. + */ + @Generated + public static final MicrosoftStemmingTokenizerLanguage ITALIAN = fromString("italian"); + + /** + * Selects the Microsoft stemming tokenizer for Kannada. + */ + @Generated + public static final MicrosoftStemmingTokenizerLanguage KANNADA = fromString("kannada"); + + /** + * Selects the Microsoft stemming tokenizer for Latvian. + */ + @Generated + public static final MicrosoftStemmingTokenizerLanguage LATVIAN = fromString("latvian"); + + /** + * Selects the Microsoft stemming tokenizer for Lithuanian. + */ + @Generated + public static final MicrosoftStemmingTokenizerLanguage LITHUANIAN = fromString("lithuanian"); + + /** + * Selects the Microsoft stemming tokenizer for Malay. + */ + @Generated + public static final MicrosoftStemmingTokenizerLanguage MALAY = fromString("malay"); + + /** + * Selects the Microsoft stemming tokenizer for Malayalam. + */ + @Generated + public static final MicrosoftStemmingTokenizerLanguage MALAYALAM = fromString("malayalam"); + + /** + * Selects the Microsoft stemming tokenizer for Marathi. + */ + @Generated + public static final MicrosoftStemmingTokenizerLanguage MARATHI = fromString("marathi"); + + /** + * Selects the Microsoft stemming tokenizer for Norwegian (Bokmål). + */ + @Generated + public static final MicrosoftStemmingTokenizerLanguage NORWEGIAN_BOKMAAL = fromString("norwegianBokmaal"); + + /** + * Selects the Microsoft stemming tokenizer for Polish. + */ + @Generated + public static final MicrosoftStemmingTokenizerLanguage POLISH = fromString("polish"); + + /** + * Selects the Microsoft stemming tokenizer for Portuguese. + */ + @Generated + public static final MicrosoftStemmingTokenizerLanguage PORTUGUESE = fromString("portuguese"); + + /** + * Selects the Microsoft stemming tokenizer for Portuguese (Brazil). + */ + @Generated + public static final MicrosoftStemmingTokenizerLanguage PORTUGUESE_BRAZILIAN = fromString("portugueseBrazilian"); + + /** + * Selects the Microsoft stemming tokenizer for Punjabi. + */ + @Generated + public static final MicrosoftStemmingTokenizerLanguage PUNJABI = fromString("punjabi"); + + /** + * Selects the Microsoft stemming tokenizer for Romanian. + */ + @Generated + public static final MicrosoftStemmingTokenizerLanguage ROMANIAN = fromString("romanian"); + + /** + * Selects the Microsoft stemming tokenizer for Russian. + */ + @Generated + public static final MicrosoftStemmingTokenizerLanguage RUSSIAN = fromString("russian"); + + /** + * Selects the Microsoft stemming tokenizer for Serbian (Cyrillic). + */ + @Generated + public static final MicrosoftStemmingTokenizerLanguage SERBIAN_CYRILLIC = fromString("serbianCyrillic"); + + /** + * Selects the Microsoft stemming tokenizer for Serbian (Latin). + */ + @Generated + public static final MicrosoftStemmingTokenizerLanguage SERBIAN_LATIN = fromString("serbianLatin"); + + /** + * Selects the Microsoft stemming tokenizer for Slovak. + */ + @Generated + public static final MicrosoftStemmingTokenizerLanguage SLOVAK = fromString("slovak"); + + /** + * Selects the Microsoft stemming tokenizer for Slovenian. + */ + @Generated + public static final MicrosoftStemmingTokenizerLanguage SLOVENIAN = fromString("slovenian"); + + /** + * Selects the Microsoft stemming tokenizer for Spanish. + */ + @Generated + public static final MicrosoftStemmingTokenizerLanguage SPANISH = fromString("spanish"); + + /** + * Selects the Microsoft stemming tokenizer for Swedish. + */ + @Generated + public static final MicrosoftStemmingTokenizerLanguage SWEDISH = fromString("swedish"); + + /** + * Selects the Microsoft stemming tokenizer for Tamil. + */ + @Generated + public static final MicrosoftStemmingTokenizerLanguage TAMIL = fromString("tamil"); + + /** + * Selects the Microsoft stemming tokenizer for Telugu. + */ + @Generated + public static final MicrosoftStemmingTokenizerLanguage TELUGU = fromString("telugu"); + + /** + * Selects the Microsoft stemming tokenizer for Turkish. + */ + @Generated + public static final MicrosoftStemmingTokenizerLanguage TURKISH = fromString("turkish"); + + /** + * Selects the Microsoft stemming tokenizer for Ukrainian. + */ + @Generated + public static final MicrosoftStemmingTokenizerLanguage UKRAINIAN = fromString("ukrainian"); + + /** + * Selects the Microsoft stemming tokenizer for Urdu. + */ + @Generated + public static final MicrosoftStemmingTokenizerLanguage URDU = fromString("urdu"); + + /** + * Creates a new instance of MicrosoftStemmingTokenizerLanguage value. + * + * @deprecated Use the {@link #fromString(String)} factory method. + */ + @Generated + @Deprecated + public MicrosoftStemmingTokenizerLanguage() { + } + + /** + * Creates or finds a MicrosoftStemmingTokenizerLanguage from its string representation. + * + * @param name a name to look for. + * @return the corresponding MicrosoftStemmingTokenizerLanguage. + */ + @Generated + public static MicrosoftStemmingTokenizerLanguage fromString(String name) { + return fromString(name, MicrosoftStemmingTokenizerLanguage.class); + } + + /** + * Gets known MicrosoftStemmingTokenizerLanguage values. + * + * @return known MicrosoftStemmingTokenizerLanguage values. + */ + @Generated + public static Collection values() { + return values(MicrosoftStemmingTokenizerLanguage.class); + } +} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/MicrosoftTokenizerLanguage.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/MicrosoftTokenizerLanguage.java new file mode 100644 index 000000000000..145033670f90 --- /dev/null +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/MicrosoftTokenizerLanguage.java @@ -0,0 +1,297 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.search.documents.models; + +import com.azure.core.annotation.Generated; +import com.azure.core.util.ExpandableStringEnum; +import java.util.Collection; + +/** + * Lists the languages supported by the Microsoft language tokenizer. + */ +public final class MicrosoftTokenizerLanguage extends ExpandableStringEnum { + /** + * Selects the Microsoft tokenizer for Bangla. + */ + @Generated + public static final MicrosoftTokenizerLanguage BANGLA = fromString("bangla"); + + /** + * Selects the Microsoft tokenizer for Bulgarian. + */ + @Generated + public static final MicrosoftTokenizerLanguage BULGARIAN = fromString("bulgarian"); + + /** + * Selects the Microsoft tokenizer for Catalan. + */ + @Generated + public static final MicrosoftTokenizerLanguage CATALAN = fromString("catalan"); + + /** + * Selects the Microsoft tokenizer for Chinese (Simplified). + */ + @Generated + public static final MicrosoftTokenizerLanguage CHINESE_SIMPLIFIED = fromString("chineseSimplified"); + + /** + * Selects the Microsoft tokenizer for Chinese (Traditional). + */ + @Generated + public static final MicrosoftTokenizerLanguage CHINESE_TRADITIONAL = fromString("chineseTraditional"); + + /** + * Selects the Microsoft tokenizer for Croatian. + */ + @Generated + public static final MicrosoftTokenizerLanguage CROATIAN = fromString("croatian"); + + /** + * Selects the Microsoft tokenizer for Czech. + */ + @Generated + public static final MicrosoftTokenizerLanguage CZECH = fromString("czech"); + + /** + * Selects the Microsoft tokenizer for Danish. + */ + @Generated + public static final MicrosoftTokenizerLanguage DANISH = fromString("danish"); + + /** + * Selects the Microsoft tokenizer for Dutch. + */ + @Generated + public static final MicrosoftTokenizerLanguage DUTCH = fromString("dutch"); + + /** + * Selects the Microsoft tokenizer for English. + */ + @Generated + public static final MicrosoftTokenizerLanguage ENGLISH = fromString("english"); + + /** + * Selects the Microsoft tokenizer for French. + */ + @Generated + public static final MicrosoftTokenizerLanguage FRENCH = fromString("french"); + + /** + * Selects the Microsoft tokenizer for German. + */ + @Generated + public static final MicrosoftTokenizerLanguage GERMAN = fromString("german"); + + /** + * Selects the Microsoft tokenizer for Greek. + */ + @Generated + public static final MicrosoftTokenizerLanguage GREEK = fromString("greek"); + + /** + * Selects the Microsoft tokenizer for Gujarati. + */ + @Generated + public static final MicrosoftTokenizerLanguage GUJARATI = fromString("gujarati"); + + /** + * Selects the Microsoft tokenizer for Hindi. + */ + @Generated + public static final MicrosoftTokenizerLanguage HINDI = fromString("hindi"); + + /** + * Selects the Microsoft tokenizer for Icelandic. + */ + @Generated + public static final MicrosoftTokenizerLanguage ICELANDIC = fromString("icelandic"); + + /** + * Selects the Microsoft tokenizer for Indonesian. + */ + @Generated + public static final MicrosoftTokenizerLanguage INDONESIAN = fromString("indonesian"); + + /** + * Selects the Microsoft tokenizer for Italian. + */ + @Generated + public static final MicrosoftTokenizerLanguage ITALIAN = fromString("italian"); + + /** + * Selects the Microsoft tokenizer for Japanese. + */ + @Generated + public static final MicrosoftTokenizerLanguage JAPANESE = fromString("japanese"); + + /** + * Selects the Microsoft tokenizer for Kannada. + */ + @Generated + public static final MicrosoftTokenizerLanguage KANNADA = fromString("kannada"); + + /** + * Selects the Microsoft tokenizer for Korean. + */ + @Generated + public static final MicrosoftTokenizerLanguage KOREAN = fromString("korean"); + + /** + * Selects the Microsoft tokenizer for Malay. + */ + @Generated + public static final MicrosoftTokenizerLanguage MALAY = fromString("malay"); + + /** + * Selects the Microsoft tokenizer for Malayalam. + */ + @Generated + public static final MicrosoftTokenizerLanguage MALAYALAM = fromString("malayalam"); + + /** + * Selects the Microsoft tokenizer for Marathi. + */ + @Generated + public static final MicrosoftTokenizerLanguage MARATHI = fromString("marathi"); + + /** + * Selects the Microsoft tokenizer for Norwegian (Bokmål). + */ + @Generated + public static final MicrosoftTokenizerLanguage NORWEGIAN_BOKMAAL = fromString("norwegianBokmaal"); + + /** + * Selects the Microsoft tokenizer for Polish. + */ + @Generated + public static final MicrosoftTokenizerLanguage POLISH = fromString("polish"); + + /** + * Selects the Microsoft tokenizer for Portuguese. + */ + @Generated + public static final MicrosoftTokenizerLanguage PORTUGUESE = fromString("portuguese"); + + /** + * Selects the Microsoft tokenizer for Portuguese (Brazil). + */ + @Generated + public static final MicrosoftTokenizerLanguage PORTUGUESE_BRAZILIAN = fromString("portugueseBrazilian"); + + /** + * Selects the Microsoft tokenizer for Punjabi. + */ + @Generated + public static final MicrosoftTokenizerLanguage PUNJABI = fromString("punjabi"); + + /** + * Selects the Microsoft tokenizer for Romanian. + */ + @Generated + public static final MicrosoftTokenizerLanguage ROMANIAN = fromString("romanian"); + + /** + * Selects the Microsoft tokenizer for Russian. + */ + @Generated + public static final MicrosoftTokenizerLanguage RUSSIAN = fromString("russian"); + + /** + * Selects the Microsoft tokenizer for Serbian (Cyrillic). + */ + @Generated + public static final MicrosoftTokenizerLanguage SERBIAN_CYRILLIC = fromString("serbianCyrillic"); + + /** + * Selects the Microsoft tokenizer for Serbian (Latin). + */ + @Generated + public static final MicrosoftTokenizerLanguage SERBIAN_LATIN = fromString("serbianLatin"); + + /** + * Selects the Microsoft tokenizer for Slovenian. + */ + @Generated + public static final MicrosoftTokenizerLanguage SLOVENIAN = fromString("slovenian"); + + /** + * Selects the Microsoft tokenizer for Spanish. + */ + @Generated + public static final MicrosoftTokenizerLanguage SPANISH = fromString("spanish"); + + /** + * Selects the Microsoft tokenizer for Swedish. + */ + @Generated + public static final MicrosoftTokenizerLanguage SWEDISH = fromString("swedish"); + + /** + * Selects the Microsoft tokenizer for Tamil. + */ + @Generated + public static final MicrosoftTokenizerLanguage TAMIL = fromString("tamil"); + + /** + * Selects the Microsoft tokenizer for Telugu. + */ + @Generated + public static final MicrosoftTokenizerLanguage TELUGU = fromString("telugu"); + + /** + * Selects the Microsoft tokenizer for Thai. + */ + @Generated + public static final MicrosoftTokenizerLanguage THAI = fromString("thai"); + + /** + * Selects the Microsoft tokenizer for Ukrainian. + */ + @Generated + public static final MicrosoftTokenizerLanguage UKRAINIAN = fromString("ukrainian"); + + /** + * Selects the Microsoft tokenizer for Urdu. + */ + @Generated + public static final MicrosoftTokenizerLanguage URDU = fromString("urdu"); + + /** + * Selects the Microsoft tokenizer for Vietnamese. + */ + @Generated + public static final MicrosoftTokenizerLanguage VIETNAMESE = fromString("vietnamese"); + + /** + * Creates a new instance of MicrosoftTokenizerLanguage value. + * + * @deprecated Use the {@link #fromString(String)} factory method. + */ + @Generated + @Deprecated + public MicrosoftTokenizerLanguage() { + } + + /** + * Creates or finds a MicrosoftTokenizerLanguage from its string representation. + * + * @param name a name to look for. + * @return the corresponding MicrosoftTokenizerLanguage. + */ + @Generated + public static MicrosoftTokenizerLanguage fromString(String name) { + return fromString(name, MicrosoftTokenizerLanguage.class); + } + + /** + * Gets known MicrosoftTokenizerLanguage values. + * + * @return known MicrosoftTokenizerLanguage values. + */ + @Generated + public static Collection values() { + return values(MicrosoftTokenizerLanguage.class); + } +} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/implementation/models/NGramTokenFilterV2.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/NGramTokenFilterV2.java similarity index 77% rename from sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/implementation/models/NGramTokenFilterV2.java rename to sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/NGramTokenFilterV2.java index 2275ef3a767e..47f02c8e2929 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/implementation/models/NGramTokenFilterV2.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/NGramTokenFilterV2.java @@ -1,36 +1,39 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) TypeSpec Code Generator. -package com.azure.search.documents.indexes.implementation.models; +package com.azure.search.documents.models; import com.azure.core.annotation.Fluent; +import com.azure.core.annotation.Generated; import com.azure.json.JsonReader; import com.azure.json.JsonToken; import com.azure.json.JsonWriter; -import com.azure.search.documents.indexes.models.TokenFilter; import java.io.IOException; /** - * Generates n-grams of the given size(s). This token filter is implemented using Apache Lucene. + * Generates n-grams of the given size(s). This token filter is implemented using + * Apache Lucene. */ @Fluent public final class NGramTokenFilterV2 extends TokenFilter { /* - * A URI fragment specifying the type of token filter. + * The discriminator for derived types. */ + @Generated private String odataType = "#Microsoft.Azure.Search.NGramTokenFilterV2"; /* - * The minimum n-gram length. Default is 1. Maximum is 300. Must be less than the value of maxGram. + * The minimum n-gram length. Default is 1. Maximum is 300. Must be less than the + * value of maxGram. */ + @Generated private Integer minGram; /* * The maximum n-gram length. Default is 2. Maximum is 300. */ + @Generated private Integer maxGram; /** @@ -38,37 +41,41 @@ public final class NGramTokenFilterV2 extends TokenFilter { * * @param name the name value to set. */ + @Generated public NGramTokenFilterV2(String name) { super(name); } /** - * Get the odataType property: A URI fragment specifying the type of token filter. + * Get the odataType property: The discriminator for derived types. * * @return the odataType value. */ + @Generated @Override public String getOdataType() { return this.odataType; } /** - * Get the minGram property: The minimum n-gram length. Default is 1. Maximum is 300. Must be less than the value of - * maxGram. + * Get the minGram property: The minimum n-gram length. Default is 1. Maximum is 300. Must be less than the + * value of maxGram. * * @return the minGram value. */ + @Generated public Integer getMinGram() { return this.minGram; } /** - * Set the minGram property: The minimum n-gram length. Default is 1. Maximum is 300. Must be less than the value of - * maxGram. + * Set the minGram property: The minimum n-gram length. Default is 1. Maximum is 300. Must be less than the + * value of maxGram. * * @param minGram the minGram value to set. * @return the NGramTokenFilterV2 object itself. */ + @Generated public NGramTokenFilterV2 setMinGram(Integer minGram) { this.minGram = minGram; return this; @@ -79,6 +86,7 @@ public NGramTokenFilterV2 setMinGram(Integer minGram) { * * @return the maxGram value. */ + @Generated public Integer getMaxGram() { return this.maxGram; } @@ -89,6 +97,7 @@ public Integer getMaxGram() { * @param maxGram the maxGram value to set. * @return the NGramTokenFilterV2 object itself. */ + @Generated public NGramTokenFilterV2 setMaxGram(Integer maxGram) { this.maxGram = maxGram; return this; @@ -97,6 +106,7 @@ public NGramTokenFilterV2 setMaxGram(Integer maxGram) { /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); @@ -116,9 +126,9 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { * @throws IllegalStateException If the deserialized JSON object was missing any required properties. * @throws IOException If an error occurs while reading the NGramTokenFilterV2. */ + @Generated public static NGramTokenFilterV2 fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { - boolean nameFound = false; String name = null; String odataType = "#Microsoft.Azure.Search.NGramTokenFilterV2"; Integer minGram = null; @@ -129,7 +139,6 @@ public static NGramTokenFilterV2 fromJson(JsonReader jsonReader) throws IOExcept if ("name".equals(fieldName)) { name = reader.getString(); - nameFound = true; } else if ("@odata.type".equals(fieldName)) { odataType = reader.getString(); } else if ("minGram".equals(fieldName)) { @@ -140,15 +149,12 @@ public static NGramTokenFilterV2 fromJson(JsonReader jsonReader) throws IOExcept reader.skipChildren(); } } - if (nameFound) { - NGramTokenFilterV2 deserializedNGramTokenFilterV2 = new NGramTokenFilterV2(name); - deserializedNGramTokenFilterV2.odataType = odataType; - deserializedNGramTokenFilterV2.minGram = minGram; - deserializedNGramTokenFilterV2.maxGram = maxGram; + NGramTokenFilterV2 deserializedNGramTokenFilterV2 = new NGramTokenFilterV2(name); + deserializedNGramTokenFilterV2.odataType = odataType; + deserializedNGramTokenFilterV2.minGram = minGram; + deserializedNGramTokenFilterV2.maxGram = maxGram; - return deserializedNGramTokenFilterV2; - } - throw new IllegalStateException("Missing required property: name"); + return deserializedNGramTokenFilterV2; }); } } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/NGramTokenizer.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/NGramTokenizer.java similarity index 75% rename from sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/NGramTokenizer.java rename to sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/NGramTokenizer.java index a3e6cdccba0a..4be9c9ba282e 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/NGramTokenizer.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/NGramTokenizer.java @@ -1,80 +1,88 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. -package com.azure.search.documents.indexes.models; +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.search.documents.models; import com.azure.core.annotation.Fluent; +import com.azure.core.annotation.Generated; import com.azure.json.JsonReader; import com.azure.json.JsonToken; import com.azure.json.JsonWriter; import java.io.IOException; -import java.util.Arrays; import java.util.List; /** - * Tokenizes the input into n-grams of the given size(s). This tokenizer is implemented using Apache Lucene. + * Tokenizes the input into n-grams of the given size(s). This tokenizer is + * implemented using Apache Lucene. */ @Fluent public final class NGramTokenizer extends LexicalTokenizer { - /* - * A URI fragment specifying the type of tokenizer. + * The discriminator for derived types. */ + @Generated private String odataType = "#Microsoft.Azure.Search.NGramTokenizer"; /* - * The minimum n-gram length. Default is 1. Maximum is 300. Must be less than the value of maxGram. + * The minimum n-gram length. Default is 1. Maximum is 300. Must be less than the + * value of maxGram. */ + @Generated private Integer minGram; /* * The maximum n-gram length. Default is 2. Maximum is 300. */ + @Generated private Integer maxGram; /* * Character classes to keep in the tokens. */ + @Generated private List tokenChars; /** * Creates an instance of NGramTokenizer class. - * + * * @param name the name value to set. */ + @Generated public NGramTokenizer(String name) { super(name); } /** - * Get the odataType property: A URI fragment specifying the type of tokenizer. - * + * Get the odataType property: The discriminator for derived types. + * * @return the odataType value. */ + @Generated @Override public String getOdataType() { return this.odataType; } /** - * Get the minGram property: The minimum n-gram length. Default is 1. Maximum is 300. Must be less than the value of - * maxGram. - * + * Get the minGram property: The minimum n-gram length. Default is 1. Maximum is 300. Must be less than the + * value of maxGram. + * * @return the minGram value. */ + @Generated public Integer getMinGram() { return this.minGram; } /** - * Set the minGram property: The minimum n-gram length. Default is 1. Maximum is 300. Must be less than the value of - * maxGram. - * + * Set the minGram property: The minimum n-gram length. Default is 1. Maximum is 300. Must be less than the + * value of maxGram. + * * @param minGram the minGram value to set. * @return the NGramTokenizer object itself. */ + @Generated public NGramTokenizer setMinGram(Integer minGram) { this.minGram = minGram; return this; @@ -82,19 +90,21 @@ public NGramTokenizer setMinGram(Integer minGram) { /** * Get the maxGram property: The maximum n-gram length. Default is 2. Maximum is 300. - * + * * @return the maxGram value. */ + @Generated public Integer getMaxGram() { return this.maxGram; } /** * Set the maxGram property: The maximum n-gram length. Default is 2. Maximum is 300. - * + * * @param maxGram the maxGram value to set. * @return the NGramTokenizer object itself. */ + @Generated public NGramTokenizer setMaxGram(Integer maxGram) { this.maxGram = maxGram; return this; @@ -102,19 +112,21 @@ public NGramTokenizer setMaxGram(Integer maxGram) { /** * Get the tokenChars property: Character classes to keep in the tokens. - * + * * @return the tokenChars value. */ + @Generated public List getTokenChars() { return this.tokenChars; } /** * Set the tokenChars property: Character classes to keep in the tokens. - * + * * @param tokenChars the tokenChars value to set. * @return the NGramTokenizer object itself. */ + @Generated public NGramTokenizer setTokenChars(List tokenChars) { this.tokenChars = tokenChars; return this; @@ -123,6 +135,7 @@ public NGramTokenizer setTokenChars(List tokenChars) { /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); @@ -137,16 +150,16 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of NGramTokenizer from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of NGramTokenizer if the JsonReader was pointing to an instance of it, or null if it was * pointing to JSON null. * @throws IllegalStateException If the deserialized JSON object was missing any required properties. * @throws IOException If an error occurs while reading the NGramTokenizer. */ + @Generated public static NGramTokenizer fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { - boolean nameFound = false; String name = null; String odataType = "#Microsoft.Azure.Search.NGramTokenizer"; Integer minGram = null; @@ -155,9 +168,9 @@ public static NGramTokenizer fromJson(JsonReader jsonReader) throws IOException while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); + if ("name".equals(fieldName)) { name = reader.getString(); - nameFound = true; } else if ("@odata.type".equals(fieldName)) { odataType = reader.getString(); } else if ("minGram".equals(fieldName)) { @@ -170,26 +183,13 @@ public static NGramTokenizer fromJson(JsonReader jsonReader) throws IOException reader.skipChildren(); } } - if (nameFound) { - NGramTokenizer deserializedNGramTokenizer = new NGramTokenizer(name); - deserializedNGramTokenizer.odataType = odataType; - deserializedNGramTokenizer.minGram = minGram; - deserializedNGramTokenizer.maxGram = maxGram; - deserializedNGramTokenizer.tokenChars = tokenChars; - return deserializedNGramTokenizer; - } - throw new IllegalStateException("Missing required property: name"); - }); - } + NGramTokenizer deserializedNGramTokenizer = new NGramTokenizer(name); + deserializedNGramTokenizer.odataType = odataType; + deserializedNGramTokenizer.minGram = minGram; + deserializedNGramTokenizer.maxGram = maxGram; + deserializedNGramTokenizer.tokenChars = tokenChars; - /** - * Set the tokenChars property: Character classes to keep in the tokens. - * - * @param tokenChars the tokenChars value to set. - * @return the NGramTokenizer object itself. - */ - public NGramTokenizer setTokenChars(TokenCharacterKind... tokenChars) { - this.tokenChars = (tokenChars == null) ? null : Arrays.asList(tokenChars); - return this; + return deserializedNGramTokenizer; + }); } } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/NativeBlobSoftDeleteDeletionDetectionPolicy.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/NativeBlobSoftDeleteDeletionDetectionPolicy.java similarity index 84% rename from sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/NativeBlobSoftDeleteDeletionDetectionPolicy.java rename to sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/NativeBlobSoftDeleteDeletionDetectionPolicy.java index 18728bd48a70..9146166899df 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/NativeBlobSoftDeleteDeletionDetectionPolicy.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/NativeBlobSoftDeleteDeletionDetectionPolicy.java @@ -1,11 +1,10 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) TypeSpec Code Generator. -package com.azure.search.documents.indexes.models; +package com.azure.search.documents.models; +import com.azure.core.annotation.Generated; import com.azure.core.annotation.Immutable; import com.azure.json.JsonReader; import com.azure.json.JsonToken; @@ -13,27 +12,30 @@ import java.io.IOException; /** - * Defines a data deletion detection policy utilizing Azure Blob Storage's native soft delete feature for deletion - * detection. + * Defines a data deletion detection policy utilizing Azure Blob Storage's native + * soft delete feature for deletion detection. */ @Immutable public final class NativeBlobSoftDeleteDeletionDetectionPolicy extends DataDeletionDetectionPolicy { /* - * A URI fragment specifying the type of data deletion detection policy. + * The discriminator for derived types. */ + @Generated private String odataType = "#Microsoft.Azure.Search.NativeBlobSoftDeleteDeletionDetectionPolicy"; /** * Creates an instance of NativeBlobSoftDeleteDeletionDetectionPolicy class. */ + @Generated public NativeBlobSoftDeleteDeletionDetectionPolicy() { } /** - * Get the odataType property: A URI fragment specifying the type of data deletion detection policy. + * Get the odataType property: The discriminator for derived types. * * @return the odataType value. */ + @Generated @Override public String getOdataType() { return this.odataType; @@ -42,6 +44,7 @@ public String getOdataType() { /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); @@ -57,6 +60,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { * of it, or null if it was pointing to JSON null. * @throws IOException If an error occurs while reading the NativeBlobSoftDeleteDeletionDetectionPolicy. */ + @Generated public static NativeBlobSoftDeleteDeletionDetectionPolicy fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { NativeBlobSoftDeleteDeletionDetectionPolicy deserializedNativeBlobSoftDeleteDeletionDetectionPolicy diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/OcrLineEnding.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/OcrLineEnding.java similarity index 84% rename from sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/OcrLineEnding.java rename to sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/OcrLineEnding.java index 4b72a2315f9f..6a4c9234071d 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/OcrLineEnding.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/OcrLineEnding.java @@ -1,37 +1,40 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) TypeSpec Code Generator. -package com.azure.search.documents.indexes.models; +package com.azure.search.documents.models; +import com.azure.core.annotation.Generated; import com.azure.core.util.ExpandableStringEnum; import java.util.Collection; /** - * Defines the sequence of characters to use between the lines of text recognized by the OCR skill. The default value is - * "space". + * Defines the sequence of characters to use between the lines of text recognized + * by the OCR skill. The default value is "space". */ public final class OcrLineEnding extends ExpandableStringEnum { /** * Lines are separated by a single space character. */ + @Generated public static final OcrLineEnding SPACE = fromString("space"); /** * Lines are separated by a carriage return ('\r') character. */ + @Generated public static final OcrLineEnding CARRIAGE_RETURN = fromString("carriageReturn"); /** * Lines are separated by a single line feed ('\n') character. */ + @Generated public static final OcrLineEnding LINE_FEED = fromString("lineFeed"); /** * Lines are separated by a carriage return and a line feed ('\r\n') character. */ + @Generated public static final OcrLineEnding CARRIAGE_RETURN_LINE_FEED = fromString("carriageReturnLineFeed"); /** @@ -39,6 +42,7 @@ public final class OcrLineEnding extends ExpandableStringEnum { * * @deprecated Use the {@link #fromString(String)} factory method. */ + @Generated @Deprecated public OcrLineEnding() { } @@ -49,6 +53,7 @@ public OcrLineEnding() { * @param name a name to look for. * @return the corresponding OcrLineEnding. */ + @Generated public static OcrLineEnding fromString(String name) { return fromString(name, OcrLineEnding.class); } @@ -58,6 +63,7 @@ public static OcrLineEnding fromString(String name) { * * @return known OcrLineEnding values. */ + @Generated public static Collection values() { return values(OcrLineEnding.class); } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/OcrSkill.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/OcrSkill.java similarity index 75% rename from sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/OcrSkill.java rename to sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/OcrSkill.java index e833141bbf38..e94d75345d32 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/OcrSkill.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/OcrSkill.java @@ -1,16 +1,15 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. -package com.azure.search.documents.indexes.models; +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.search.documents.models; import com.azure.core.annotation.Fluent; +import com.azure.core.annotation.Generated; import com.azure.json.JsonReader; import com.azure.json.JsonToken; import com.azure.json.JsonWriter; import java.io.IOException; -import java.util.ArrayList; import java.util.List; /** @@ -18,43 +17,48 @@ */ @Fluent public final class OcrSkill extends SearchIndexerSkill { - /* - * A URI fragment specifying the type of skill. + * The discriminator for derived types. */ + @Generated private String odataType = "#Microsoft.Skills.Vision.OcrSkill"; /* * A value indicating which language code to use. Default is `en`. */ + @Generated private OcrSkillLanguage defaultLanguageCode; /* * A value indicating to turn orientation detection on or not. Default is false. */ + @Generated private Boolean shouldDetectOrientation; /* - * Defines the sequence of characters to use between the lines of text recognized by the OCR skill. The default - * value is "space". + * Defines the sequence of characters to use between the lines of text recognized + * by the OCR skill. The default value is "space". */ + @Generated private OcrLineEnding lineEnding; /** * Creates an instance of OcrSkill class. - * + * * @param inputs the inputs value to set. * @param outputs the outputs value to set. */ + @Generated public OcrSkill(List inputs, List outputs) { super(inputs, outputs); } /** - * Get the odataType property: A URI fragment specifying the type of skill. - * + * Get the odataType property: The discriminator for derived types. + * * @return the odataType value. */ + @Generated @Override public String getOdataType() { return this.odataType; @@ -62,19 +66,21 @@ public String getOdataType() { /** * Get the defaultLanguageCode property: A value indicating which language code to use. Default is `en`. - * + * * @return the defaultLanguageCode value. */ + @Generated public OcrSkillLanguage getDefaultLanguageCode() { return this.defaultLanguageCode; } /** * Set the defaultLanguageCode property: A value indicating which language code to use. Default is `en`. - * + * * @param defaultLanguageCode the defaultLanguageCode value to set. * @return the OcrSkill object itself. */ + @Generated public OcrSkill setDefaultLanguageCode(OcrSkillLanguage defaultLanguageCode) { this.defaultLanguageCode = defaultLanguageCode; return this; @@ -83,9 +89,10 @@ public OcrSkill setDefaultLanguageCode(OcrSkillLanguage defaultLanguageCode) { /** * Get the shouldDetectOrientation property: A value indicating to turn orientation detection on or not. Default is * false. - * + * * @return the shouldDetectOrientation value. */ + @Generated public Boolean isShouldDetectOrientation() { return this.shouldDetectOrientation; } @@ -93,32 +100,35 @@ public Boolean isShouldDetectOrientation() { /** * Set the shouldDetectOrientation property: A value indicating to turn orientation detection on or not. Default is * false. - * + * * @param shouldDetectOrientation the shouldDetectOrientation value to set. * @return the OcrSkill object itself. */ + @Generated public OcrSkill setShouldDetectOrientation(Boolean shouldDetectOrientation) { this.shouldDetectOrientation = shouldDetectOrientation; return this; } /** - * Get the lineEnding property: Defines the sequence of characters to use between the lines of text recognized by - * the OCR skill. The default value is "space". - * + * Get the lineEnding property: Defines the sequence of characters to use between the lines of text recognized + * by the OCR skill. The default value is "space". + * * @return the lineEnding value. */ + @Generated public OcrLineEnding getLineEnding() { return this.lineEnding; } /** - * Set the lineEnding property: Defines the sequence of characters to use between the lines of text recognized by - * the OCR skill. The default value is "space". - * + * Set the lineEnding property: Defines the sequence of characters to use between the lines of text recognized + * by the OCR skill. The default value is "space". + * * @param lineEnding the lineEnding value to set. * @return the OcrSkill object itself. */ + @Generated public OcrSkill setLineEnding(OcrLineEnding lineEnding) { this.lineEnding = lineEnding; return this; @@ -127,6 +137,7 @@ public OcrSkill setLineEnding(OcrLineEnding lineEnding) { /** * {@inheritDoc} */ + @Generated @Override public OcrSkill setName(String name) { super.setName(name); @@ -136,6 +147,7 @@ public OcrSkill setName(String name) { /** * {@inheritDoc} */ + @Generated @Override public OcrSkill setDescription(String description) { super.setDescription(description); @@ -145,6 +157,7 @@ public OcrSkill setDescription(String description) { /** * {@inheritDoc} */ + @Generated @Override public OcrSkill setContext(String context) { super.setContext(context); @@ -154,6 +167,7 @@ public OcrSkill setContext(String context) { /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); @@ -172,18 +186,17 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of OcrSkill from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of OcrSkill if the JsonReader was pointing to an instance of it, or null if it was pointing * to JSON null. * @throws IllegalStateException If the deserialized JSON object was missing any required properties. * @throws IOException If an error occurs while reading the OcrSkill. */ + @Generated public static OcrSkill fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { - boolean inputsFound = false; List inputs = null; - boolean outputsFound = false; List outputs = null; String name = null; String description = null; @@ -195,12 +208,11 @@ public static OcrSkill fromJson(JsonReader jsonReader) throws IOException { while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); + if ("inputs".equals(fieldName)) { inputs = reader.readArray(reader1 -> InputFieldMappingEntry.fromJson(reader1)); - inputsFound = true; } else if ("outputs".equals(fieldName)) { outputs = reader.readArray(reader1 -> OutputFieldMappingEntry.fromJson(reader1)); - outputsFound = true; } else if ("name".equals(fieldName)) { name = reader.getString(); } else if ("description".equals(fieldName)) { @@ -219,38 +231,16 @@ public static OcrSkill fromJson(JsonReader jsonReader) throws IOException { reader.skipChildren(); } } - if (inputsFound && outputsFound) { - OcrSkill deserializedOcrSkill = new OcrSkill(inputs, outputs); - deserializedOcrSkill.setName(name); - deserializedOcrSkill.setDescription(description); - deserializedOcrSkill.setContext(context); - deserializedOcrSkill.odataType = odataType; - deserializedOcrSkill.defaultLanguageCode = defaultLanguageCode; - deserializedOcrSkill.shouldDetectOrientation = shouldDetectOrientation; - deserializedOcrSkill.lineEnding = lineEnding; - return deserializedOcrSkill; - } - List missingProperties = new ArrayList<>(); - if (!inputsFound) { - missingProperties.add("inputs"); - } - if (!outputsFound) { - missingProperties.add("outputs"); - } - throw new IllegalStateException( - "Missing required property/properties: " + String.join(", ", missingProperties)); + OcrSkill deserializedOcrSkill = new OcrSkill(inputs, outputs); + deserializedOcrSkill.setName(name); + deserializedOcrSkill.setDescription(description); + deserializedOcrSkill.setContext(context); + deserializedOcrSkill.odataType = odataType; + deserializedOcrSkill.defaultLanguageCode = defaultLanguageCode; + deserializedOcrSkill.shouldDetectOrientation = shouldDetectOrientation; + deserializedOcrSkill.lineEnding = lineEnding; + + return deserializedOcrSkill; }); } - - /** - * Get the shouldDetectOrientation property: A value indicating to turn orientation detection on or not. Default is - * false. - * - * @return the shouldDetectOrientation value. - * @deprecated Use {@link #isShouldDetectOrientation()} instead. - */ - @Deprecated() - public Boolean setShouldDetectOrientation() { - return this.shouldDetectOrientation; - } } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/OcrSkillLanguage.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/OcrSkillLanguage.java similarity index 87% rename from sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/OcrSkillLanguage.java rename to sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/OcrSkillLanguage.java index 12728427e403..7212b73531b4 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/OcrSkillLanguage.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/OcrSkillLanguage.java @@ -1,11 +1,10 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) TypeSpec Code Generator. -package com.azure.search.documents.indexes.models; +package com.azure.search.documents.models; +import com.azure.core.annotation.Generated; import com.azure.core.util.ExpandableStringEnum; import java.util.Collection; @@ -16,851 +15,1021 @@ public final class OcrSkillLanguage extends ExpandableStringEnum values() { return values(OcrSkillLanguage.class); } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/OutputFieldMappingEntry.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/OutputFieldMappingEntry.java similarity index 83% rename from sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/OutputFieldMappingEntry.java rename to sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/OutputFieldMappingEntry.java index 4d92b19c4151..82854e44bd0c 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/OutputFieldMappingEntry.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/OutputFieldMappingEntry.java @@ -1,12 +1,11 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) TypeSpec Code Generator. -package com.azure.search.documents.indexes.models; +package com.azure.search.documents.models; import com.azure.core.annotation.Fluent; +import com.azure.core.annotation.Generated; import com.azure.json.JsonReader; import com.azure.json.JsonSerializable; import com.azure.json.JsonToken; @@ -21,11 +20,13 @@ public final class OutputFieldMappingEntry implements JsonSerializable { - boolean nameFound = false; String name = null; String targetName = null; while (reader.nextToken() != JsonToken.END_OBJECT) { @@ -97,20 +103,16 @@ public static OutputFieldMappingEntry fromJson(JsonReader jsonReader) throws IOE if ("name".equals(fieldName)) { name = reader.getString(); - nameFound = true; } else if ("targetName".equals(fieldName)) { targetName = reader.getString(); } else { reader.skipChildren(); } } - if (nameFound) { - OutputFieldMappingEntry deserializedOutputFieldMappingEntry = new OutputFieldMappingEntry(name); - deserializedOutputFieldMappingEntry.targetName = targetName; + OutputFieldMappingEntry deserializedOutputFieldMappingEntry = new OutputFieldMappingEntry(name); + deserializedOutputFieldMappingEntry.targetName = targetName; - return deserializedOutputFieldMappingEntry; - } - throw new IllegalStateException("Missing required property: name"); + return deserializedOutputFieldMappingEntry; }); } } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/PiiDetectionSkill.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/PIIDetectionSkill.java similarity index 64% rename from sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/PiiDetectionSkill.java rename to sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/PIIDetectionSkill.java index 1462cc8e6583..fcfa8c7b7ab8 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/PiiDetectionSkill.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/PIIDetectionSkill.java @@ -1,84 +1,95 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) TypeSpec Code Generator. -package com.azure.search.documents.indexes.models; +package com.azure.search.documents.models; import com.azure.core.annotation.Fluent; +import com.azure.core.annotation.Generated; import com.azure.json.JsonReader; import com.azure.json.JsonToken; import com.azure.json.JsonWriter; import java.io.IOException; -import java.util.ArrayList; import java.util.List; /** - * Using the Text Analytics API, extracts personal information from an input text and gives you the option of masking - * it. + * Using the Text Analytics API, extracts personal information from an input text + * and gives you the option of masking it. */ @Fluent -public final class PiiDetectionSkill extends SearchIndexerSkill { +public final class PIIDetectionSkill extends SearchIndexerSkill { /* - * A URI fragment specifying the type of skill. + * The discriminator for derived types. */ + @Generated private String odataType = "#Microsoft.Skills.Text.PIIDetectionSkill"; /* * A value indicating which language code to use. Default is `en`. */ + @Generated private String defaultLanguageCode; /* - * 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. + * 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. */ + @Generated private Double minimumPrecision; /* - * A parameter that provides various ways to mask the personal information detected in the input text. Default is - * 'none'. + * A parameter that provides various ways to mask the personal information + * detected in the input text. Default is 'none'. */ - private PiiDetectionSkillMaskingMode maskingMode; + @Generated + private PIIDetectionSkillMaskingMode maskingMode; /* - * The character used to mask the text if the maskingMode parameter is set to replace. Default is '*'. + * The character used to mask the text if the maskingMode parameter is set to + * replace. Default is '*'. */ + @Generated private String mask; /* - * 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. + * 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. */ + @Generated private String modelVersion; /* * A list of PII entity categories that should be extracted and masked. */ + @Generated private List piiCategories; /* - * If specified, will set the PII domain to include only a subset of the entity categories. Possible values include: - * 'phi', 'none'. Default is 'none'. + * If specified, will set the PII domain to include only a subset of the entity + * categories. Possible values include: 'phi', 'none'. Default is 'none'. */ + @Generated private String domain; /** - * Creates an instance of PiiDetectionSkill class. + * Creates an instance of PIIDetectionSkill class. * * @param inputs the inputs value to set. * @param outputs the outputs value to set. */ - public PiiDetectionSkill(List inputs, List outputs) { + @Generated + public PIIDetectionSkill(List inputs, List outputs) { super(inputs, outputs); } /** - * Get the odataType property: A URI fragment specifying the type of skill. + * Get the odataType property: The discriminator for derived types. * * @return the odataType value. */ + @Generated @Override public String getOdataType() { return this.odataType; @@ -89,6 +100,7 @@ public String getOdataType() { * * @return the defaultLanguageCode value. */ + @Generated public String getDefaultLanguageCode() { return this.defaultLanguageCode; } @@ -97,101 +109,110 @@ public String getDefaultLanguageCode() { * Set the defaultLanguageCode property: A value indicating which language code to use. Default is `en`. * * @param defaultLanguageCode the defaultLanguageCode value to set. - * @return the PiiDetectionSkill object itself. + * @return the PIIDetectionSkill object itself. */ - public PiiDetectionSkill setDefaultLanguageCode(String defaultLanguageCode) { + @Generated + public PIIDetectionSkill setDefaultLanguageCode(String defaultLanguageCode) { this.defaultLanguageCode = defaultLanguageCode; return this; } /** * Get the minimumPrecision property: 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. + * score is greater than the value specified. If not set (default), or if + * explicitly set to null, all entities will be included. * * @return the minimumPrecision value. */ + @Generated public Double getMinimumPrecision() { return this.minimumPrecision; } /** * Set the minimumPrecision property: 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. + * score is greater than the value specified. If not set (default), or if + * explicitly set to null, all entities will be included. * * @param minimumPrecision the minimumPrecision value to set. - * @return the PiiDetectionSkill object itself. + * @return the PIIDetectionSkill object itself. */ - public PiiDetectionSkill setMinimumPrecision(Double minimumPrecision) { + @Generated + public PIIDetectionSkill setMinimumPrecision(Double minimumPrecision) { this.minimumPrecision = minimumPrecision; return this; } /** - * Get the maskingMode property: A parameter that provides various ways to mask the personal information detected in - * the input text. Default is 'none'. + * Get the maskingMode property: A parameter that provides various ways to mask the personal information + * detected in the input text. Default is 'none'. * * @return the maskingMode value. */ - public PiiDetectionSkillMaskingMode getMaskingMode() { + @Generated + public PIIDetectionSkillMaskingMode getMaskingMode() { return this.maskingMode; } /** - * Set the maskingMode property: A parameter that provides various ways to mask the personal information detected in - * the input text. Default is 'none'. + * Set the maskingMode property: A parameter that provides various ways to mask the personal information + * detected in the input text. Default is 'none'. * * @param maskingMode the maskingMode value to set. - * @return the PiiDetectionSkill object itself. + * @return the PIIDetectionSkill object itself. */ - public PiiDetectionSkill setMaskingMode(PiiDetectionSkillMaskingMode maskingMode) { + @Generated + public PIIDetectionSkill setMaskingMode(PIIDetectionSkillMaskingMode maskingMode) { this.maskingMode = maskingMode; return this; } /** - * Get the mask property: The character used to mask the text if the maskingMode parameter is set to replace. - * Default is '*'. + * Get the mask property: The character used to mask the text if the maskingMode parameter is set to + * replace. Default is '*'. * * @return the mask value. */ + @Generated public String getMask() { return this.mask; } /** - * Set the mask property: The character used to mask the text if the maskingMode parameter is set to replace. - * Default is '*'. + * Set the mask property: The character used to mask the text if the maskingMode parameter is set to + * replace. Default is '*'. * * @param mask the mask value to set. - * @return the PiiDetectionSkill object itself. + * @return the PIIDetectionSkill object itself. */ - public PiiDetectionSkill setMask(String mask) { + @Generated + public PIIDetectionSkill setMask(String mask) { this.mask = mask; return this; } /** - * Get the modelVersion property: 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. + * Get the modelVersion property: 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. * * @return the modelVersion value. */ + @Generated public String getModelVersion() { return this.modelVersion; } /** - * Set the modelVersion property: 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. + * Set the modelVersion property: 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. * * @param modelVersion the modelVersion value to set. - * @return the PiiDetectionSkill object itself. + * @return the PIIDetectionSkill object itself. */ - public PiiDetectionSkill setModelVersion(String modelVersion) { + @Generated + public PIIDetectionSkill setModelVersion(String modelVersion) { this.modelVersion = modelVersion; return this; } @@ -201,6 +222,7 @@ public PiiDetectionSkill setModelVersion(String modelVersion) { * * @return the piiCategories value. */ + @Generated public List getPiiCategories() { return this.piiCategories; } @@ -209,31 +231,34 @@ public List getPiiCategories() { * Set the piiCategories property: A list of PII entity categories that should be extracted and masked. * * @param piiCategories the piiCategories value to set. - * @return the PiiDetectionSkill object itself. + * @return the PIIDetectionSkill object itself. */ - public PiiDetectionSkill setPiiCategories(List piiCategories) { + @Generated + public PIIDetectionSkill setPiiCategories(List piiCategories) { this.piiCategories = piiCategories; return this; } /** - * Get the domain property: If specified, will set the PII domain to include only a subset of the entity categories. - * Possible values include: 'phi', 'none'. Default is 'none'. + * Get the domain property: If specified, will set the PII domain to include only a subset of the entity + * categories. Possible values include: 'phi', 'none'. Default is 'none'. * * @return the domain value. */ + @Generated public String getDomain() { return this.domain; } /** - * Set the domain property: If specified, will set the PII domain to include only a subset of the entity categories. - * Possible values include: 'phi', 'none'. Default is 'none'. + * Set the domain property: If specified, will set the PII domain to include only a subset of the entity + * categories. Possible values include: 'phi', 'none'. Default is 'none'. * * @param domain the domain value to set. - * @return the PiiDetectionSkill object itself. + * @return the PIIDetectionSkill object itself. */ - public PiiDetectionSkill setDomain(String domain) { + @Generated + public PIIDetectionSkill setDomain(String domain) { this.domain = domain; return this; } @@ -241,8 +266,9 @@ public PiiDetectionSkill setDomain(String domain) { /** * {@inheritDoc} */ + @Generated @Override - public PiiDetectionSkill setName(String name) { + public PIIDetectionSkill setName(String name) { super.setName(name); return this; } @@ -250,8 +276,9 @@ public PiiDetectionSkill setName(String name) { /** * {@inheritDoc} */ + @Generated @Override - public PiiDetectionSkill setDescription(String description) { + public PIIDetectionSkill setDescription(String description) { super.setDescription(description); return this; } @@ -259,8 +286,9 @@ public PiiDetectionSkill setDescription(String description) { /** * {@inheritDoc} */ + @Generated @Override - public PiiDetectionSkill setContext(String context) { + public PIIDetectionSkill setContext(String context) { super.setContext(context); return this; } @@ -268,6 +296,7 @@ public PiiDetectionSkill setContext(String context) { /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); @@ -289,19 +318,18 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { } /** - * Reads an instance of PiiDetectionSkill from the JsonReader. + * Reads an instance of PIIDetectionSkill from the JsonReader. * * @param jsonReader The JsonReader being read. - * @return An instance of PiiDetectionSkill if the JsonReader was pointing to an instance of it, or null if it was + * @return An instance of PIIDetectionSkill if the JsonReader was pointing to an instance of it, or null if it was * pointing to JSON null. * @throws IllegalStateException If the deserialized JSON object was missing any required properties. - * @throws IOException If an error occurs while reading the PiiDetectionSkill. + * @throws IOException If an error occurs while reading the PIIDetectionSkill. */ - public static PiiDetectionSkill fromJson(JsonReader jsonReader) throws IOException { + @Generated + public static PIIDetectionSkill fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { - boolean inputsFound = false; List inputs = null; - boolean outputsFound = false; List outputs = null; String name = null; String description = null; @@ -309,7 +337,7 @@ public static PiiDetectionSkill fromJson(JsonReader jsonReader) throws IOExcepti String odataType = "#Microsoft.Skills.Text.PIIDetectionSkill"; String defaultLanguageCode = null; Double minimumPrecision = null; - PiiDetectionSkillMaskingMode maskingMode = null; + PIIDetectionSkillMaskingMode maskingMode = null; String mask = null; String modelVersion = null; List piiCategories = null; @@ -320,10 +348,8 @@ public static PiiDetectionSkill fromJson(JsonReader jsonReader) throws IOExcepti if ("inputs".equals(fieldName)) { inputs = reader.readArray(reader1 -> InputFieldMappingEntry.fromJson(reader1)); - inputsFound = true; } else if ("outputs".equals(fieldName)) { outputs = reader.readArray(reader1 -> OutputFieldMappingEntry.fromJson(reader1)); - outputsFound = true; } else if ("name".equals(fieldName)) { name = reader.getString(); } else if ("description".equals(fieldName)) { @@ -337,7 +363,7 @@ public static PiiDetectionSkill fromJson(JsonReader jsonReader) throws IOExcepti } else if ("minimumPrecision".equals(fieldName)) { minimumPrecision = reader.getNullable(JsonReader::getDouble); } else if ("maskingMode".equals(fieldName)) { - maskingMode = PiiDetectionSkillMaskingMode.fromString(reader.getString()); + maskingMode = PIIDetectionSkillMaskingMode.fromString(reader.getString()); } else if ("maskingCharacter".equals(fieldName)) { mask = reader.getString(); } else if ("modelVersion".equals(fieldName)) { @@ -350,32 +376,20 @@ public static PiiDetectionSkill fromJson(JsonReader jsonReader) throws IOExcepti reader.skipChildren(); } } - if (inputsFound && outputsFound) { - PiiDetectionSkill deserializedPiiDetectionSkill = new PiiDetectionSkill(inputs, outputs); - deserializedPiiDetectionSkill.setName(name); - deserializedPiiDetectionSkill.setDescription(description); - deserializedPiiDetectionSkill.setContext(context); - deserializedPiiDetectionSkill.odataType = odataType; - deserializedPiiDetectionSkill.defaultLanguageCode = defaultLanguageCode; - deserializedPiiDetectionSkill.minimumPrecision = minimumPrecision; - deserializedPiiDetectionSkill.maskingMode = maskingMode; - deserializedPiiDetectionSkill.mask = mask; - deserializedPiiDetectionSkill.modelVersion = modelVersion; - deserializedPiiDetectionSkill.piiCategories = piiCategories; - deserializedPiiDetectionSkill.domain = domain; - - return deserializedPiiDetectionSkill; - } - List missingProperties = new ArrayList<>(); - if (!inputsFound) { - missingProperties.add("inputs"); - } - if (!outputsFound) { - missingProperties.add("outputs"); - } - - throw new IllegalStateException( - "Missing required property/properties: " + String.join(", ", missingProperties)); + PIIDetectionSkill deserializedPIIDetectionSkill = new PIIDetectionSkill(inputs, outputs); + deserializedPIIDetectionSkill.setName(name); + deserializedPIIDetectionSkill.setDescription(description); + deserializedPIIDetectionSkill.setContext(context); + deserializedPIIDetectionSkill.odataType = odataType; + deserializedPIIDetectionSkill.defaultLanguageCode = defaultLanguageCode; + deserializedPIIDetectionSkill.minimumPrecision = minimumPrecision; + deserializedPIIDetectionSkill.maskingMode = maskingMode; + deserializedPIIDetectionSkill.mask = mask; + deserializedPIIDetectionSkill.modelVersion = modelVersion; + deserializedPIIDetectionSkill.piiCategories = piiCategories; + deserializedPIIDetectionSkill.domain = domain; + + return deserializedPIIDetectionSkill; }); } } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/PIIDetectionSkillMaskingMode.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/PIIDetectionSkillMaskingMode.java new file mode 100644 index 000000000000..a6d8030f78f3 --- /dev/null +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/PIIDetectionSkillMaskingMode.java @@ -0,0 +1,61 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.search.documents.models; + +import com.azure.core.annotation.Generated; +import com.azure.core.util.ExpandableStringEnum; +import java.util.Collection; + +/** + * A string indicating what maskingMode to use to mask the personal information + * detected in the input text. + */ +public final class PIIDetectionSkillMaskingMode extends ExpandableStringEnum { + /** + * No masking occurs and the maskedText output will not be returned. + */ + @Generated + public static final PIIDetectionSkillMaskingMode NONE = fromString("none"); + + /** + * Replaces the detected entities with the character given in the maskingCharacter + * parameter. The character will be repeated to the length of the detected entity + * so that the offsets will correctly correspond to both the input text as well as + * the output maskedText. + */ + @Generated + public static final PIIDetectionSkillMaskingMode REPLACE = fromString("replace"); + + /** + * Creates a new instance of PIIDetectionSkillMaskingMode value. + * + * @deprecated Use the {@link #fromString(String)} factory method. + */ + @Generated + @Deprecated + public PIIDetectionSkillMaskingMode() { + } + + /** + * Creates or finds a PIIDetectionSkillMaskingMode from its string representation. + * + * @param name a name to look for. + * @return the corresponding PIIDetectionSkillMaskingMode. + */ + @Generated + public static PIIDetectionSkillMaskingMode fromString(String name) { + return fromString(name, PIIDetectionSkillMaskingMode.class); + } + + /** + * Gets known PIIDetectionSkillMaskingMode values. + * + * @return known PIIDetectionSkillMaskingMode values. + */ + @Generated + public static Collection values() { + return values(PIIDetectionSkillMaskingMode.class); + } +} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/PathHierarchyTokenizer.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/PathHierarchyTokenizerV2.java similarity index 57% rename from sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/PathHierarchyTokenizer.java rename to sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/PathHierarchyTokenizerV2.java index 9e5829755fc4..afc64c5da833 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/PathHierarchyTokenizer.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/PathHierarchyTokenizerV2.java @@ -1,67 +1,75 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) TypeSpec Code Generator. -package com.azure.search.documents.indexes.models; +package com.azure.search.documents.models; import com.azure.core.annotation.Fluent; +import com.azure.core.annotation.Generated; import com.azure.json.JsonReader; import com.azure.json.JsonToken; import com.azure.json.JsonWriter; import java.io.IOException; -import java.util.Objects; /** - * Tokenizer for path-like hierarchies. This tokenizer is implemented using Apache Lucene. + * Tokenizer for path-like hierarchies. This tokenizer is implemented using Apache + * Lucene. */ @Fluent -public final class PathHierarchyTokenizer extends LexicalTokenizer { +public final class PathHierarchyTokenizerV2 extends LexicalTokenizer { /* - * A URI fragment specifying the type of tokenizer. + * The discriminator for derived types. */ + @Generated private String odataType = "#Microsoft.Azure.Search.PathHierarchyTokenizerV2"; /* * The delimiter character to use. Default is "/". */ - private Character delimiter; + @Generated + private String delimiter; /* * A value that, if set, replaces the delimiter character. Default is "/". */ - private Character replacement; + @Generated + private String replacement; /* * The maximum token length. Default and maximum is 300. */ + @Generated private Integer maxTokenLength; /* - * A value indicating whether to generate tokens in reverse order. Default is false. + * A value indicating whether to generate tokens in reverse order. Default is + * false. */ - private Boolean tokenOrderReversed; + @Generated + private Boolean reverseTokenOrder; /* * The number of initial tokens to skip. Default is 0. */ + @Generated private Integer numberOfTokensToSkip; /** - * Creates an instance of PathHierarchyTokenizer class. + * Creates an instance of PathHierarchyTokenizerV2 class. * * @param name the name value to set. */ - public PathHierarchyTokenizer(String name) { + @Generated + public PathHierarchyTokenizerV2(String name) { super(name); } /** - * Get the odataType property: A URI fragment specifying the type of tokenizer. + * Get the odataType property: The discriminator for derived types. * * @return the odataType value. */ + @Generated @Override public String getOdataType() { return this.odataType; @@ -72,7 +80,8 @@ public String getOdataType() { * * @return the delimiter value. */ - public Character getDelimiter() { + @Generated + public String getDelimiter() { return this.delimiter; } @@ -80,9 +89,10 @@ public Character getDelimiter() { * Set the delimiter property: The delimiter character to use. Default is "/". * * @param delimiter the delimiter value to set. - * @return the PathHierarchyTokenizer object itself. + * @return the PathHierarchyTokenizerV2 object itself. */ - public PathHierarchyTokenizer setDelimiter(Character delimiter) { + @Generated + public PathHierarchyTokenizerV2 setDelimiter(String delimiter) { this.delimiter = delimiter; return this; } @@ -92,7 +102,8 @@ public PathHierarchyTokenizer setDelimiter(Character delimiter) { * * @return the replacement value. */ - public Character getReplacement() { + @Generated + public String getReplacement() { return this.replacement; } @@ -100,9 +111,10 @@ public Character getReplacement() { * Set the replacement property: A value that, if set, replaces the delimiter character. Default is "/". * * @param replacement the replacement value to set. - * @return the PathHierarchyTokenizer object itself. + * @return the PathHierarchyTokenizerV2 object itself. */ - public PathHierarchyTokenizer setReplacement(Character replacement) { + @Generated + public PathHierarchyTokenizerV2 setReplacement(String replacement) { this.replacement = replacement; return this; } @@ -112,6 +124,7 @@ public PathHierarchyTokenizer setReplacement(Character replacement) { * * @return the maxTokenLength value. */ + @Generated public Integer getMaxTokenLength() { return this.maxTokenLength; } @@ -120,32 +133,35 @@ public Integer getMaxTokenLength() { * Set the maxTokenLength property: The maximum token length. Default and maximum is 300. * * @param maxTokenLength the maxTokenLength value to set. - * @return the PathHierarchyTokenizer object itself. + * @return the PathHierarchyTokenizerV2 object itself. */ - public PathHierarchyTokenizer setMaxTokenLength(Integer maxTokenLength) { + @Generated + public PathHierarchyTokenizerV2 setMaxTokenLength(Integer maxTokenLength) { this.maxTokenLength = maxTokenLength; return this; } /** - * Get the tokenOrderReversed property: A value indicating whether to generate tokens in reverse order. Default is + * Get the reverseTokenOrder property: A value indicating whether to generate tokens in reverse order. Default is * false. * - * @return the tokenOrderReversed value. + * @return the reverseTokenOrder value. */ - public Boolean isTokenOrderReversed() { - return this.tokenOrderReversed; + @Generated + public Boolean isReverseTokenOrder() { + return this.reverseTokenOrder; } /** - * Set the tokenOrderReversed property: A value indicating whether to generate tokens in reverse order. Default is + * Set the reverseTokenOrder property: A value indicating whether to generate tokens in reverse order. Default is * false. * - * @param tokenOrderReversed the tokenOrderReversed value to set. - * @return the PathHierarchyTokenizer object itself. + * @param reverseTokenOrder the reverseTokenOrder value to set. + * @return the PathHierarchyTokenizerV2 object itself. */ - public PathHierarchyTokenizer setTokenOrderReversed(Boolean tokenOrderReversed) { - this.tokenOrderReversed = tokenOrderReversed; + @Generated + public PathHierarchyTokenizerV2 setReverseTokenOrder(Boolean reverseTokenOrder) { + this.reverseTokenOrder = reverseTokenOrder; return this; } @@ -154,6 +170,7 @@ public PathHierarchyTokenizer setTokenOrderReversed(Boolean tokenOrderReversed) * * @return the numberOfTokensToSkip value. */ + @Generated public Integer getNumberOfTokensToSkip() { return this.numberOfTokensToSkip; } @@ -162,9 +179,10 @@ public Integer getNumberOfTokensToSkip() { * Set the numberOfTokensToSkip property: The number of initial tokens to skip. Default is 0. * * @param numberOfTokensToSkip the numberOfTokensToSkip value to set. - * @return the PathHierarchyTokenizer object itself. + * @return the PathHierarchyTokenizerV2 object itself. */ - public PathHierarchyTokenizer setNumberOfTokensToSkip(Integer numberOfTokensToSkip) { + @Generated + public PathHierarchyTokenizerV2 setNumberOfTokensToSkip(Integer numberOfTokensToSkip) { this.numberOfTokensToSkip = numberOfTokensToSkip; return this; } @@ -172,37 +190,38 @@ public PathHierarchyTokenizer setNumberOfTokensToSkip(Integer numberOfTokensToSk /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); jsonWriter.writeStringField("name", getName()); jsonWriter.writeStringField("@odata.type", this.odataType); - jsonWriter.writeStringField("delimiter", Objects.toString(this.delimiter, null)); - jsonWriter.writeStringField("replacement", Objects.toString(this.replacement, null)); + jsonWriter.writeStringField("delimiter", this.delimiter); + jsonWriter.writeStringField("replacement", this.replacement); jsonWriter.writeNumberField("maxTokenLength", this.maxTokenLength); - jsonWriter.writeBooleanField("reverse", this.tokenOrderReversed); + jsonWriter.writeBooleanField("reverse", this.reverseTokenOrder); jsonWriter.writeNumberField("skip", this.numberOfTokensToSkip); return jsonWriter.writeEndObject(); } /** - * Reads an instance of PathHierarchyTokenizer from the JsonReader. + * Reads an instance of PathHierarchyTokenizerV2 from the JsonReader. * * @param jsonReader The JsonReader being read. - * @return An instance of PathHierarchyTokenizer if the JsonReader was pointing to an instance of it, or null if it - * was pointing to JSON null. + * @return An instance of PathHierarchyTokenizerV2 if the JsonReader was pointing to an instance of it, or null if + * it was pointing to JSON null. * @throws IllegalStateException If the deserialized JSON object was missing any required properties. - * @throws IOException If an error occurs while reading the PathHierarchyTokenizer. + * @throws IOException If an error occurs while reading the PathHierarchyTokenizerV2. */ - public static PathHierarchyTokenizer fromJson(JsonReader jsonReader) throws IOException { + @Generated + public static PathHierarchyTokenizerV2 fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { - boolean nameFound = false; String name = null; String odataType = "#Microsoft.Azure.Search.PathHierarchyTokenizerV2"; - Character delimiter = null; - Character replacement = null; + String delimiter = null; + String replacement = null; Integer maxTokenLength = null; - Boolean tokenOrderReversed = null; + Boolean reverseTokenOrder = null; Integer numberOfTokensToSkip = null; while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); @@ -210,35 +229,31 @@ public static PathHierarchyTokenizer fromJson(JsonReader jsonReader) throws IOEx if ("name".equals(fieldName)) { name = reader.getString(); - nameFound = true; } else if ("@odata.type".equals(fieldName)) { odataType = reader.getString(); } else if ("delimiter".equals(fieldName)) { - delimiter = reader.getNullable(nonNullReader -> nonNullReader.getString().charAt(0)); + delimiter = reader.getString(); } else if ("replacement".equals(fieldName)) { - replacement = reader.getNullable(nonNullReader -> nonNullReader.getString().charAt(0)); + replacement = reader.getString(); } else if ("maxTokenLength".equals(fieldName)) { maxTokenLength = reader.getNullable(JsonReader::getInt); } else if ("reverse".equals(fieldName)) { - tokenOrderReversed = reader.getNullable(JsonReader::getBoolean); + reverseTokenOrder = reader.getNullable(JsonReader::getBoolean); } else if ("skip".equals(fieldName)) { numberOfTokensToSkip = reader.getNullable(JsonReader::getInt); } else { reader.skipChildren(); } } - if (nameFound) { - PathHierarchyTokenizer deserializedPathHierarchyTokenizer = new PathHierarchyTokenizer(name); - deserializedPathHierarchyTokenizer.odataType = odataType; - deserializedPathHierarchyTokenizer.delimiter = delimiter; - deserializedPathHierarchyTokenizer.replacement = replacement; - deserializedPathHierarchyTokenizer.maxTokenLength = maxTokenLength; - deserializedPathHierarchyTokenizer.tokenOrderReversed = tokenOrderReversed; - deserializedPathHierarchyTokenizer.numberOfTokensToSkip = numberOfTokensToSkip; - - return deserializedPathHierarchyTokenizer; - } - throw new IllegalStateException("Missing required property: name"); + PathHierarchyTokenizerV2 deserializedPathHierarchyTokenizerV2 = new PathHierarchyTokenizerV2(name); + deserializedPathHierarchyTokenizerV2.odataType = odataType; + deserializedPathHierarchyTokenizerV2.delimiter = delimiter; + deserializedPathHierarchyTokenizerV2.replacement = replacement; + deserializedPathHierarchyTokenizerV2.maxTokenLength = maxTokenLength; + deserializedPathHierarchyTokenizerV2.reverseTokenOrder = reverseTokenOrder; + deserializedPathHierarchyTokenizerV2.numberOfTokensToSkip = numberOfTokensToSkip; + + return deserializedPathHierarchyTokenizerV2; }); } } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/PatternAnalyzer.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/PatternAnalyzer.java similarity index 66% rename from sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/PatternAnalyzer.java rename to sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/PatternAnalyzer.java index 75495a899bd8..886d46de173a 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/PatternAnalyzer.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/PatternAnalyzer.java @@ -1,66 +1,70 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. -package com.azure.search.documents.indexes.models; +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.search.documents.models; import com.azure.core.annotation.Fluent; +import com.azure.core.annotation.Generated; import com.azure.json.JsonReader; import com.azure.json.JsonToken; import com.azure.json.JsonWriter; import java.io.IOException; -import java.util.Arrays; import java.util.List; -import java.util.stream.Collectors; /** - * Flexibly separates text into terms via a regular expression pattern. This analyzer is implemented using Apache - * Lucene. + * Flexibly separates text into terms via a regular expression pattern. This + * analyzer is implemented using Apache Lucene. */ @Fluent public final class PatternAnalyzer extends LexicalAnalyzer { - /* - * A URI fragment specifying the type of analyzer. + * The discriminator for derived types. */ + @Generated private String odataType = "#Microsoft.Azure.Search.PatternAnalyzer"; /* * A value indicating whether terms should be lower-cased. Default is true. */ + @Generated private Boolean lowerCaseTerms; /* - * A regular expression pattern to match token separators. Default is an expression that matches one or more - * non-word characters. + * A regular expression pattern to match token separators. Default is an + * expression that matches one or more non-word characters. */ + @Generated private String pattern; /* * Regular expression flags. */ + @Generated private RegexFlags flags; /* * A list of stopwords. */ + @Generated private List stopwords; /** * Creates an instance of PatternAnalyzer class. - * + * * @param name the name value to set. */ + @Generated public PatternAnalyzer(String name) { super(name); } /** - * Get the odataType property: A URI fragment specifying the type of analyzer. - * + * Get the odataType property: The discriminator for derived types. + * * @return the odataType value. */ + @Generated @Override public String getOdataType() { return this.odataType; @@ -68,41 +72,45 @@ public String getOdataType() { /** * Get the lowerCaseTerms property: A value indicating whether terms should be lower-cased. Default is true. - * + * * @return the lowerCaseTerms value. */ - public Boolean areLowerCaseTerms() { + @Generated + public Boolean isLowerCaseTerms() { return this.lowerCaseTerms; } /** * Set the lowerCaseTerms property: A value indicating whether terms should be lower-cased. Default is true. - * + * * @param lowerCaseTerms the lowerCaseTerms value to set. * @return the PatternAnalyzer object itself. */ + @Generated public PatternAnalyzer setLowerCaseTerms(Boolean lowerCaseTerms) { this.lowerCaseTerms = lowerCaseTerms; return this; } /** - * Get the pattern property: A regular expression pattern to match token separators. Default is an expression that - * matches one or more non-word characters. - * + * Get the pattern property: A regular expression pattern to match token separators. Default is an + * expression that matches one or more non-word characters. + * * @return the pattern value. */ + @Generated public String getPattern() { return this.pattern; } /** - * Set the pattern property: A regular expression pattern to match token separators. Default is an expression that - * matches one or more non-word characters. - * + * Set the pattern property: A regular expression pattern to match token separators. Default is an + * expression that matches one or more non-word characters. + * * @param pattern the pattern value to set. * @return the PatternAnalyzer object itself. */ + @Generated public PatternAnalyzer setPattern(String pattern) { this.pattern = pattern; return this; @@ -110,49 +118,43 @@ public PatternAnalyzer setPattern(String pattern) { /** * Get the flags property: Regular expression flags. - * + * * @return the flags value. */ - public List getFlags() { - if (this.flags == null) { - return null; - } else { - String[] flagStrings = this.flags.toString().split("\\|"); - return Arrays.stream(flagStrings).map(RegexFlags::fromString).collect(Collectors.toList()); - } + @Generated + public RegexFlags getFlags() { + return this.flags; } /** * Set the flags property: Regular expression flags. - * + * * @param flags the flags value to set. * @return the PatternAnalyzer object itself. */ - public PatternAnalyzer setFlags(List flags) { - if (flags == null) { - this.flags = null; - } else { - String flagString = flags.stream().map(RegexFlags::toString).collect(Collectors.joining("|")); - this.flags = RegexFlags.fromString(flagString); - } + @Generated + public PatternAnalyzer setFlags(RegexFlags flags) { + this.flags = flags; return this; } /** * Get the stopwords property: A list of stopwords. - * + * * @return the stopwords value. */ + @Generated public List getStopwords() { return this.stopwords; } /** * Set the stopwords property: A list of stopwords. - * + * * @param stopwords the stopwords value to set. * @return the PatternAnalyzer object itself. */ + @Generated public PatternAnalyzer setStopwords(List stopwords) { this.stopwords = stopwords; return this; @@ -161,6 +163,7 @@ public PatternAnalyzer setStopwords(List stopwords) { /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); @@ -175,16 +178,16 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of PatternAnalyzer from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of PatternAnalyzer if the JsonReader was pointing to an instance of it, or null if it was * pointing to JSON null. * @throws IllegalStateException If the deserialized JSON object was missing any required properties. * @throws IOException If an error occurs while reading the PatternAnalyzer. */ + @Generated public static PatternAnalyzer fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { - boolean nameFound = false; String name = null; String odataType = "#Microsoft.Azure.Search.PatternAnalyzer"; Boolean lowerCaseTerms = null; @@ -194,9 +197,9 @@ public static PatternAnalyzer fromJson(JsonReader jsonReader) throws IOException while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); + if ("name".equals(fieldName)) { name = reader.getString(); - nameFound = true; } else if ("@odata.type".equals(fieldName)) { odataType = reader.getString(); } else if ("lowercase".equals(fieldName)) { @@ -211,42 +214,14 @@ public static PatternAnalyzer fromJson(JsonReader jsonReader) throws IOException reader.skipChildren(); } } - if (nameFound) { - PatternAnalyzer deserializedPatternAnalyzer = new PatternAnalyzer(name); - deserializedPatternAnalyzer.odataType = odataType; - deserializedPatternAnalyzer.lowerCaseTerms = lowerCaseTerms; - deserializedPatternAnalyzer.pattern = pattern; - deserializedPatternAnalyzer.flags = flags; - deserializedPatternAnalyzer.stopwords = stopwords; - return deserializedPatternAnalyzer; - } - throw new IllegalStateException("Missing required property: name"); + PatternAnalyzer deserializedPatternAnalyzer = new PatternAnalyzer(name); + deserializedPatternAnalyzer.odataType = odataType; + deserializedPatternAnalyzer.lowerCaseTerms = lowerCaseTerms; + deserializedPatternAnalyzer.pattern = pattern; + deserializedPatternAnalyzer.flags = flags; + deserializedPatternAnalyzer.stopwords = stopwords; + + return deserializedPatternAnalyzer; }); } - - /** - * Set the stopwords property: A list of stopwords. - * - * @param stopwords the stopwords value to set. - * @return the PatternAnalyzer object itself. - */ - public PatternAnalyzer setStopwords(String... stopwords) { - this.stopwords = (stopwords == null) ? null : Arrays.asList(stopwords); - return this; - } - - /** - * Set the flags property: Regular expression flags. - * - * @param flags the flags value to set. - * @return the PatternAnalyzer object itself. - */ - public PatternAnalyzer setFlags(RegexFlags... flags) { - if (flags == null) { - this.flags = null; - return this; - } else { - return setFlags(Arrays.asList(flags)); - } - } } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/PatternCaptureTokenFilter.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/PatternCaptureTokenFilter.java similarity index 74% rename from sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/PatternCaptureTokenFilter.java rename to sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/PatternCaptureTokenFilter.java index a7b760b13ef8..82cd96bd4d74 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/PatternCaptureTokenFilter.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/PatternCaptureTokenFilter.java @@ -1,38 +1,40 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) TypeSpec Code Generator. -package com.azure.search.documents.indexes.models; +package com.azure.search.documents.models; import com.azure.core.annotation.Fluent; +import com.azure.core.annotation.Generated; import com.azure.json.JsonReader; import com.azure.json.JsonToken; import com.azure.json.JsonWriter; import java.io.IOException; -import java.util.ArrayList; import java.util.List; /** - * 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. + * 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. */ @Fluent public final class PatternCaptureTokenFilter extends TokenFilter { /* - * A URI fragment specifying the type of token filter. + * The discriminator for derived types. */ + @Generated private String odataType = "#Microsoft.Azure.Search.PatternCaptureTokenFilter"; /* * A list of patterns to match against each token. */ + @Generated private final List patterns; /* - * A value indicating whether to return the original token even if one of the patterns matches. Default is true. + * A value indicating whether to return the original token even if one of the + * patterns matches. Default is true. */ + @Generated private Boolean preserveOriginal; /** @@ -41,16 +43,18 @@ public final class PatternCaptureTokenFilter extends TokenFilter { * @param name the name value to set. * @param patterns the patterns value to set. */ + @Generated public PatternCaptureTokenFilter(String name, List patterns) { super(name); this.patterns = patterns; } /** - * Get the odataType property: A URI fragment specifying the type of token filter. + * Get the odataType property: The discriminator for derived types. * * @return the odataType value. */ + @Generated @Override public String getOdataType() { return this.odataType; @@ -61,6 +65,7 @@ public String getOdataType() { * * @return the patterns value. */ + @Generated public List getPatterns() { return this.patterns; } @@ -71,6 +76,7 @@ public List getPatterns() { * * @return the preserveOriginal value. */ + @Generated public Boolean isPreserveOriginal() { return this.preserveOriginal; } @@ -82,6 +88,7 @@ public Boolean isPreserveOriginal() { * @param preserveOriginal the preserveOriginal value to set. * @return the PatternCaptureTokenFilter object itself. */ + @Generated public PatternCaptureTokenFilter setPreserveOriginal(Boolean preserveOriginal) { this.preserveOriginal = preserveOriginal; return this; @@ -90,6 +97,7 @@ public PatternCaptureTokenFilter setPreserveOriginal(Boolean preserveOriginal) { /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); @@ -109,11 +117,10 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { * @throws IllegalStateException If the deserialized JSON object was missing any required properties. * @throws IOException If an error occurs while reading the PatternCaptureTokenFilter. */ + @Generated public static PatternCaptureTokenFilter fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { - boolean nameFound = false; String name = null; - boolean patternsFound = false; List patterns = null; String odataType = "#Microsoft.Azure.Search.PatternCaptureTokenFilter"; Boolean preserveOriginal = null; @@ -123,10 +130,8 @@ public static PatternCaptureTokenFilter fromJson(JsonReader jsonReader) throws I if ("name".equals(fieldName)) { name = reader.getString(); - nameFound = true; } else if ("patterns".equals(fieldName)) { patterns = reader.readArray(reader1 -> reader1.getString()); - patternsFound = true; } else if ("@odata.type".equals(fieldName)) { odataType = reader.getString(); } else if ("preserveOriginal".equals(fieldName)) { @@ -135,24 +140,12 @@ public static PatternCaptureTokenFilter fromJson(JsonReader jsonReader) throws I reader.skipChildren(); } } - if (nameFound && patternsFound) { - PatternCaptureTokenFilter deserializedPatternCaptureTokenFilter - = new PatternCaptureTokenFilter(name, patterns); - deserializedPatternCaptureTokenFilter.odataType = odataType; - deserializedPatternCaptureTokenFilter.preserveOriginal = preserveOriginal; - - return deserializedPatternCaptureTokenFilter; - } - List missingProperties = new ArrayList<>(); - if (!nameFound) { - missingProperties.add("name"); - } - if (!patternsFound) { - missingProperties.add("patterns"); - } + PatternCaptureTokenFilter deserializedPatternCaptureTokenFilter + = new PatternCaptureTokenFilter(name, patterns); + deserializedPatternCaptureTokenFilter.odataType = odataType; + deserializedPatternCaptureTokenFilter.preserveOriginal = preserveOriginal; - throw new IllegalStateException( - "Missing required property/properties: " + String.join(", ", missingProperties)); + return deserializedPatternCaptureTokenFilter; }); } } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/PatternReplaceCharFilter.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/PatternReplaceCharFilter.java similarity index 66% rename from sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/PatternReplaceCharFilter.java rename to sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/PatternReplaceCharFilter.java index 9d5a9a311453..bfd3c9494f3e 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/PatternReplaceCharFilter.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/PatternReplaceCharFilter.java @@ -1,40 +1,42 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) TypeSpec Code Generator. -package com.azure.search.documents.indexes.models; +package com.azure.search.documents.models; +import com.azure.core.annotation.Generated; import com.azure.core.annotation.Immutable; import com.azure.json.JsonReader; import com.azure.json.JsonToken; import com.azure.json.JsonWriter; import java.io.IOException; -import java.util.ArrayList; -import java.util.List; /** - * 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. + * 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. */ @Immutable public final class PatternReplaceCharFilter extends CharFilter { /* - * A URI fragment specifying the type of char filter. + * The discriminator for derived types. */ + @Generated private String odataType = "#Microsoft.Azure.Search.PatternReplaceCharFilter"; /* * A regular expression pattern. */ + @Generated private final String pattern; /* * The replacement text. */ + @Generated private final String replacement; /** @@ -44,6 +46,7 @@ public final class PatternReplaceCharFilter extends CharFilter { * @param pattern the pattern value to set. * @param replacement the replacement value to set. */ + @Generated public PatternReplaceCharFilter(String name, String pattern, String replacement) { super(name); this.pattern = pattern; @@ -51,10 +54,11 @@ public PatternReplaceCharFilter(String name, String pattern, String replacement) } /** - * Get the odataType property: A URI fragment specifying the type of char filter. + * Get the odataType property: The discriminator for derived types. * * @return the odataType value. */ + @Generated @Override public String getOdataType() { return this.odataType; @@ -65,6 +69,7 @@ public String getOdataType() { * * @return the pattern value. */ + @Generated public String getPattern() { return this.pattern; } @@ -74,6 +79,7 @@ public String getPattern() { * * @return the replacement value. */ + @Generated public String getReplacement() { return this.replacement; } @@ -81,6 +87,7 @@ public String getReplacement() { /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); @@ -100,13 +107,11 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { * @throws IllegalStateException If the deserialized JSON object was missing any required properties. * @throws IOException If an error occurs while reading the PatternReplaceCharFilter. */ + @Generated public static PatternReplaceCharFilter fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { - boolean nameFound = false; String name = null; - boolean patternFound = false; String pattern = null; - boolean replacementFound = false; String replacement = null; String odataType = "#Microsoft.Azure.Search.PatternReplaceCharFilter"; while (reader.nextToken() != JsonToken.END_OBJECT) { @@ -115,39 +120,21 @@ public static PatternReplaceCharFilter fromJson(JsonReader jsonReader) throws IO if ("name".equals(fieldName)) { name = reader.getString(); - nameFound = true; } else if ("pattern".equals(fieldName)) { pattern = reader.getString(); - patternFound = true; } else if ("replacement".equals(fieldName)) { replacement = reader.getString(); - replacementFound = true; } else if ("@odata.type".equals(fieldName)) { odataType = reader.getString(); } else { reader.skipChildren(); } } - if (nameFound && patternFound && replacementFound) { - PatternReplaceCharFilter deserializedPatternReplaceCharFilter - = new PatternReplaceCharFilter(name, pattern, replacement); - deserializedPatternReplaceCharFilter.odataType = odataType; + PatternReplaceCharFilter deserializedPatternReplaceCharFilter + = new PatternReplaceCharFilter(name, pattern, replacement); + deserializedPatternReplaceCharFilter.odataType = odataType; - return deserializedPatternReplaceCharFilter; - } - List missingProperties = new ArrayList<>(); - if (!nameFound) { - missingProperties.add("name"); - } - if (!patternFound) { - missingProperties.add("pattern"); - } - if (!replacementFound) { - missingProperties.add("replacement"); - } - - throw new IllegalStateException( - "Missing required property/properties: " + String.join(", ", missingProperties)); + return deserializedPatternReplaceCharFilter; }); } } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/PatternReplaceTokenFilter.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/PatternReplaceTokenFilter.java similarity index 66% rename from sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/PatternReplaceTokenFilter.java rename to sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/PatternReplaceTokenFilter.java index af06720459e9..65efb61e668f 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/PatternReplaceTokenFilter.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/PatternReplaceTokenFilter.java @@ -1,40 +1,42 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) TypeSpec Code Generator. -package com.azure.search.documents.indexes.models; +package com.azure.search.documents.models; +import com.azure.core.annotation.Generated; import com.azure.core.annotation.Immutable; import com.azure.json.JsonReader; import com.azure.json.JsonToken; import com.azure.json.JsonWriter; import java.io.IOException; -import java.util.ArrayList; -import java.util.List; /** - * 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. + * 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. */ @Immutable public final class PatternReplaceTokenFilter extends TokenFilter { /* - * A URI fragment specifying the type of token filter. + * The discriminator for derived types. */ + @Generated private String odataType = "#Microsoft.Azure.Search.PatternReplaceTokenFilter"; /* * A regular expression pattern. */ + @Generated private final String pattern; /* * The replacement text. */ + @Generated private final String replacement; /** @@ -44,6 +46,7 @@ public final class PatternReplaceTokenFilter extends TokenFilter { * @param pattern the pattern value to set. * @param replacement the replacement value to set. */ + @Generated public PatternReplaceTokenFilter(String name, String pattern, String replacement) { super(name); this.pattern = pattern; @@ -51,10 +54,11 @@ public PatternReplaceTokenFilter(String name, String pattern, String replacement } /** - * Get the odataType property: A URI fragment specifying the type of token filter. + * Get the odataType property: The discriminator for derived types. * * @return the odataType value. */ + @Generated @Override public String getOdataType() { return this.odataType; @@ -65,6 +69,7 @@ public String getOdataType() { * * @return the pattern value. */ + @Generated public String getPattern() { return this.pattern; } @@ -74,6 +79,7 @@ public String getPattern() { * * @return the replacement value. */ + @Generated public String getReplacement() { return this.replacement; } @@ -81,6 +87,7 @@ public String getReplacement() { /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); @@ -100,13 +107,11 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { * @throws IllegalStateException If the deserialized JSON object was missing any required properties. * @throws IOException If an error occurs while reading the PatternReplaceTokenFilter. */ + @Generated public static PatternReplaceTokenFilter fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { - boolean nameFound = false; String name = null; - boolean patternFound = false; String pattern = null; - boolean replacementFound = false; String replacement = null; String odataType = "#Microsoft.Azure.Search.PatternReplaceTokenFilter"; while (reader.nextToken() != JsonToken.END_OBJECT) { @@ -115,39 +120,21 @@ public static PatternReplaceTokenFilter fromJson(JsonReader jsonReader) throws I if ("name".equals(fieldName)) { name = reader.getString(); - nameFound = true; } else if ("pattern".equals(fieldName)) { pattern = reader.getString(); - patternFound = true; } else if ("replacement".equals(fieldName)) { replacement = reader.getString(); - replacementFound = true; } else if ("@odata.type".equals(fieldName)) { odataType = reader.getString(); } else { reader.skipChildren(); } } - if (nameFound && patternFound && replacementFound) { - PatternReplaceTokenFilter deserializedPatternReplaceTokenFilter - = new PatternReplaceTokenFilter(name, pattern, replacement); - deserializedPatternReplaceTokenFilter.odataType = odataType; + PatternReplaceTokenFilter deserializedPatternReplaceTokenFilter + = new PatternReplaceTokenFilter(name, pattern, replacement); + deserializedPatternReplaceTokenFilter.odataType = odataType; - return deserializedPatternReplaceTokenFilter; - } - List missingProperties = new ArrayList<>(); - if (!nameFound) { - missingProperties.add("name"); - } - if (!patternFound) { - missingProperties.add("pattern"); - } - if (!replacementFound) { - missingProperties.add("replacement"); - } - - throw new IllegalStateException( - "Missing required property/properties: " + String.join(", ", missingProperties)); + return deserializedPatternReplaceTokenFilter; }); } } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/PatternTokenizer.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/PatternTokenizer.java similarity index 60% rename from sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/PatternTokenizer.java rename to sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/PatternTokenizer.java index a36185432239..5fd6d210383d 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/PatternTokenizer.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/PatternTokenizer.java @@ -1,85 +1,89 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. -package com.azure.search.documents.indexes.models; +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.search.documents.models; import com.azure.core.annotation.Fluent; +import com.azure.core.annotation.Generated; import com.azure.json.JsonReader; import com.azure.json.JsonToken; import com.azure.json.JsonWriter; import java.io.IOException; -import java.util.Arrays; -import java.util.List; -import java.util.stream.Collectors; /** - * Tokenizer that uses regex pattern matching to construct distinct tokens. This tokenizer is implemented using Apache - * Lucene. + * Tokenizer that uses regex pattern matching to construct distinct tokens. This + * tokenizer is implemented using Apache Lucene. */ @Fluent public final class PatternTokenizer extends LexicalTokenizer { - /* - * A URI fragment specifying the type of tokenizer. + * The discriminator for derived types. */ + @Generated private String odataType = "#Microsoft.Azure.Search.PatternTokenizer"; /* - * A regular expression pattern to match token separators. Default is an expression that matches one or more - * non-word characters. + * A regular expression pattern to match token separators. Default is an + * expression that matches one or more non-word characters. */ + @Generated private String pattern; /* * Regular expression flags. */ + @Generated private RegexFlags flags; /* - * 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. + * 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. */ + @Generated private Integer group; /** * Creates an instance of PatternTokenizer class. - * + * * @param name the name value to set. */ + @Generated public PatternTokenizer(String name) { super(name); } /** - * Get the odataType property: A URI fragment specifying the type of tokenizer. - * + * Get the odataType property: The discriminator for derived types. + * * @return the odataType value. */ + @Generated @Override public String getOdataType() { return this.odataType; } /** - * Get the pattern property: A regular expression pattern to match token separators. Default is an expression that - * matches one or more non-word characters. - * + * Get the pattern property: A regular expression pattern to match token separators. Default is an + * expression that matches one or more non-word characters. + * * @return the pattern value. */ + @Generated public String getPattern() { return this.pattern; } /** - * Set the pattern property: A regular expression pattern to match token separators. Default is an expression that - * matches one or more non-word characters. - * + * Set the pattern property: A regular expression pattern to match token separators. Default is an + * expression that matches one or more non-word characters. + * * @param pattern the pattern value to set. * @return the PatternTokenizer object itself. */ + @Generated public PatternTokenizer setPattern(String pattern) { this.pattern = pattern; return this; @@ -87,53 +91,47 @@ public PatternTokenizer setPattern(String pattern) { /** * Get the flags property: Regular expression flags. - * + * * @return the flags value. */ - public List getFlags() { - if (this.flags == null) { - return null; - } else { - String[] flagStrings = this.flags.toString().split("\\|"); - return Arrays.stream(flagStrings).map(RegexFlags::fromString).collect(Collectors.toList()); - } + @Generated + public RegexFlags getFlags() { + return this.flags; } /** * Set the flags property: Regular expression flags. - * + * * @param flags the flags value to set. * @return the PatternTokenizer object itself. */ - public PatternTokenizer setFlags(List flags) { - if (flags == null) { - this.flags = null; - } else { - String flagString = flags.stream().map(RegexFlags::toString).collect(Collectors.joining("|")); - this.flags = RegexFlags.fromString(flagString); - } + @Generated + public PatternTokenizer setFlags(RegexFlags flags) { + this.flags = flags; return this; } /** - * Get the group property: 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. - * + * Get the group property: 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. + * * @return the group value. */ + @Generated public Integer getGroup() { return this.group; } /** - * Set the group property: 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. - * + * Set the group property: 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. + * * @param group the group value to set. * @return the PatternTokenizer object itself. */ + @Generated public PatternTokenizer setGroup(Integer group) { this.group = group; return this; @@ -142,6 +140,7 @@ public PatternTokenizer setGroup(Integer group) { /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); @@ -155,16 +154,16 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of PatternTokenizer from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of PatternTokenizer if the JsonReader was pointing to an instance of it, or null if it was * pointing to JSON null. * @throws IllegalStateException If the deserialized JSON object was missing any required properties. * @throws IOException If an error occurs while reading the PatternTokenizer. */ + @Generated public static PatternTokenizer fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { - boolean nameFound = false; String name = null; String odataType = "#Microsoft.Azure.Search.PatternTokenizer"; String pattern = null; @@ -173,9 +172,9 @@ public static PatternTokenizer fromJson(JsonReader jsonReader) throws IOExceptio while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); + if ("name".equals(fieldName)) { name = reader.getString(); - nameFound = true; } else if ("@odata.type".equals(fieldName)) { odataType = reader.getString(); } else if ("pattern".equals(fieldName)) { @@ -188,30 +187,13 @@ public static PatternTokenizer fromJson(JsonReader jsonReader) throws IOExceptio reader.skipChildren(); } } - if (nameFound) { - PatternTokenizer deserializedPatternTokenizer = new PatternTokenizer(name); - deserializedPatternTokenizer.odataType = odataType; - deserializedPatternTokenizer.pattern = pattern; - deserializedPatternTokenizer.flags = flags; - deserializedPatternTokenizer.group = group; - return deserializedPatternTokenizer; - } - throw new IllegalStateException("Missing required property: name"); - }); - } + PatternTokenizer deserializedPatternTokenizer = new PatternTokenizer(name); + deserializedPatternTokenizer.odataType = odataType; + deserializedPatternTokenizer.pattern = pattern; + deserializedPatternTokenizer.flags = flags; + deserializedPatternTokenizer.group = group; - /** - * Set the flags property: Regular expression flags. - * - * @param flags the flags value to set. - * @return the PatternTokenizer object itself. - */ - public PatternTokenizer setFlags(RegexFlags... flags) { - if (flags == null) { - this.flags = null; - return this; - } else { - return setFlags(Arrays.asList(flags)); - } + return deserializedPatternTokenizer; + }); } } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/PhoneticEncoder.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/PhoneticEncoder.java new file mode 100644 index 000000000000..3cc85cfe83ad --- /dev/null +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/PhoneticEncoder.java @@ -0,0 +1,111 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.search.documents.models; + +import com.azure.core.annotation.Generated; +import com.azure.core.util.ExpandableStringEnum; +import java.util.Collection; + +/** + * Identifies the type of phonetic encoder to use with a PhoneticTokenFilter. + */ +public final class PhoneticEncoder extends ExpandableStringEnum { + /** + * Encodes a token into a Metaphone value. + */ + @Generated + public static final PhoneticEncoder METAPHONE = fromString("metaphone"); + + /** + * Encodes a token into a double metaphone value. + */ + @Generated + public static final PhoneticEncoder DOUBLE_METAPHONE = fromString("doubleMetaphone"); + + /** + * Encodes a token into a Soundex value. + */ + @Generated + public static final PhoneticEncoder SOUNDEX = fromString("soundex"); + + /** + * Encodes a token into a Refined Soundex value. + */ + @Generated + public static final PhoneticEncoder REFINED_SOUNDEX = fromString("refinedSoundex"); + + /** + * Encodes a token into a Caverphone 1.0 value. + */ + @Generated + public static final PhoneticEncoder CAVERPHONE1 = fromString("caverphone1"); + + /** + * Encodes a token into a Caverphone 2.0 value. + */ + @Generated + public static final PhoneticEncoder CAVERPHONE2 = fromString("caverphone2"); + + /** + * Encodes a token into a Cologne Phonetic value. + */ + @Generated + public static final PhoneticEncoder COLOGNE = fromString("cologne"); + + /** + * Encodes a token into a NYSIIS value. + */ + @Generated + public static final PhoneticEncoder NYSIIS = fromString("nysiis"); + + /** + * Encodes a token using the Kölner Phonetik algorithm. + */ + @Generated + public static final PhoneticEncoder KOELNER_PHONETIK = fromString("koelnerPhonetik"); + + /** + * Encodes a token using the Haase refinement of the Kölner Phonetik algorithm. + */ + @Generated + public static final PhoneticEncoder HAASE_PHONETIK = fromString("haasePhonetik"); + + /** + * Encodes a token into a Beider-Morse value. + */ + @Generated + public static final PhoneticEncoder BEIDER_MORSE = fromString("beiderMorse"); + + /** + * Creates a new instance of PhoneticEncoder value. + * + * @deprecated Use the {@link #fromString(String)} factory method. + */ + @Generated + @Deprecated + public PhoneticEncoder() { + } + + /** + * Creates or finds a PhoneticEncoder from its string representation. + * + * @param name a name to look for. + * @return the corresponding PhoneticEncoder. + */ + @Generated + public static PhoneticEncoder fromString(String name) { + return fromString(name, PhoneticEncoder.class); + } + + /** + * Gets known PhoneticEncoder values. + * + * @return known PhoneticEncoder values. + */ + @Generated + public static Collection values() { + return values(PhoneticEncoder.class); + } +} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/PhoneticTokenFilter.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/PhoneticTokenFilter.java similarity index 62% rename from sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/PhoneticTokenFilter.java rename to sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/PhoneticTokenFilter.java index df91487513b1..0d2d0bb98f0a 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/PhoneticTokenFilter.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/PhoneticTokenFilter.java @@ -1,52 +1,57 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. -package com.azure.search.documents.indexes.models; +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.search.documents.models; import com.azure.core.annotation.Fluent; +import com.azure.core.annotation.Generated; import com.azure.json.JsonReader; import com.azure.json.JsonToken; import com.azure.json.JsonWriter; import java.io.IOException; /** - * Create tokens for phonetic matches. This token filter is implemented using Apache Lucene. + * Create tokens for phonetic matches. This token filter is implemented using + * Apache Lucene. */ @Fluent public final class PhoneticTokenFilter extends TokenFilter { - /* - * A URI fragment specifying the type of token filter. + * The discriminator for derived types. */ + @Generated private String odataType = "#Microsoft.Azure.Search.PhoneticTokenFilter"; /* * The phonetic encoder to use. Default is "metaphone". */ + @Generated private PhoneticEncoder encoder; /* - * A value indicating whether encoded tokens should replace original tokens. If false, encoded tokens are added as - * synonyms. Default is true. + * A value indicating whether encoded tokens should replace original tokens. If + * false, encoded tokens are added as synonyms. Default is true. */ - private Boolean originalTokensReplaced; + @Generated + private Boolean replaceOriginalTokens; /** * Creates an instance of PhoneticTokenFilter class. - * + * * @param name the name value to set. */ + @Generated public PhoneticTokenFilter(String name) { super(name); } /** - * Get the odataType property: A URI fragment specifying the type of token filter. - * + * Get the odataType property: The discriminator for derived types. + * * @return the odataType value. */ + @Generated @Override public String getOdataType() { return this.odataType; @@ -54,99 +59,104 @@ public String getOdataType() { /** * Get the encoder property: The phonetic encoder to use. Default is "metaphone". - * + * * @return the encoder value. */ + @Generated public PhoneticEncoder getEncoder() { return this.encoder; } /** * Set the encoder property: The phonetic encoder to use. Default is "metaphone". - * + * * @param encoder the encoder value to set. * @return the PhoneticTokenFilter object itself. */ + @Generated public PhoneticTokenFilter setEncoder(PhoneticEncoder encoder) { this.encoder = encoder; return this; } /** - * Get the originalTokensReplaced property: A value indicating whether encoded tokens should replace original - * tokens. If false, encoded tokens are added as synonyms. Default is true. - * - * @return the originalTokensReplaced value. + * Get the replaceOriginalTokens property: A value indicating whether encoded tokens should replace original tokens. + * If + * false, encoded tokens are added as synonyms. Default is true. + * + * @return the replaceOriginalTokens value. */ - public Boolean areOriginalTokensReplaced() { - return this.originalTokensReplaced; + @Generated + public Boolean isReplaceOriginalTokens() { + return this.replaceOriginalTokens; } /** - * Set the originalTokensReplaced property: A value indicating whether encoded tokens should replace original - * tokens. If false, encoded tokens are added as synonyms. Default is true. - * - * @param originalTokensReplaced the originalTokensReplaced value to set. + * Set the replaceOriginalTokens property: A value indicating whether encoded tokens should replace original tokens. + * If + * false, encoded tokens are added as synonyms. Default is true. + * + * @param replaceOriginalTokens the replaceOriginalTokens value to set. * @return the PhoneticTokenFilter object itself. */ - public PhoneticTokenFilter setOriginalTokensReplaced(Boolean originalTokensReplaced) { - this.originalTokensReplaced = originalTokensReplaced; + @Generated + public PhoneticTokenFilter setReplaceOriginalTokens(Boolean replaceOriginalTokens) { + this.replaceOriginalTokens = replaceOriginalTokens; return this; } /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); jsonWriter.writeStringField("name", getName()); jsonWriter.writeStringField("@odata.type", this.odataType); jsonWriter.writeStringField("encoder", this.encoder == null ? null : this.encoder.toString()); - jsonWriter.writeBooleanField("replace", this.originalTokensReplaced); + jsonWriter.writeBooleanField("replace", this.replaceOriginalTokens); return jsonWriter.writeEndObject(); } /** * Reads an instance of PhoneticTokenFilter from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of PhoneticTokenFilter if the JsonReader was pointing to an instance of it, or null if it was * pointing to JSON null. * @throws IllegalStateException If the deserialized JSON object was missing any required properties. * @throws IOException If an error occurs while reading the PhoneticTokenFilter. */ + @Generated public static PhoneticTokenFilter fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { - boolean nameFound = false; String name = null; String odataType = "#Microsoft.Azure.Search.PhoneticTokenFilter"; PhoneticEncoder encoder = null; - Boolean originalTokensReplaced = null; + Boolean replaceOriginalTokens = null; while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); + if ("name".equals(fieldName)) { name = reader.getString(); - nameFound = true; } else if ("@odata.type".equals(fieldName)) { odataType = reader.getString(); } else if ("encoder".equals(fieldName)) { encoder = PhoneticEncoder.fromString(reader.getString()); } else if ("replace".equals(fieldName)) { - originalTokensReplaced = reader.getNullable(JsonReader::getBoolean); + replaceOriginalTokens = reader.getNullable(JsonReader::getBoolean); } else { reader.skipChildren(); } } - if (nameFound) { - PhoneticTokenFilter deserializedPhoneticTokenFilter = new PhoneticTokenFilter(name); - deserializedPhoneticTokenFilter.odataType = odataType; - deserializedPhoneticTokenFilter.encoder = encoder; - deserializedPhoneticTokenFilter.originalTokensReplaced = originalTokensReplaced; - return deserializedPhoneticTokenFilter; - } - throw new IllegalStateException("Missing required property: name"); + PhoneticTokenFilter deserializedPhoneticTokenFilter = new PhoneticTokenFilter(name); + deserializedPhoneticTokenFilter.odataType = odataType; + deserializedPhoneticTokenFilter.encoder = encoder; + deserializedPhoneticTokenFilter.replaceOriginalTokens = replaceOriginalTokens; + + return deserializedPhoneticTokenFilter; }); } } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/QueryAnswer.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/QueryAnswer.java deleted file mode 100644 index 43dacbe89298..000000000000 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/QueryAnswer.java +++ /dev/null @@ -1,118 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -package com.azure.search.documents.models; - -import java.util.Objects; - -/** - * Configuration for how semantic search returns answers to the search. - */ -public final class QueryAnswer { - private final QueryAnswerType answerType; - private Integer count; - private Double threshold; - private Integer maxCharLength; - - /** - * Creates a new instance of {@link QueryAnswer}. - * - * @param answerType The type of answers to generate. - */ - public QueryAnswer(QueryAnswerType answerType) { - this.answerType = Objects.requireNonNull(answerType, "'answerType' cannot be null."); - } - - /** - * Gets the type of answers to generate. - * - * @return The type of answers to generate. - */ - public QueryAnswerType getAnswerType() { - return answerType; - } - - /** - * Gets the number of answers to generate. - *

- * The number of answers to return is optional and will default to 1. - *

- * The value only takes effect when {@link #getAnswerType()} is {@link QueryAnswerType#EXTRACTIVE}. - * - * @return The number of answers to generate. - */ - public Integer getCount() { - return count; - } - - /** - * Sets the number of answers to generate. - *

- * The number of answers to return is optional and will default to 1. - *

- * The value only takes effect when {@link #getAnswerType()} is {@link QueryAnswerType#EXTRACTIVE}. - * - * @param count The number of answers to generate. - * @return The QueryAnswer object itself. - */ - public QueryAnswer setCount(Integer count) { - this.count = count; - return this; - } - - /** - * Gets the confidence threshold an answer must match to be included as an answer to the query of answers. - *

- * The threshold is optional and will default to 0.7. - *

- * The value only takes effect when {@link #getAnswerType()} is {@link QueryAnswerType#EXTRACTIVE}. - * - * @return The confidence threshold an answer must match to be included as an answer to the query of answers. - */ - public Double getThreshold() { - return threshold; - } - - /** - * Sets the confidence threshold an answer must match to be included as an answer to the query of answers. - *

- * The threshold is optional and will default to 0.7. - *

- * The value only takes effect when {@link #getAnswerType()} is {@link QueryAnswerType#EXTRACTIVE}. - * - * @param threshold The confidence threshold an answer must match to be included as an answer to the query of - * answers. - * @return The QueryAnswer object itself. - */ - public QueryAnswer setThreshold(Double threshold) { - this.threshold = threshold; - return this; - } - - /** - * Gets the maximum character length of answers. - *

- * The maximum character length of answers is optional. - *

- * The value only takes effect when {@link #getAnswerType()} is {@link QueryAnswerType#EXTRACTIVE}. - * - * @return The maximum character length of answers. - */ - public Integer getMaxCharLength() { - return maxCharLength; - } - - /** - * Sets the maximum character length of answers. - *

- * The maximum character length of answers is optional. - *

- * The value only takes effect when {@link #getAnswerType()} is {@link QueryAnswerType#EXTRACTIVE}. - * - * @param maxCharLength The maximum character length of answers. - * @return The QueryAnswer object itself. - */ - public QueryAnswer setMaxCharLength(Integer maxCharLength) { - this.maxCharLength = maxCharLength; - return this; - } -} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/QueryAnswerResult.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/QueryAnswerResult.java index 61aed9d574ce..8e6317f5ea3c 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/QueryAnswerResult.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/QueryAnswerResult.java @@ -1,12 +1,12 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.search.documents.models; -import com.azure.core.annotation.Fluent; +import com.azure.core.annotation.Generated; +import com.azure.core.annotation.Immutable; +import com.azure.core.util.BinaryData; import com.azure.json.JsonReader; import com.azure.json.JsonSerializable; import com.azure.json.JsonToken; @@ -16,50 +16,60 @@ import java.util.Map; /** - * 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. + * 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. */ -@Fluent +@Immutable public final class QueryAnswerResult implements JsonSerializable { /* - * The score value represents how relevant the answer is to the query relative to other answers returned for the - * query. + * The score value represents how relevant the answer is to the query relative to + * other answers returned for the query. */ + @Generated private Double score; /* * The key of the document the answer was extracted from. */ + @Generated private String key; /* * The text passage extracted from the document contents as the answer. */ + @Generated private String text; /* - * Same text passage as in the Text property with highlighted text phrases most relevant to the query. + * Same text passage as in the Text property with highlighted text phrases most + * relevant to the query. */ + @Generated private String highlights; /* - * 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. + * 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. */ - private Map additionalProperties; + @Generated + private Map additionalProperties; /** * Creates an instance of QueryAnswerResult class. */ - public QueryAnswerResult() { + @Generated + private QueryAnswerResult() { } /** - * Get the score property: The score value represents how relevant the answer is to the query relative to other - * answers returned for the query. + * Get the score property: The score value represents how relevant the answer is to the query relative to + * other answers returned for the query. * * @return the score value. */ + @Generated public Double getScore() { return this.score; } @@ -69,6 +79,7 @@ public Double getScore() { * * @return the key value. */ + @Generated public String getKey() { return this.key; } @@ -78,6 +89,7 @@ public String getKey() { * * @return the text value. */ + @Generated public String getText() { return this.text; } @@ -88,30 +100,43 @@ public String getText() { * * @return the highlights value. */ + @Generated public String getHighlights() { return this.highlights; } /** * Get the additionalProperties property: 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. + * relevant + * documents that matched the query. Answers are extracted from the top search + * results. Answer candidates are scored and the top answers are selected. * * @return the additionalProperties value. */ - public Map getAdditionalProperties() { + @Generated + public Map getAdditionalProperties() { return this.additionalProperties; } /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); + jsonWriter.writeNumberField("score", this.score); + jsonWriter.writeStringField("key", this.key); + jsonWriter.writeStringField("text", this.text); + jsonWriter.writeStringField("highlights", this.highlights); if (additionalProperties != null) { - for (Map.Entry additionalProperty : additionalProperties.entrySet()) { - jsonWriter.writeUntypedField(additionalProperty.getKey(), additionalProperty.getValue()); + for (Map.Entry additionalProperty : additionalProperties.entrySet()) { + jsonWriter.writeFieldName(additionalProperty.getKey()); + if (additionalProperty.getValue() == null) { + jsonWriter.writeNull(); + } else { + additionalProperty.getValue().writeTo(jsonWriter); + } } } return jsonWriter.writeEndObject(); @@ -125,10 +150,11 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { * pointing to JSON null. * @throws IOException If an error occurs while reading the QueryAnswerResult. */ + @Generated public static QueryAnswerResult fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { QueryAnswerResult deserializedQueryAnswerResult = new QueryAnswerResult(); - Map additionalProperties = null; + Map additionalProperties = null; while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); @@ -146,7 +172,8 @@ public static QueryAnswerResult fromJson(JsonReader jsonReader) throws IOExcepti additionalProperties = new LinkedHashMap<>(); } - additionalProperties.put(fieldName, reader.readUntyped()); + additionalProperties.put(fieldName, + reader.getNullable(nonNullReader -> BinaryData.fromObject(nonNullReader.readUntyped()))); } } deserializedQueryAnswerResult.additionalProperties = additionalProperties; diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/QueryAnswerType.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/QueryAnswerType.java index 1cd37c177f9c..d7458a16e254 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/QueryAnswerType.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/QueryAnswerType.java @@ -1,34 +1,38 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.search.documents.models; +import com.azure.core.annotation.Generated; import com.azure.core.util.ExpandableStringEnum; import java.util.Collection; /** - * 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-<number of answers>` 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-<confidence 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-<number of maximum character length>', such as - * 'extractive|maxcharlength-600'. + * 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-<number of answers>` 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-<confidence 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-<number of maximum character length>', + * such as 'extractive|maxcharlength-600'. */ public final class QueryAnswerType extends ExpandableStringEnum { /** * Do not return answers for the query. */ + @Generated public static final QueryAnswerType NONE = fromString("none"); /** - * Extracts answer candidates from the contents of the documents returned in response to a query expressed as a - * question in natural language. + * Extracts answer candidates from the contents of the documents returned in + * response to a query expressed as a question in natural language. */ + @Generated public static final QueryAnswerType EXTRACTIVE = fromString("extractive"); /** @@ -36,6 +40,7 @@ public final class QueryAnswerType extends ExpandableStringEnum * * @deprecated Use the {@link #fromString(String)} factory method. */ + @Generated @Deprecated public QueryAnswerType() { } @@ -46,6 +51,7 @@ public QueryAnswerType() { * @param name a name to look for. * @return the corresponding QueryAnswerType. */ + @Generated public static QueryAnswerType fromString(String name) { return fromString(name, QueryAnswerType.class); } @@ -55,6 +61,7 @@ public static QueryAnswerType fromString(String name) { * * @return known QueryAnswerType values. */ + @Generated public static Collection values() { return values(QueryAnswerType.class); } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/QueryCaption.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/QueryCaption.java deleted file mode 100644 index 3151027b43d8..000000000000 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/QueryCaption.java +++ /dev/null @@ -1,72 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -package com.azure.search.documents.models; - -import java.util.Objects; - -/** - * Configuration for how semantic search captions search results. - */ -public final class QueryCaption { - private final QueryCaptionType captionType; - private Boolean highlightEnabled; - private Integer maxCharLength; - - /** - * Creates a new instance of {@link QueryCaption}. - * - * @param captionType The type of captions to generate. - */ - public QueryCaption(QueryCaptionType captionType) { - this.captionType = Objects.requireNonNull(captionType, "'captionType' cannot be null."); - } - - /** - * Gets the type of captions to generate. - * - * @return The type of captions to generate. - */ - public QueryCaptionType getCaptionType() { - return captionType; - } - - /** - * Whether to highlight the captioned text in the result. - * - * @return Whether to highlight the captioned text in the result. - */ - public Boolean isHighlightEnabled() { - return highlightEnabled; - } - - /** - * Sets whether to highlight the captioned text in the result. - * - * @param highlightEnabled Whether to highlight the captioned text in the result. - * @return The QueryCaption object itself. - */ - public QueryCaption setHighlightEnabled(Boolean highlightEnabled) { - this.highlightEnabled = highlightEnabled; - return this; - } - - /** - * Gets the maximum number of characters to include in the caption. - * - * @return The maximum number of characters to include in the caption. - */ - public Integer getMaxCharLength() { - return maxCharLength; - } - - /** - * Sets the maximum number of characters to include in the caption. - * - * @param maxCharLength The maximum number of characters to include in the caption. - * @return The QueryCaption object itself. - */ - public QueryCaption setMaxCharLength(Integer maxCharLength) { - this.maxCharLength = maxCharLength; - return this; - } -} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/QueryCaptionResult.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/QueryCaptionResult.java index 5132e352b965..6178bcdb7589 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/QueryCaptionResult.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/QueryCaptionResult.java @@ -1,12 +1,12 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.search.documents.models; -import com.azure.core.annotation.Fluent; +import com.azure.core.annotation.Generated; +import com.azure.core.annotation.Immutable; +import com.azure.core.util.BinaryData; import com.azure.json.JsonReader; import com.azure.json.JsonSerializable; import com.azure.json.JsonToken; @@ -16,73 +16,93 @@ import java.util.Map; /** - * 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`. + * 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`. */ -@Fluent +@Immutable public final class QueryCaptionResult implements JsonSerializable { /* - * A representative text passage extracted from the document most relevant to the search query. + * A representative text passage extracted from the document most relevant to the + * search query. */ + @Generated private String text; /* - * Same text passage as in the Text property with highlighted phrases most relevant to the query. + * Same text passage as in the Text property with highlighted phrases most + * relevant to the query. */ + @Generated private String highlights; /* - * 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`. + * 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`. */ - private Map additionalProperties; + @Generated + private Map additionalProperties; /** * Creates an instance of QueryCaptionResult class. */ - public QueryCaptionResult() { + @Generated + private QueryCaptionResult() { } /** - * Get the text property: A representative text passage extracted from the document most relevant to the search - * query. + * Get the text property: A representative text passage extracted from the document most relevant to the + * search query. * * @return the text value. */ + @Generated public String getText() { return this.text; } /** - * Get the highlights property: Same text passage as in the Text property with highlighted phrases most relevant to - * the query. + * Get the highlights property: Same text passage as in the Text property with highlighted phrases most + * relevant to the query. * * @return the highlights value. */ + @Generated public String getHighlights() { return this.highlights; } /** * Get the additionalProperties property: 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`. + * to + * the search query. They are often used as document summary. Captions are only + * returned for queries of type `semantic`. * * @return the additionalProperties value. */ - public Map getAdditionalProperties() { + @Generated + public Map getAdditionalProperties() { return this.additionalProperties; } /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); + jsonWriter.writeStringField("text", this.text); + jsonWriter.writeStringField("highlights", this.highlights); if (additionalProperties != null) { - for (Map.Entry additionalProperty : additionalProperties.entrySet()) { - jsonWriter.writeUntypedField(additionalProperty.getKey(), additionalProperty.getValue()); + for (Map.Entry additionalProperty : additionalProperties.entrySet()) { + jsonWriter.writeFieldName(additionalProperty.getKey()); + if (additionalProperty.getValue() == null) { + jsonWriter.writeNull(); + } else { + additionalProperty.getValue().writeTo(jsonWriter); + } } } return jsonWriter.writeEndObject(); @@ -96,10 +116,11 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { * pointing to JSON null. * @throws IOException If an error occurs while reading the QueryCaptionResult. */ + @Generated public static QueryCaptionResult fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { QueryCaptionResult deserializedQueryCaptionResult = new QueryCaptionResult(); - Map additionalProperties = null; + Map additionalProperties = null; while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); @@ -113,7 +134,8 @@ public static QueryCaptionResult fromJson(JsonReader jsonReader) throws IOExcept additionalProperties = new LinkedHashMap<>(); } - additionalProperties.put(fieldName, reader.readUntyped()); + additionalProperties.put(fieldName, + reader.getNullable(nonNullReader -> BinaryData.fromObject(nonNullReader.readUntyped()))); } } deserializedQueryCaptionResult.additionalProperties = additionalProperties; diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/QueryCaptionType.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/QueryCaptionType.java index 9f6e61c7447c..22906fc08e26 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/QueryCaptionType.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/QueryCaptionType.java @@ -1,31 +1,35 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.search.documents.models; +import com.azure.core.annotation.Generated; import com.azure.core.util.ExpandableStringEnum; import java.util.Collection; /** - * 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-<true/false>` 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-<number of maximum character length>', such as - * 'extractive|maxcharlength-600'. + * 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-<true/false>` 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-<number of maximum + * character length>', such as 'extractive|maxcharlength-600'. */ public final class QueryCaptionType extends ExpandableStringEnum { /** * Do not return captions for the query. */ + @Generated public static final QueryCaptionType NONE = fromString("none"); /** - * Extracts captions from the matching documents that contain passages relevant to the search query. + * Extracts captions from the matching documents that contain passages relevant to + * the search query. */ + @Generated public static final QueryCaptionType EXTRACTIVE = fromString("extractive"); /** @@ -33,6 +37,7 @@ public final class QueryCaptionType extends ExpandableStringEnum values() { return values(QueryCaptionType.class); } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/QueryDebugMode.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/QueryDebugMode.java index 6ae5ade78bfb..a275c1538c3a 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/QueryDebugMode.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/QueryDebugMode.java @@ -1,42 +1,48 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.search.documents.models; +import com.azure.core.annotation.Generated; import com.azure.core.util.ExpandableStringEnum; import java.util.Collection; /** - * Enables a debugging tool that can be used to further explore your search results. You can enable multiple debug modes - * simultaneously by separating them with a | character, for example: semantic|queryRewrites. + * Enables a debugging tool that can be used to further explore your search + * results. You can enable multiple debug modes simultaneously by separating them + * with a | character, for example: semantic|queryRewrites. */ public final class QueryDebugMode extends ExpandableStringEnum { /** * No query debugging information will be returned. */ + @Generated public static final QueryDebugMode DISABLED = fromString("disabled"); /** * Allows the user to further explore their reranked results. */ + @Generated public static final QueryDebugMode SEMANTIC = fromString("semantic"); /** * Allows the user to further explore their hybrid and vector query results. */ + @Generated public static final QueryDebugMode VECTOR = fromString("vector"); /** - * Allows the user to explore the list of query rewrites generated for their search request. + * Allows the user to explore the list of query rewrites generated for their + * search request. */ + @Generated public static final QueryDebugMode QUERY_REWRITES = fromString("queryRewrites"); /** * Turn on all debug options. */ + @Generated public static final QueryDebugMode ALL = fromString("all"); /** @@ -44,6 +50,7 @@ public final class QueryDebugMode extends ExpandableStringEnum { * * @deprecated Use the {@link #fromString(String)} factory method. */ + @Generated @Deprecated public QueryDebugMode() { } @@ -54,6 +61,7 @@ public QueryDebugMode() { * @param name a name to look for. * @return the corresponding QueryDebugMode. */ + @Generated public static QueryDebugMode fromString(String name) { return fromString(name, QueryDebugMode.class); } @@ -63,6 +71,7 @@ public static QueryDebugMode fromString(String name) { * * @return known QueryDebugMode values. */ + @Generated public static Collection values() { return values(QueryDebugMode.class); } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/QueryLanguage.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/QueryLanguage.java index 4fc2ee4ff54f..06921d547033 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/QueryLanguage.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/QueryLanguage.java @@ -1,11 +1,10 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.search.documents.models; +import com.azure.core.annotation.Generated; import com.azure.core.util.ExpandableStringEnum; import java.util.Collection; @@ -16,361 +15,433 @@ public final class QueryLanguage extends ExpandableStringEnum { /** * Query language not specified. */ + @Generated public static final QueryLanguage NONE = fromString("none"); /** * Query language value for English (United States). */ + @Generated public static final QueryLanguage EN_US = fromString("en-us"); /** * Query language value for English (Great Britain). */ + @Generated public static final QueryLanguage EN_GB = fromString("en-gb"); /** * Query language value for English (India). */ + @Generated public static final QueryLanguage EN_IN = fromString("en-in"); /** * Query language value for English (Canada). */ + @Generated public static final QueryLanguage EN_CA = fromString("en-ca"); /** * Query language value for English (Australia). */ + @Generated public static final QueryLanguage EN_AU = fromString("en-au"); /** * Query language value for French (France). */ + @Generated public static final QueryLanguage FR_FR = fromString("fr-fr"); /** * Query language value for French (Canada). */ + @Generated public static final QueryLanguage FR_CA = fromString("fr-ca"); /** * Query language value for German (Germany). */ + @Generated public static final QueryLanguage DE_DE = fromString("de-de"); /** * Query language value for Spanish (Spain). */ + @Generated public static final QueryLanguage ES_ES = fromString("es-es"); /** * Query language value for Spanish (Mexico). */ + @Generated public static final QueryLanguage ES_MX = fromString("es-mx"); /** * Query language value for Chinese (China). */ + @Generated public static final QueryLanguage ZH_CN = fromString("zh-cn"); /** * Query language value for Chinese (Taiwan). */ + @Generated public static final QueryLanguage ZH_TW = fromString("zh-tw"); /** * Query language value for Portuguese (Brazil). */ + @Generated public static final QueryLanguage PT_BR = fromString("pt-br"); /** * Query language value for Portuguese (Portugal). */ + @Generated public static final QueryLanguage PT_PT = fromString("pt-pt"); /** * Query language value for Italian (Italy). */ + @Generated public static final QueryLanguage IT_IT = fromString("it-it"); /** * Query language value for Japanese (Japan). */ + @Generated public static final QueryLanguage JA_JP = fromString("ja-jp"); /** * Query language value for Korean (Korea). */ + @Generated public static final QueryLanguage KO_KR = fromString("ko-kr"); /** * Query language value for Russian (Russia). */ + @Generated public static final QueryLanguage RU_RU = fromString("ru-ru"); /** * Query language value for Czech (Czech Republic). */ + @Generated public static final QueryLanguage CS_CZ = fromString("cs-cz"); /** * Query language value for Dutch (Belgium). */ + @Generated public static final QueryLanguage NL_BE = fromString("nl-be"); /** * Query language value for Dutch (Netherlands). */ + @Generated public static final QueryLanguage NL_NL = fromString("nl-nl"); /** * Query language value for Hungarian (Hungary). */ + @Generated public static final QueryLanguage HU_HU = fromString("hu-hu"); /** * Query language value for Polish (Poland). */ + @Generated public static final QueryLanguage PL_PL = fromString("pl-pl"); /** * Query language value for Swedish (Sweden). */ + @Generated public static final QueryLanguage SV_SE = fromString("sv-se"); /** * Query language value for Turkish (Turkey). */ + @Generated public static final QueryLanguage TR_TR = fromString("tr-tr"); /** * Query language value for Hindi (India). */ + @Generated public static final QueryLanguage HI_IN = fromString("hi-in"); /** * Query language value for Arabic (Saudi Arabia). */ + @Generated public static final QueryLanguage AR_SA = fromString("ar-sa"); /** * Query language value for Arabic (Egypt). */ + @Generated public static final QueryLanguage AR_EG = fromString("ar-eg"); /** * Query language value for Arabic (Morocco). */ + @Generated public static final QueryLanguage AR_MA = fromString("ar-ma"); /** * Query language value for Arabic (Kuwait). */ + @Generated public static final QueryLanguage AR_KW = fromString("ar-kw"); /** * Query language value for Arabic (Jordan). */ + @Generated public static final QueryLanguage AR_JO = fromString("ar-jo"); /** * Query language value for Danish (Denmark). */ + @Generated public static final QueryLanguage DA_DK = fromString("da-dk"); /** * Query language value for Norwegian (Norway). */ + @Generated public static final QueryLanguage NO_NO = fromString("no-no"); /** * Query language value for Bulgarian (Bulgaria). */ + @Generated public static final QueryLanguage BG_BG = fromString("bg-bg"); /** * Query language value for Croatian (Croatia). */ + @Generated public static final QueryLanguage HR_HR = fromString("hr-hr"); /** * Query language value for Croatian (Bosnia and Herzegovina). */ + @Generated public static final QueryLanguage HR_BA = fromString("hr-ba"); /** * Query language value for Malay (Malaysia). */ + @Generated public static final QueryLanguage MS_MY = fromString("ms-my"); /** * Query language value for Malay (Brunei Darussalam). */ + @Generated public static final QueryLanguage MS_BN = fromString("ms-bn"); /** * Query language value for Slovenian (Slovenia). */ + @Generated public static final QueryLanguage SL_SL = fromString("sl-sl"); /** * Query language value for Tamil (India). */ + @Generated public static final QueryLanguage TA_IN = fromString("ta-in"); /** * Query language value for Vietnamese (Viet Nam). */ + @Generated public static final QueryLanguage VI_VN = fromString("vi-vn"); /** * Query language value for Greek (Greece). */ + @Generated public static final QueryLanguage EL_GR = fromString("el-gr"); /** * Query language value for Romanian (Romania). */ + @Generated public static final QueryLanguage RO_RO = fromString("ro-ro"); /** * Query language value for Icelandic (Iceland). */ + @Generated public static final QueryLanguage IS_IS = fromString("is-is"); /** * Query language value for Indonesian (Indonesia). */ + @Generated public static final QueryLanguage ID_ID = fromString("id-id"); /** * Query language value for Thai (Thailand). */ + @Generated public static final QueryLanguage TH_TH = fromString("th-th"); /** * Query language value for Lithuanian (Lithuania). */ + @Generated public static final QueryLanguage LT_LT = fromString("lt-lt"); /** * Query language value for Ukrainian (Ukraine). */ + @Generated public static final QueryLanguage UK_UA = fromString("uk-ua"); /** * Query language value for Latvian (Latvia). */ + @Generated public static final QueryLanguage LV_LV = fromString("lv-lv"); /** * Query language value for Estonian (Estonia). */ + @Generated public static final QueryLanguage ET_EE = fromString("et-ee"); /** * Query language value for Catalan. */ + @Generated public static final QueryLanguage CA_ES = fromString("ca-es"); /** * Query language value for Finnish (Finland). */ + @Generated public static final QueryLanguage FI_FI = fromString("fi-fi"); /** * Query language value for Serbian (Bosnia and Herzegovina). */ + @Generated public static final QueryLanguage SR_BA = fromString("sr-ba"); /** * Query language value for Serbian (Montenegro). */ + @Generated public static final QueryLanguage SR_ME = fromString("sr-me"); /** * Query language value for Serbian (Serbia). */ + @Generated public static final QueryLanguage SR_RS = fromString("sr-rs"); /** * Query language value for Slovak (Slovakia). */ + @Generated public static final QueryLanguage SK_SK = fromString("sk-sk"); /** * Query language value for Norwegian (Norway). */ + @Generated public static final QueryLanguage NB_NO = fromString("nb-no"); /** * Query language value for Armenian (Armenia). */ + @Generated public static final QueryLanguage HY_AM = fromString("hy-am"); /** * Query language value for Bengali (India). */ + @Generated public static final QueryLanguage BN_IN = fromString("bn-in"); /** * Query language value for Basque. */ + @Generated public static final QueryLanguage EU_ES = fromString("eu-es"); /** * Query language value for Galician. */ + @Generated public static final QueryLanguage GL_ES = fromString("gl-es"); /** * Query language value for Gujarati (India). */ + @Generated public static final QueryLanguage GU_IN = fromString("gu-in"); /** * Query language value for Hebrew (Israel). */ + @Generated public static final QueryLanguage HE_IL = fromString("he-il"); /** * Query language value for Irish (Ireland). */ + @Generated public static final QueryLanguage GA_IE = fromString("ga-ie"); /** * Query language value for Kannada (India). */ + @Generated public static final QueryLanguage KN_IN = fromString("kn-in"); /** * Query language value for Malayalam (India). */ + @Generated public static final QueryLanguage ML_IN = fromString("ml-in"); /** * Query language value for Marathi (India). */ + @Generated public static final QueryLanguage MR_IN = fromString("mr-in"); /** * Query language value for Persian (U.A.E.). */ + @Generated public static final QueryLanguage FA_AE = fromString("fa-ae"); /** * Query language value for Punjabi (India). */ + @Generated public static final QueryLanguage PA_IN = fromString("pa-in"); /** * Query language value for Telugu (India). */ + @Generated public static final QueryLanguage TE_IN = fromString("te-in"); /** * Query language value for Urdu (Pakistan). */ + @Generated public static final QueryLanguage UR_PK = fromString("ur-pk"); /** @@ -378,6 +449,7 @@ public final class QueryLanguage extends ExpandableStringEnum { * * @deprecated Use the {@link #fromString(String)} factory method. */ + @Generated @Deprecated public QueryLanguage() { } @@ -388,6 +460,7 @@ public QueryLanguage() { * @param name a name to look for. * @return the corresponding QueryLanguage. */ + @Generated public static QueryLanguage fromString(String name) { return fromString(name, QueryLanguage.class); } @@ -397,6 +470,7 @@ public static QueryLanguage fromString(String name) { * * @return known QueryLanguage values. */ + @Generated public static Collection values() { return values(QueryLanguage.class); } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/QueryResultDocumentRerankerInput.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/QueryResultDocumentRerankerInput.java index 73f316163a6f..b134e047e66c 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/QueryResultDocumentRerankerInput.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/QueryResultDocumentRerankerInput.java @@ -1,11 +1,10 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.search.documents.models; +import com.azure.core.annotation.Generated; import com.azure.core.annotation.Immutable; import com.azure.json.JsonReader; import com.azure.json.JsonSerializable; @@ -21,22 +20,28 @@ public final class QueryResultDocumentRerankerInput implements JsonSerializable< /* * The raw string for the title field that was used for semantic enrichment. */ + @Generated private String title; /* - * The raw concatenated strings for the content fields that were used for semantic enrichment. + * The raw concatenated strings for the content fields that were used for semantic + * enrichment. */ + @Generated private String content; /* - * The raw concatenated strings for the keyword fields that were used for semantic enrichment. + * The raw concatenated strings for the keyword fields that were used for semantic + * enrichment. */ + @Generated private String keywords; /** * Creates an instance of QueryResultDocumentRerankerInput class. */ - public QueryResultDocumentRerankerInput() { + @Generated + private QueryResultDocumentRerankerInput() { } /** @@ -44,6 +49,7 @@ public QueryResultDocumentRerankerInput() { * * @return the title value. */ + @Generated public String getTitle() { return this.title; } @@ -54,6 +60,7 @@ public String getTitle() { * * @return the content value. */ + @Generated public String getContent() { return this.content; } @@ -64,6 +71,7 @@ public String getContent() { * * @return the keywords value. */ + @Generated public String getKeywords() { return this.keywords; } @@ -71,6 +79,7 @@ public String getKeywords() { /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); @@ -85,6 +94,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { * null if it was pointing to JSON null. * @throws IOException If an error occurs while reading the QueryResultDocumentRerankerInput. */ + @Generated public static QueryResultDocumentRerankerInput fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { QueryResultDocumentRerankerInput deserializedQueryResultDocumentRerankerInput diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/QueryResultDocumentSemanticField.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/QueryResultDocumentSemanticField.java index 80f166ecda28..f20f50410235 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/QueryResultDocumentSemanticField.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/QueryResultDocumentSemanticField.java @@ -1,11 +1,10 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.search.documents.models; +import com.azure.core.annotation.Generated; import com.azure.core.annotation.Immutable; import com.azure.json.JsonReader; import com.azure.json.JsonSerializable; @@ -14,24 +13,29 @@ import java.io.IOException; /** - * Description of fields that were sent to the semantic enrichment process, as well as how they were used. + * Description of fields that were sent to the semantic enrichment process, as + * well as how they were used. */ @Immutable public final class QueryResultDocumentSemanticField implements JsonSerializable { /* * The name of the field that was sent to the semantic enrichment process */ + @Generated private String name; /* - * The way the field was used for the semantic enrichment process (fully used, partially used, or unused) + * The way the field was used for the semantic enrichment process (fully used, + * partially used, or unused) */ + @Generated private SemanticFieldState state; /** * Creates an instance of QueryResultDocumentSemanticField class. */ - public QueryResultDocumentSemanticField() { + @Generated + private QueryResultDocumentSemanticField() { } /** @@ -39,16 +43,18 @@ public QueryResultDocumentSemanticField() { * * @return the name value. */ + @Generated public String getName() { return this.name; } /** - * Get the state property: The way the field was used for the semantic enrichment process (fully used, partially - * used, or unused). + * Get the state property: The way the field was used for the semantic enrichment process (fully used, + * partially used, or unused). * * @return the state value. */ + @Generated public SemanticFieldState getState() { return this.state; } @@ -56,6 +62,7 @@ public SemanticFieldState getState() { /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); @@ -70,6 +77,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { * null if it was pointing to JSON null. * @throws IOException If an error occurs while reading the QueryResultDocumentSemanticField. */ + @Generated public static QueryResultDocumentSemanticField fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { QueryResultDocumentSemanticField deserializedQueryResultDocumentSemanticField diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/QueryResultDocumentSubscores.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/QueryResultDocumentSubscores.java index f692683a0ad1..b785c22a9ac1 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/QueryResultDocumentSubscores.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/QueryResultDocumentSubscores.java @@ -1,11 +1,10 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.search.documents.models; +import com.azure.core.annotation.Generated; import com.azure.core.annotation.Immutable; import com.azure.json.JsonReader; import com.azure.json.JsonSerializable; @@ -16,30 +15,35 @@ import java.util.Map; /** - * 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. + * 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. */ @Immutable public final class QueryResultDocumentSubscores implements JsonSerializable { /* * The BM25 or Classic score for the text portion of the query. */ + @Generated private TextResult text; /* * The vector similarity and @search.score values for each vector query. */ + @Generated private List> vectors; /* * The BM25 or Classic score for the text portion of the query. */ + @Generated private Double documentBoost; /** * Creates an instance of QueryResultDocumentSubscores class. */ - public QueryResultDocumentSubscores() { + @Generated + private QueryResultDocumentSubscores() { } /** @@ -47,6 +51,7 @@ public QueryResultDocumentSubscores() { * * @return the text value. */ + @Generated public TextResult getText() { return this.text; } @@ -56,6 +61,7 @@ public TextResult getText() { * * @return the vectors value. */ + @Generated public List> getVectors() { return this.vectors; } @@ -65,6 +71,7 @@ public List> getVectors() { * * @return the documentBoost value. */ + @Generated public Double getDocumentBoost() { return this.documentBoost; } @@ -72,6 +79,7 @@ public Double getDocumentBoost() { /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); @@ -86,6 +94,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { * if it was pointing to JSON null. * @throws IOException If an error occurs while reading the QueryResultDocumentSubscores. */ + @Generated public static QueryResultDocumentSubscores fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { QueryResultDocumentSubscores deserializedQueryResultDocumentSubscores = new QueryResultDocumentSubscores(); diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/QueryRewrites.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/QueryRewrites.java deleted file mode 100644 index 999f039b8adb..000000000000 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/QueryRewrites.java +++ /dev/null @@ -1,121 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -package com.azure.search.documents.models; - -import java.util.HashMap; -import java.util.Objects; - -/** - * Configuration for how semantic search rewrites a query. - */ -public class QueryRewrites { - - private final QueryRewritesType rewritesType; - private Integer count; - - /** - * Creates a new instance of {@link QueryRewrites}. - * - * @param rewritesType The type of query rewrites to perform. - * @throws NullPointerException If {@code rewritesType} is null. - */ - public QueryRewrites(QueryRewritesType rewritesType) { - this.rewritesType = Objects.requireNonNull(rewritesType, "'rewritesType' cannot be null"); - } - - /** - * Gets the type of query rewrites to perform. - * - * @return The type of query rewrites to perform. - */ - public QueryRewritesType getRewritesType() { - return rewritesType; - } - - /** - * Gets the number of rewrites to generate. - *

- * The number of rewrites to return is optional and will default to 10. - * - * @return The number of rewrites to generate. - */ - public Integer getCount() { - return count; - } - - /** - * Sets the number of rewrites to generate. - *

- * The number of rewrites to return is optional and will default to 10. - * - * @param count The number of rewrites to generate. - * @return The QueryRewrites object itself. - */ - public QueryRewrites setCount(Integer count) { - this.count = count; - return this; - } - - @Override - public String toString() { - String queryRewritesTypeString = rewritesType.toString(); - - if (rewritesType == QueryRewritesType.NONE || count == null) { - return queryRewritesTypeString; - } - - return queryRewritesTypeString + "|count-" + count; - } - - @Override - public int hashCode() { - return Objects.hash(rewritesType, count); - } - - @Override - public boolean equals(Object obj) { - if (!(obj instanceof QueryRewrites)) { - return false; - } - - QueryRewrites other = (QueryRewrites) obj; - return Objects.equals(rewritesType, other.rewritesType) && Objects.equals(count, other.count); - } - - /** - * Parses a {@link QueryRewrites} from a string. - * @param str The string to parse. - * @return The parsed {@link QueryRewrites}. - * @throws IllegalArgumentException If the string is invalid. - */ - public static QueryRewrites fromString(String str) { - if (str == null || str.isEmpty()) { - return null; - } - - if (!str.contains("|")) { - return new QueryRewrites(QueryRewritesType.fromString(str)); - } - - String[] parts = new String[2]; - - parts[0] = str.substring(0, str.indexOf("|")); - parts[1] = str.substring(str.indexOf("|") + 1); - QueryRewritesType rewritesType = QueryRewritesType.fromString(parts[0]); - HashMap queryRewriteOptions = new HashMap<>(); - for (String queryRewriteOption : parts[1].split(",")) { - if (queryRewriteOption.contains("-")) { - String[] optionParts = queryRewriteOption.split("-"); - queryRewriteOptions.putIfAbsent(optionParts[0], optionParts[1]); - } - } - - QueryRewrites queryRewrites = new QueryRewrites(rewritesType); - - if (queryRewriteOptions.containsKey("count")) { - queryRewrites.setCount(Integer.parseInt(queryRewriteOptions.get("count").toString())); - } - - return queryRewrites; - } -} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/QueryRewritesDebugInfo.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/QueryRewritesDebugInfo.java index d4b909929095..ed51c4d3e80a 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/QueryRewritesDebugInfo.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/QueryRewritesDebugInfo.java @@ -1,11 +1,10 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.search.documents.models; +import com.azure.core.annotation.Generated; import com.azure.core.annotation.Immutable; import com.azure.json.JsonReader; import com.azure.json.JsonSerializable; @@ -22,17 +21,20 @@ public final class QueryRewritesDebugInfo implements JsonSerializable vectors; /** * Creates an instance of QueryRewritesDebugInfo class. */ - public QueryRewritesDebugInfo() { + @Generated + private QueryRewritesDebugInfo() { } /** @@ -40,6 +42,7 @@ public QueryRewritesDebugInfo() { * * @return the text value. */ + @Generated public QueryRewritesValuesDebugInfo getText() { return this.text; } @@ -49,6 +52,7 @@ public QueryRewritesValuesDebugInfo getText() { * * @return the vectors value. */ + @Generated public List getVectors() { return this.vectors; } @@ -56,6 +60,7 @@ public List getVectors() { /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); @@ -70,6 +75,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { * was pointing to JSON null. * @throws IOException If an error occurs while reading the QueryRewritesDebugInfo. */ + @Generated public static QueryRewritesDebugInfo fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { QueryRewritesDebugInfo deserializedQueryRewritesDebugInfo = new QueryRewritesDebugInfo(); diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/QueryRewritesType.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/QueryRewritesType.java index 63990d3da5f6..cc341e53753d 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/QueryRewritesType.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/QueryRewritesType.java @@ -1,29 +1,32 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.search.documents.models; +import com.azure.core.annotation.Generated; import com.azure.core.util.ExpandableStringEnum; import java.util.Collection; /** - * 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) rewrites to help increase the recall of the - * request. The requested count can be configured by appending the pipe character `|` followed by the `count-<number - * of rewrites>` option, such as `generative|count-3`. Defaults to `None`. + * 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) rewrites to help increase the recall of + * the request. The requested count can be configured by appending the pipe + * character `|` followed by the `count-<number of rewrites>` option, such as + * `generative|count-3`. Defaults to `None`. */ public final class QueryRewritesType extends ExpandableStringEnum { /** * Do not generate additional query rewrites for this query. */ + @Generated public static final QueryRewritesType NONE = fromString("none"); /** * Generate alternative query terms to increase the recall of a search request. */ + @Generated public static final QueryRewritesType GENERATIVE = fromString("generative"); /** @@ -31,6 +34,7 @@ public final class QueryRewritesType extends ExpandableStringEnum values() { return values(QueryRewritesType.class); } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/QueryRewritesValuesDebugInfo.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/QueryRewritesValuesDebugInfo.java index d0f08949eb8a..9443d795249f 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/QueryRewritesValuesDebugInfo.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/QueryRewritesValuesDebugInfo.java @@ -1,11 +1,10 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.search.documents.models; +import com.azure.core.annotation.Generated; import com.azure.core.annotation.Immutable; import com.azure.json.JsonReader; import com.azure.json.JsonSerializable; @@ -20,28 +19,32 @@ @Immutable public final class QueryRewritesValuesDebugInfo implements JsonSerializable { /* - * 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. + * 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. */ + @Generated private String inputQuery; /* * List of query rewrites. */ + @Generated private List rewrites; /** * Creates an instance of QueryRewritesValuesDebugInfo class. */ - public QueryRewritesValuesDebugInfo() { + @Generated + private QueryRewritesValuesDebugInfo() { } /** - * Get the inputQuery property: 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. + * Get the inputQuery property: 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. * * @return the inputQuery value. */ + @Generated public String getInputQuery() { return this.inputQuery; } @@ -51,6 +54,7 @@ public String getInputQuery() { * * @return the rewrites value. */ + @Generated public List getRewrites() { return this.rewrites; } @@ -58,6 +62,7 @@ public List getRewrites() { /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); @@ -72,6 +77,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { * if it was pointing to JSON null. * @throws IOException If an error occurs while reading the QueryRewritesValuesDebugInfo. */ + @Generated public static QueryRewritesValuesDebugInfo fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { QueryRewritesValuesDebugInfo deserializedQueryRewritesValuesDebugInfo = new QueryRewritesValuesDebugInfo(); diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/QuerySpellerType.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/QuerySpellerType.java index 391b9f6a435e..3c922e2f4c63 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/QuerySpellerType.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/QuerySpellerType.java @@ -1,11 +1,10 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.search.documents.models; +import com.azure.core.annotation.Generated; import com.azure.core.util.ExpandableStringEnum; import java.util.Collection; @@ -16,12 +15,14 @@ public final class QuerySpellerType extends ExpandableStringEnum values() { return values(QuerySpellerType.class); } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/QueryType.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/QueryType.java index 16bc144e9de7..33274b8d57b6 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/QueryType.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/QueryType.java @@ -1,68 +1,72 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.search.documents.models; +import com.azure.core.annotation.Generated; +import com.azure.core.util.ExpandableStringEnum; +import java.util.Collection; + /** - * Specifies the syntax of the search query. The default is 'simple'. Use 'full' if your query uses the Lucene query - * syntax and 'semantic' if query syntax is not needed. + * Specifies the syntax of the search query. The default is 'simple'. Use 'full' + * if your query uses the Lucene query syntax and 'semantic' if query syntax is + * not needed. */ -public enum QueryType { +public final class QueryType extends ExpandableStringEnum { /** - * Uses the simple query syntax for searches. Search text is interpreted using a simple query language that allows - * for symbols such as +, * and "". Queries are evaluated across all searchable fields by default, unless the - * searchFields parameter is specified. + * Uses the simple query syntax for searches. Search text is interpreted using a + * simple query language that allows for symbols such as +, * and "". Queries are + * evaluated across all searchable fields by default, unless the searchFields + * parameter is specified. */ - SIMPLE("simple"), + @Generated + public static final QueryType SIMPLE = fromString("simple"); /** - * Uses the full Lucene query syntax for searches. Search text is interpreted using the Lucene query language which - * allows field-specific and weighted searches, as well as other advanced features. + * Uses the full Lucene query syntax for searches. Search text is interpreted + * using the Lucene query language which allows field-specific and weighted + * searches, as well as other advanced features. */ - FULL("full"), + @Generated + public static final QueryType FULL = fromString("full"); /** - * Best suited for queries expressed in natural language as opposed to keywords. Improves precision of search - * results by re-ranking the top search results using a ranking model trained on the Web corpus. + * Best suited for queries expressed in natural language as opposed to keywords. + * Improves precision of search results by re-ranking the top search results using + * a ranking model trained on the Web corpus. */ - SEMANTIC("semantic"); + @Generated + public static final QueryType SEMANTIC = fromString("semantic"); /** - * The actual serialized value for a QueryType instance. + * Creates a new instance of QueryType value. + * + * @deprecated Use the {@link #fromString(String)} factory method. */ - private final String value; - - QueryType(String value) { - this.value = value; + @Generated + @Deprecated + public QueryType() { } /** - * Parses a serialized value to a QueryType instance. + * Creates or finds a QueryType from its string representation. * - * @param value the serialized value to parse. - * @return the parsed QueryType object, or null if unable to parse. + * @param name a name to look for. + * @return the corresponding QueryType. */ - public static QueryType fromString(String value) { - if (value == null) { - return null; - } - QueryType[] items = QueryType.values(); - for (QueryType item : items) { - if (item.toString().equalsIgnoreCase(value)) { - return item; - } - } - return null; + @Generated + public static QueryType fromString(String name) { + return fromString(name, QueryType.class); } /** - * {@inheritDoc} + * Gets known QueryType values. + * + * @return known QueryType values. */ - @Override - public String toString() { - return this.value; + @Generated + public static Collection values() { + return values(QueryType.class); } } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/RangeFacetResult.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/RangeFacetResult.java deleted file mode 100644 index e12780ed73f8..000000000000 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/RangeFacetResult.java +++ /dev/null @@ -1,75 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.search.documents.models; - -import com.azure.core.annotation.Immutable; - -/** - * A single bucket of a range facet query result that reports the number of documents with a field value falling within - * a particular range. - * - * @param The type of the facets. - */ -@Immutable -public class RangeFacetResult { - private static final String FROM = "from"; - private static final String TO = "to"; - private final Long count; - private final T from; - private final T to; - - /** - * Constructor of RangeFacetResult. - * - * @param count The count of the result. - * @param from Value indicates the lower bound of facet's range - * @param to Value indicates the upper bound of facet's range - */ - public RangeFacetResult(Long count, T from, T to) { - this.count = count; - this.from = from; - this.to = to; - } - - /** - * Constructor from {@link FacetResult} - * - * @param facetResult {@link FacetResult}. - */ - @SuppressWarnings("unchecked") - public RangeFacetResult(FacetResult facetResult) { - this.count = facetResult.getCount(); - this.from = (T) facetResult.getAdditionalProperties().get(FROM); - this.to = (T) facetResult.getAdditionalProperties().get(TO); - } - - /** - * Gets the approximate count of documents falling within the bucket described by this facet. - * - * @return count - */ - public Long getCount() { - return count; - } - - /** - * Gets a value indicating the inclusive lower bound of the facet's range, or null to indicate that there is no - * lower bound (i.e. -- for the first bucket). - * - * @return from - */ - public T getFrom() { - return from; - } - - /** - * Gets a value indicating the exclusive upper bound of the facet's range, or null to indicate that there is no - * upper bound (i.e. -- for the last bucket). - * - * @return to - */ - public T getTo() { - return to; - } -} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/RegexFlags.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/RegexFlags.java similarity index 84% rename from sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/RegexFlags.java rename to sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/RegexFlags.java index b50ac9ef6e80..298bc501fc98 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/RegexFlags.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/RegexFlags.java @@ -1,57 +1,64 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) TypeSpec Code Generator. -package com.azure.search.documents.indexes.models; +package com.azure.search.documents.models; +import com.azure.core.annotation.Generated; import com.azure.core.util.ExpandableStringEnum; import java.util.Collection; /** - * Defines flags that can be combined to control how regular expressions are used in the pattern analyzer and pattern - * tokenizer. + * Defines flags that can be combined to control how regular expressions are used + * in the pattern analyzer and pattern tokenizer. */ public final class RegexFlags extends ExpandableStringEnum { /** * Enables canonical equivalence. */ + @Generated public static final RegexFlags CANON_EQ = fromString("CANON_EQ"); /** * Enables case-insensitive matching. */ + @Generated public static final RegexFlags CASE_INSENSITIVE = fromString("CASE_INSENSITIVE"); /** * Permits whitespace and comments in the pattern. */ + @Generated public static final RegexFlags COMMENTS = fromString("COMMENTS"); /** * Enables dotall mode. */ + @Generated public static final RegexFlags DOT_ALL = fromString("DOTALL"); /** * Enables literal parsing of the pattern. */ + @Generated public static final RegexFlags LITERAL = fromString("LITERAL"); /** * Enables multiline mode. */ + @Generated public static final RegexFlags MULTILINE = fromString("MULTILINE"); /** * Enables Unicode-aware case folding. */ + @Generated public static final RegexFlags UNICODE_CASE = fromString("UNICODE_CASE"); /** * Enables Unix lines mode. */ + @Generated public static final RegexFlags UNIX_LINES = fromString("UNIX_LINES"); /** @@ -59,6 +66,7 @@ public final class RegexFlags extends ExpandableStringEnum { * * @deprecated Use the {@link #fromString(String)} factory method. */ + @Generated @Deprecated public RegexFlags() { } @@ -69,6 +77,7 @@ public RegexFlags() { * @param name a name to look for. * @return the corresponding RegexFlags. */ + @Generated public static RegexFlags fromString(String name) { return fromString(name, RegexFlags.class); } @@ -78,6 +87,7 @@ public static RegexFlags fromString(String name) { * * @return known RegexFlags values. */ + @Generated public static Collection values() { return values(RegexFlags.class); } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/RescoringOptions.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/RescoringOptions.java similarity index 75% rename from sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/RescoringOptions.java rename to sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/RescoringOptions.java index ea13db2bfac3..c6d3463ee5bb 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/RescoringOptions.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/RescoringOptions.java @@ -1,12 +1,11 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) TypeSpec Code Generator. -package com.azure.search.documents.indexes.models; +package com.azure.search.documents.models; import com.azure.core.annotation.Fluent; +import com.azure.core.annotation.Generated; import com.azure.json.JsonReader; import com.azure.json.JsonSerializable; import com.azure.json.JsonToken; @@ -19,49 +18,57 @@ @Fluent public final class RescoringOptions implements JsonSerializable { /* - * 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. + * 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. */ + @Generated private Boolean enableRescoring; /* - * 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. + * 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. */ + @Generated private Double defaultOversampling; /* * Controls the storage method for original vectors. This setting is immutable. */ + @Generated private VectorSearchCompressionRescoreStorageMethod rescoreStorageMethod; /** * Creates an instance of RescoringOptions class. */ + @Generated public RescoringOptions() { } /** * Get the enableRescoring property: 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. + * similarity scores are recalculated using the full-precision vectors. This will + * improve recall at the expense of latency. * * @return the enableRescoring value. */ + @Generated public Boolean isEnableRescoring() { return this.enableRescoring; } /** * Set the enableRescoring property: 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. + * similarity scores are recalculated using the full-precision vectors. This will + * improve recall at the expense of latency. * * @param enableRescoring the enableRescoring value to set. * @return the RescoringOptions object itself. */ + @Generated public RescoringOptions setEnableRescoring(Boolean enableRescoring) { this.enableRescoring = enableRescoring; return this; @@ -69,25 +76,31 @@ public RescoringOptions setEnableRescoring(Boolean enableRescoring) { /** * Get the defaultOversampling property: 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. + * 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. * * @return the defaultOversampling value. */ + @Generated public Double getDefaultOversampling() { return this.defaultOversampling; } /** * Set the defaultOversampling property: 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. + * 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. * * @param defaultOversampling the defaultOversampling value to set. * @return the RescoringOptions object itself. */ + @Generated public RescoringOptions setDefaultOversampling(Double defaultOversampling) { this.defaultOversampling = defaultOversampling; return this; @@ -99,6 +112,7 @@ public RescoringOptions setDefaultOversampling(Double defaultOversampling) { * * @return the rescoreStorageMethod value. */ + @Generated public VectorSearchCompressionRescoreStorageMethod getRescoreStorageMethod() { return this.rescoreStorageMethod; } @@ -110,6 +124,7 @@ public VectorSearchCompressionRescoreStorageMethod getRescoreStorageMethod() { * @param rescoreStorageMethod the rescoreStorageMethod value to set. * @return the RescoringOptions object itself. */ + @Generated public RescoringOptions setRescoreStorageMethod(VectorSearchCompressionRescoreStorageMethod rescoreStorageMethod) { this.rescoreStorageMethod = rescoreStorageMethod; return this; @@ -118,6 +133,7 @@ public RescoringOptions setRescoreStorageMethod(VectorSearchCompressionRescoreSt /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); @@ -136,6 +152,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { * pointing to JSON null. * @throws IOException If an error occurs while reading the RescoringOptions. */ + @Generated public static RescoringOptions fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { RescoringOptions deserializedRescoringOptions = new RescoringOptions(); diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/ResourceCounter.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/ResourceCounter.java similarity index 72% rename from sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/ResourceCounter.java rename to sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/ResourceCounter.java index 2a8aee93380b..c308d3f11682 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/ResourceCounter.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/ResourceCounter.java @@ -1,12 +1,11 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) TypeSpec Code Generator. -package com.azure.search.documents.indexes.models; +package com.azure.search.documents.models; -import com.azure.core.annotation.Fluent; +import com.azure.core.annotation.Generated; +import com.azure.core.annotation.Immutable; import com.azure.json.JsonReader; import com.azure.json.JsonSerializable; import com.azure.json.JsonToken; @@ -16,16 +15,18 @@ /** * Represents a resource's usage and quota. */ -@Fluent +@Immutable public final class ResourceCounter implements JsonSerializable { /* * The resource usage amount. */ + @Generated private final long usage; /* * The resource amount quota. */ + @Generated private Long quota; /** @@ -33,7 +34,8 @@ public final class ResourceCounter implements JsonSerializable * * @param usage the usage value to set. */ - public ResourceCounter(long usage) { + @Generated + private ResourceCounter(long usage) { this.usage = usage; } @@ -42,6 +44,7 @@ public ResourceCounter(long usage) { * * @return the usage value. */ + @Generated public long getUsage() { return this.usage; } @@ -51,24 +54,15 @@ public long getUsage() { * * @return the quota value. */ + @Generated public Long getQuota() { return this.quota; } - /** - * Set the quota property: The resource amount quota. - * - * @param quota the quota value to set. - * @return the ResourceCounter object itself. - */ - public ResourceCounter setQuota(Long quota) { - this.quota = quota; - return this; - } - /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); @@ -86,9 +80,9 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { * @throws IllegalStateException If the deserialized JSON object was missing any required properties. * @throws IOException If an error occurs while reading the ResourceCounter. */ + @Generated public static ResourceCounter fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { - boolean usageFound = false; long usage = 0L; Long quota = null; while (reader.nextToken() != JsonToken.END_OBJECT) { @@ -97,20 +91,16 @@ public static ResourceCounter fromJson(JsonReader jsonReader) throws IOException if ("usage".equals(fieldName)) { usage = reader.getLong(); - usageFound = true; } else if ("quota".equals(fieldName)) { quota = reader.getNullable(JsonReader::getLong); } else { reader.skipChildren(); } } - if (usageFound) { - ResourceCounter deserializedResourceCounter = new ResourceCounter(usage); - deserializedResourceCounter.quota = quota; + ResourceCounter deserializedResourceCounter = new ResourceCounter(usage); + deserializedResourceCounter.quota = quota; - return deserializedResourceCounter; - } - throw new IllegalStateException("Missing required property: usage"); + return deserializedResourceCounter; }); } } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/ScalarQuantizationCompression.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/ScalarQuantizationCompression.java similarity index 79% rename from sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/ScalarQuantizationCompression.java rename to sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/ScalarQuantizationCompression.java index 7eabb7581648..2bb3bf728012 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/ScalarQuantizationCompression.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/ScalarQuantizationCompression.java @@ -1,31 +1,32 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) TypeSpec Code Generator. -package com.azure.search.documents.indexes.models; +package com.azure.search.documents.models; import com.azure.core.annotation.Fluent; +import com.azure.core.annotation.Generated; import com.azure.json.JsonReader; import com.azure.json.JsonToken; import com.azure.json.JsonWriter; import java.io.IOException; /** - * Contains configuration options specific to the scalar quantization compression method used during indexing and - * querying. + * Contains configuration options specific to the scalar quantization compression + * method used during indexing and querying. */ @Fluent public final class ScalarQuantizationCompression extends VectorSearchCompression { /* - * The name of the kind of compression method being configured for use with vector search. + * Type of VectorSearchCompression. */ + @Generated private VectorSearchCompressionKind kind = VectorSearchCompressionKind.SCALAR_QUANTIZATION; /* * Contains the parameters specific to Scalar Quantization. */ + @Generated private ScalarQuantizationParameters parameters; /** @@ -33,15 +34,17 @@ public final class ScalarQuantizationCompression extends VectorSearchCompression * * @param compressionName the compressionName value to set. */ + @Generated public ScalarQuantizationCompression(String compressionName) { super(compressionName); } /** - * Get the kind property: The name of the kind of compression method being configured for use with vector search. + * Get the kind property: Type of VectorSearchCompression. * * @return the kind value. */ + @Generated @Override public VectorSearchCompressionKind getKind() { return this.kind; @@ -52,6 +55,7 @@ public VectorSearchCompressionKind getKind() { * * @return the parameters value. */ + @Generated public ScalarQuantizationParameters getParameters() { return this.parameters; } @@ -62,6 +66,7 @@ public ScalarQuantizationParameters getParameters() { * @param parameters the parameters value to set. * @return the ScalarQuantizationCompression object itself. */ + @Generated public ScalarQuantizationCompression setParameters(ScalarQuantizationParameters parameters) { this.parameters = parameters; return this; @@ -70,6 +75,7 @@ public ScalarQuantizationCompression setParameters(ScalarQuantizationParameters /** * {@inheritDoc} */ + @Generated @Override public ScalarQuantizationCompression setRerankWithOriginalVectors(Boolean rerankWithOriginalVectors) { super.setRerankWithOriginalVectors(rerankWithOriginalVectors); @@ -79,6 +85,7 @@ public ScalarQuantizationCompression setRerankWithOriginalVectors(Boolean rerank /** * {@inheritDoc} */ + @Generated @Override public ScalarQuantizationCompression setDefaultOversampling(Double defaultOversampling) { super.setDefaultOversampling(defaultOversampling); @@ -88,6 +95,7 @@ public ScalarQuantizationCompression setDefaultOversampling(Double defaultOversa /** * {@inheritDoc} */ + @Generated @Override public ScalarQuantizationCompression setRescoringOptions(RescoringOptions rescoringOptions) { super.setRescoringOptions(rescoringOptions); @@ -97,6 +105,7 @@ public ScalarQuantizationCompression setRescoringOptions(RescoringOptions rescor /** * {@inheritDoc} */ + @Generated @Override public ScalarQuantizationCompression setTruncationDimension(Integer truncationDimension) { super.setTruncationDimension(truncationDimension); @@ -106,6 +115,7 @@ public ScalarQuantizationCompression setTruncationDimension(Integer truncationDi /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); @@ -128,9 +138,9 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { * @throws IllegalStateException If the deserialized JSON object was missing any required properties. * @throws IOException If an error occurs while reading the ScalarQuantizationCompression. */ + @Generated public static ScalarQuantizationCompression fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { - boolean compressionNameFound = false; String compressionName = null; Boolean rerankWithOriginalVectors = null; Double defaultOversampling = null; @@ -144,7 +154,6 @@ public static ScalarQuantizationCompression fromJson(JsonReader jsonReader) thro if ("name".equals(fieldName)) { compressionName = reader.getString(); - compressionNameFound = true; } else if ("rerankWithOriginalVectors".equals(fieldName)) { rerankWithOriginalVectors = reader.getNullable(JsonReader::getBoolean); } else if ("defaultOversampling".equals(fieldName)) { @@ -161,19 +170,16 @@ public static ScalarQuantizationCompression fromJson(JsonReader jsonReader) thro reader.skipChildren(); } } - if (compressionNameFound) { - ScalarQuantizationCompression deserializedScalarQuantizationCompression - = new ScalarQuantizationCompression(compressionName); - deserializedScalarQuantizationCompression.setRerankWithOriginalVectors(rerankWithOriginalVectors); - deserializedScalarQuantizationCompression.setDefaultOversampling(defaultOversampling); - deserializedScalarQuantizationCompression.setRescoringOptions(rescoringOptions); - deserializedScalarQuantizationCompression.setTruncationDimension(truncationDimension); - deserializedScalarQuantizationCompression.kind = kind; - deserializedScalarQuantizationCompression.parameters = parameters; - - return deserializedScalarQuantizationCompression; - } - throw new IllegalStateException("Missing required property: name"); + ScalarQuantizationCompression deserializedScalarQuantizationCompression + = new ScalarQuantizationCompression(compressionName); + deserializedScalarQuantizationCompression.setRerankWithOriginalVectors(rerankWithOriginalVectors); + deserializedScalarQuantizationCompression.setDefaultOversampling(defaultOversampling); + deserializedScalarQuantizationCompression.setRescoringOptions(rescoringOptions); + deserializedScalarQuantizationCompression.setTruncationDimension(truncationDimension); + deserializedScalarQuantizationCompression.kind = kind; + deserializedScalarQuantizationCompression.parameters = parameters; + + return deserializedScalarQuantizationCompression; }); } } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/ScalarQuantizationParameters.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/ScalarQuantizationParameters.java similarity index 92% rename from sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/ScalarQuantizationParameters.java rename to sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/ScalarQuantizationParameters.java index 5cc029026e81..88e178d8028c 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/ScalarQuantizationParameters.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/ScalarQuantizationParameters.java @@ -1,12 +1,11 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) TypeSpec Code Generator. -package com.azure.search.documents.indexes.models; +package com.azure.search.documents.models; import com.azure.core.annotation.Fluent; +import com.azure.core.annotation.Generated; import com.azure.json.JsonReader; import com.azure.json.JsonSerializable; import com.azure.json.JsonToken; @@ -21,11 +20,13 @@ public final class ScalarQuantizationParameters implements JsonSerializable { ScalarQuantizationParameters deserializedScalarQuantizationParameters = new ScalarQuantizationParameters(); diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/ScoringFunction.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/ScoringFunction.java similarity index 80% rename from sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/ScoringFunction.java rename to sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/ScoringFunction.java index cc8ec514c633..a5adbb71c6a2 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/ScoringFunction.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/ScoringFunction.java @@ -1,19 +1,16 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) TypeSpec Code Generator. -package com.azure.search.documents.indexes.models; +package com.azure.search.documents.models; import com.azure.core.annotation.Fluent; +import com.azure.core.annotation.Generated; import com.azure.json.JsonReader; import com.azure.json.JsonSerializable; import com.azure.json.JsonToken; import com.azure.json.JsonWriter; import java.io.IOException; -import java.util.ArrayList; -import java.util.List; /** * Base type for functions that can modify document scores during ranking. @@ -21,24 +18,28 @@ @Fluent public class ScoringFunction implements JsonSerializable { /* - * Indicates the type of function to use. Valid values include magnitude, freshness, distance, and tag. The function - * type must be lower case. + * Type of ScoringFunction. */ + @Generated private String type = "ScoringFunction"; /* * The name of the field used as input to the scoring function. */ + @Generated private final String fieldName; /* * A multiplier for the raw score. Must be a positive number not equal to 1.0. */ + @Generated private final double boost; /* - * A value indicating how boosting will be interpolated across document scores; defaults to "Linear". + * A value indicating how boosting will be interpolated across document scores; + * defaults to "Linear". */ + @Generated private ScoringFunctionInterpolation interpolation; /** @@ -47,17 +48,18 @@ public class ScoringFunction implements JsonSerializable { * @param fieldName the fieldName value to set. * @param boost the boost value to set. */ + @Generated public ScoringFunction(String fieldName, double boost) { this.fieldName = fieldName; this.boost = boost; } /** - * Get the type property: Indicates the type of function to use. Valid values include magnitude, freshness, - * distance, and tag. The function type must be lower case. + * Get the type property: Type of ScoringFunction. * * @return the type value. */ + @Generated public String getType() { return this.type; } @@ -67,6 +69,7 @@ public String getType() { * * @return the fieldName value. */ + @Generated public String getFieldName() { return this.fieldName; } @@ -76,6 +79,7 @@ public String getFieldName() { * * @return the boost value. */ + @Generated public double getBoost() { return this.boost; } @@ -86,6 +90,7 @@ public double getBoost() { * * @return the interpolation value. */ + @Generated public ScoringFunctionInterpolation getInterpolation() { return this.interpolation; } @@ -97,6 +102,7 @@ public ScoringFunctionInterpolation getInterpolation() { * @param interpolation the interpolation value to set. * @return the ScoringFunction object itself. */ + @Generated public ScoringFunction setInterpolation(ScoringFunctionInterpolation interpolation) { this.interpolation = interpolation; return this; @@ -105,6 +111,7 @@ public ScoringFunction setInterpolation(ScoringFunctionInterpolation interpolati /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); @@ -124,6 +131,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { * @throws IllegalStateException If the deserialized JSON object was missing any required properties. * @throws IOException If an error occurs while reading the ScoringFunction. */ + @Generated public static ScoringFunction fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { String discriminatorValue = null; @@ -155,11 +163,10 @@ public static ScoringFunction fromJson(JsonReader jsonReader) throws IOException }); } + @Generated static ScoringFunction fromJsonKnownDiscriminator(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { - boolean fieldNameFound = false; String fieldName = null; - boolean boostFound = false; double boost = 0.0; String type = null; ScoringFunctionInterpolation interpolation = null; @@ -169,10 +176,8 @@ static ScoringFunction fromJsonKnownDiscriminator(JsonReader jsonReader) throws if ("fieldName".equals(jsonFieldName)) { fieldName = reader.getString(); - fieldNameFound = true; } else if ("boost".equals(jsonFieldName)) { boost = reader.getDouble(); - boostFound = true; } else if ("type".equals(jsonFieldName)) { type = reader.getString(); } else if ("interpolation".equals(jsonFieldName)) { @@ -181,23 +186,11 @@ static ScoringFunction fromJsonKnownDiscriminator(JsonReader jsonReader) throws reader.skipChildren(); } } - if (fieldNameFound && boostFound) { - ScoringFunction deserializedScoringFunction = new ScoringFunction(fieldName, boost); - deserializedScoringFunction.type = type; - deserializedScoringFunction.interpolation = interpolation; - - return deserializedScoringFunction; - } - List missingProperties = new ArrayList<>(); - if (!fieldNameFound) { - missingProperties.add("fieldName"); - } - if (!boostFound) { - missingProperties.add("boost"); - } + ScoringFunction deserializedScoringFunction = new ScoringFunction(fieldName, boost); + deserializedScoringFunction.type = type; + deserializedScoringFunction.interpolation = interpolation; - throw new IllegalStateException( - "Missing required property/properties: " + String.join(", ", missingProperties)); + return deserializedScoringFunction; }); } } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/ScoringFunctionAggregation.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/ScoringFunctionAggregation.java new file mode 100644 index 000000000000..5f253819a564 --- /dev/null +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/ScoringFunctionAggregation.java @@ -0,0 +1,76 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.search.documents.models; + +import com.azure.core.annotation.Generated; +import com.azure.core.util.ExpandableStringEnum; +import java.util.Collection; + +/** + * Defines the aggregation function used to combine the results of all the scoring + * functions in a scoring profile. + */ +public final class ScoringFunctionAggregation extends ExpandableStringEnum { + /** + * Boost scores by the sum of all scoring function results. + */ + @Generated + public static final ScoringFunctionAggregation SUM = fromString("sum"); + + /** + * Boost scores by the average of all scoring function results. + */ + @Generated + public static final ScoringFunctionAggregation AVERAGE = fromString("average"); + + /** + * Boost scores by the minimum of all scoring function results. + */ + @Generated + public static final ScoringFunctionAggregation MINIMUM = fromString("minimum"); + + /** + * Boost scores by the maximum of all scoring function results. + */ + @Generated + public static final ScoringFunctionAggregation MAXIMUM = fromString("maximum"); + + /** + * Boost scores using the first applicable scoring function in the scoring profile. + */ + @Generated + public static final ScoringFunctionAggregation FIRST_MATCHING = fromString("firstMatching"); + + /** + * Creates a new instance of ScoringFunctionAggregation value. + * + * @deprecated Use the {@link #fromString(String)} factory method. + */ + @Generated + @Deprecated + public ScoringFunctionAggregation() { + } + + /** + * Creates or finds a ScoringFunctionAggregation from its string representation. + * + * @param name a name to look for. + * @return the corresponding ScoringFunctionAggregation. + */ + @Generated + public static ScoringFunctionAggregation fromString(String name) { + return fromString(name, ScoringFunctionAggregation.class); + } + + /** + * Gets known ScoringFunctionAggregation values. + * + * @return known ScoringFunctionAggregation values. + */ + @Generated + public static Collection values() { + return values(ScoringFunctionAggregation.class); + } +} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/ScoringFunctionInterpolation.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/ScoringFunctionInterpolation.java new file mode 100644 index 000000000000..da6551c7e94b --- /dev/null +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/ScoringFunctionInterpolation.java @@ -0,0 +1,75 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.search.documents.models; + +import com.azure.core.annotation.Generated; +import com.azure.core.util.ExpandableStringEnum; +import java.util.Collection; + +/** + * Defines the function used to interpolate score boosting across a range of + * documents. + */ +public final class ScoringFunctionInterpolation extends ExpandableStringEnum { + /** + * Boosts scores by a linearly decreasing amount. This is the default + * interpolation for scoring functions. + */ + @Generated + public static final ScoringFunctionInterpolation LINEAR = fromString("linear"); + + /** + * Boosts scores by a constant factor. + */ + @Generated + public static final ScoringFunctionInterpolation CONSTANT = fromString("constant"); + + /** + * Boosts scores by an amount that decreases quadratically. Boosts decrease slowly + * for higher scores, and more quickly as the scores decrease. This interpolation + * option is not allowed in tag scoring functions. + */ + @Generated + public static final ScoringFunctionInterpolation QUADRATIC = fromString("quadratic"); + + /** + * Boosts scores by an amount that decreases logarithmically. Boosts decrease + * quickly for higher scores, and more slowly as the scores decrease. This + * interpolation option is not allowed in tag scoring functions. + */ + @Generated + public static final ScoringFunctionInterpolation LOGARITHMIC = fromString("logarithmic"); + + /** + * Creates a new instance of ScoringFunctionInterpolation value. + * + * @deprecated Use the {@link #fromString(String)} factory method. + */ + @Generated + @Deprecated + public ScoringFunctionInterpolation() { + } + + /** + * Creates or finds a ScoringFunctionInterpolation from its string representation. + * + * @param name a name to look for. + * @return the corresponding ScoringFunctionInterpolation. + */ + @Generated + public static ScoringFunctionInterpolation fromString(String name) { + return fromString(name, ScoringFunctionInterpolation.class); + } + + /** + * Gets known ScoringFunctionInterpolation values. + * + * @return known ScoringFunctionInterpolation values. + */ + @Generated + public static Collection values() { + return values(ScoringFunctionInterpolation.class); + } +} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/ScoringParameter.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/ScoringParameter.java deleted file mode 100644 index f9e85253709c..000000000000 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/ScoringParameter.java +++ /dev/null @@ -1,123 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.search.documents.models; - -import com.azure.core.models.GeoPoint; -import com.azure.core.util.CoreUtils; -import com.azure.core.util.logging.ClientLogger; -import com.azure.search.documents.implementation.util.Utility; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import java.util.Objects; -import java.util.stream.Collectors; - -/** - * Represents a parameter value to be used in scoring functions (for example, referencePointParameter). - */ -public final class ScoringParameter { - private static final ClientLogger LOGGER = new ClientLogger(ScoringParameter.class); - private final String name; - private final List values; - - private static final String DASH = "-"; - private static final String COMMA = ","; - private static final String SINGLE_QUOTE = "'"; - - /** - * Constructor to take name value pair string of ScoringParameter. Name and values are separated by dash, and - * values are separared by comma. - * - * @param nameValuePair The dash separated name value pairs. - */ - public ScoringParameter(String nameValuePair) { - Objects.requireNonNull(nameValuePair); - if (!nameValuePair.contains(DASH)) { - throw LOGGER.logExceptionAsError(new IllegalArgumentException( - String.format("The name and value string: %s is invalid.", nameValuePair))); - } - this.name = nameValuePair.split(DASH)[0]; - this.values = Arrays.asList(nameValuePair.split(DASH)[1].split(COMMA)); - } - - /** - * Initializes a new instance of the ScoringParameter class with the given name and string values. - * - * @param name Name of the scoring parameter. - * @param values Values of the scoring parameter. - * @throws NullPointerException if {@code name} or {@code values} is null. - */ - public ScoringParameter(String name, List values) { - Objects.requireNonNull(name); - Objects.requireNonNull(values); - this.name = name; - // Deep clone the values. - this.values = new ArrayList<>(values); - } - - /** - * Initializes a new instance of the ScoringParameter class with the given name and GeographyPoint value. - * - * @param name Name of the scoring parameter. - * @param value Value of the scoring parameter. - * @throws NullPointerException If {@code value} is null. - */ - public ScoringParameter(String name, GeoPoint value) { - this(name, toLonLatStrings(value)); - } - - private static List toLonLatStrings(GeoPoint point) { - Objects.requireNonNull(point); - return Arrays.asList(Utility.formatCoordinate(point.getCoordinates().getLongitude()), - Utility.formatCoordinate(point.getCoordinates().getLatitude())); - } - - /** - * Gets the name of the scoring parameter. - * - * @return The name of scoring parameter. - */ - public String getName() { - return name; - } - - /** - * Gets the values of the scoring parameter. - * - * @return The values of scoring parameter. - */ - public List getValues() { - return new ArrayList<>(values); - } - - /** - * Covert {@link ScoringParameter} to string. - * - * @return Service accepted string format. - * @throws IllegalArgumentException if all values in the list are null or empty. - */ - @Override - public String toString() { - String flattenValue = values.stream() - .filter(value -> !CoreUtils.isNullOrEmpty(value)) - .map(ScoringParameter::escapeValue) - .collect(Collectors.joining(COMMA)); - if (CoreUtils.isNullOrEmpty(flattenValue)) { - throw LOGGER.logExceptionAsError( - new IllegalArgumentException("There must be at least one valid value for scoring parameter values.")); - } - return name + DASH + flattenValue; - } - - private static String escapeValue(String value) { - if (value.contains("'")) { - value = value.replace("'", "''"); - } - if (value.contains(COMMA)) { - value = SINGLE_QUOTE + value + SINGLE_QUOTE; - } - return value; - } -} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/ScoringProfile.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/ScoringProfile.java similarity index 78% rename from sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/ScoringProfile.java rename to sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/ScoringProfile.java index 356c55d47dde..b5b65af38431 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/ScoringProfile.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/ScoringProfile.java @@ -1,17 +1,16 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. -package com.azure.search.documents.indexes.models; +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.search.documents.models; import com.azure.core.annotation.Fluent; +import com.azure.core.annotation.Generated; import com.azure.json.JsonReader; import com.azure.json.JsonSerializable; import com.azure.json.JsonToken; import com.azure.json.JsonWriter; import java.io.IOException; -import java.util.Arrays; import java.util.List; /** @@ -19,61 +18,68 @@ */ @Fluent public final class ScoringProfile implements JsonSerializable { - /* * The name of the scoring profile. */ + @Generated private final String name; /* * Parameters that boost scoring based on text matches in certain index fields. */ + @Generated private TextWeights textWeights; /* * The collection of functions that influence the scoring of documents. */ + @Generated private List functions; /* - * A value indicating how the results of individual scoring functions should be combined. Defaults to "Sum". Ignored - * if there are no scoring functions. + * A value indicating how the results of individual scoring functions should be + * combined. Defaults to "Sum". Ignored if there are no scoring functions. */ + @Generated private ScoringFunctionAggregation functionAggregation; /** * Creates an instance of ScoringProfile class. - * + * * @param name the name value to set. */ + @Generated public ScoringProfile(String name) { this.name = name; } /** * Get the name property: The name of the scoring profile. - * + * * @return the name value. */ + @Generated public String getName() { return this.name; } /** * Get the textWeights property: Parameters that boost scoring based on text matches in certain index fields. - * + * * @return the textWeights value. */ + @Generated public TextWeights getTextWeights() { return this.textWeights; } /** * Set the textWeights property: Parameters that boost scoring based on text matches in certain index fields. - * + * * @param textWeights the textWeights value to set. * @return the ScoringProfile object itself. */ + @Generated public ScoringProfile setTextWeights(TextWeights textWeights) { this.textWeights = textWeights; return this; @@ -81,19 +87,21 @@ public ScoringProfile setTextWeights(TextWeights textWeights) { /** * Get the functions property: The collection of functions that influence the scoring of documents. - * + * * @return the functions value. */ + @Generated public List getFunctions() { return this.functions; } /** * Set the functions property: The collection of functions that influence the scoring of documents. - * + * * @param functions the functions value to set. * @return the ScoringProfile object itself. */ + @Generated public ScoringProfile setFunctions(List functions) { this.functions = functions; return this; @@ -101,21 +109,25 @@ public ScoringProfile setFunctions(List functions) { /** * Get the functionAggregation property: A value indicating how the results of individual scoring functions should - * be combined. Defaults to "Sum". Ignored if there are no scoring functions. - * + * be + * combined. Defaults to "Sum". Ignored if there are no scoring functions. + * * @return the functionAggregation value. */ + @Generated public ScoringFunctionAggregation getFunctionAggregation() { return this.functionAggregation; } /** * Set the functionAggregation property: A value indicating how the results of individual scoring functions should - * be combined. Defaults to "Sum". Ignored if there are no scoring functions. - * + * be + * combined. Defaults to "Sum". Ignored if there are no scoring functions. + * * @param functionAggregation the functionAggregation value to set. * @return the ScoringProfile object itself. */ + @Generated public ScoringProfile setFunctionAggregation(ScoringFunctionAggregation functionAggregation) { this.functionAggregation = functionAggregation; return this; @@ -124,6 +136,7 @@ public ScoringProfile setFunctionAggregation(ScoringFunctionAggregation function /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); @@ -137,16 +150,16 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of ScoringProfile from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of ScoringProfile if the JsonReader was pointing to an instance of it, or null if it was * pointing to JSON null. * @throws IllegalStateException If the deserialized JSON object was missing any required properties. * @throws IOException If an error occurs while reading the ScoringProfile. */ + @Generated public static ScoringProfile fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { - boolean nameFound = false; String name = null; TextWeights textWeights = null; List functions = null; @@ -154,9 +167,9 @@ public static ScoringProfile fromJson(JsonReader jsonReader) throws IOException while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); + if ("name".equals(fieldName)) { name = reader.getString(); - nameFound = true; } else if ("text".equals(fieldName)) { textWeights = TextWeights.fromJson(reader); } else if ("functions".equals(fieldName)) { @@ -167,25 +180,12 @@ public static ScoringProfile fromJson(JsonReader jsonReader) throws IOException reader.skipChildren(); } } - if (nameFound) { - ScoringProfile deserializedScoringProfile = new ScoringProfile(name); - deserializedScoringProfile.textWeights = textWeights; - deserializedScoringProfile.functions = functions; - deserializedScoringProfile.functionAggregation = functionAggregation; - return deserializedScoringProfile; - } - throw new IllegalStateException("Missing required property: name"); - }); - } + ScoringProfile deserializedScoringProfile = new ScoringProfile(name); + deserializedScoringProfile.textWeights = textWeights; + deserializedScoringProfile.functions = functions; + deserializedScoringProfile.functionAggregation = functionAggregation; - /** - * Set the functions property: The collection of functions that influence the scoring of documents. - * - * @param functions the functions value to set. - * @return the ScoringProfile object itself. - */ - public ScoringProfile setFunctions(ScoringFunction... functions) { - this.functions = (functions == null) ? null : Arrays.asList(functions); - return this; + return deserializedScoringProfile; + }); } } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/ScoringStatistics.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/ScoringStatistics.java index de1aac30cf37..9236c96522b8 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/ScoringStatistics.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/ScoringStatistics.java @@ -1,60 +1,61 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.search.documents.models; +import com.azure.core.annotation.Generated; +import com.azure.core.util.ExpandableStringEnum; +import java.util.Collection; + /** - * 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. + * 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. */ -public enum ScoringStatistics { +public final class ScoringStatistics extends ExpandableStringEnum { /** * The scoring statistics will be calculated locally for lower latency. */ - LOCAL("local"), + @Generated + public static final ScoringStatistics LOCAL = fromString("local"); /** * The scoring statistics will be calculated globally for more consistent scoring. */ - GLOBAL("global"); + @Generated + public static final ScoringStatistics GLOBAL = fromString("global"); /** - * The actual serialized value for a ScoringStatistics instance. + * Creates a new instance of ScoringStatistics value. + * + * @deprecated Use the {@link #fromString(String)} factory method. */ - private final String value; - - ScoringStatistics(String value) { - this.value = value; + @Generated + @Deprecated + public ScoringStatistics() { } /** - * Parses a serialized value to a ScoringStatistics instance. + * Creates or finds a ScoringStatistics from its string representation. * - * @param value the serialized value to parse. - * @return the parsed ScoringStatistics object, or null if unable to parse. + * @param name a name to look for. + * @return the corresponding ScoringStatistics. */ - public static ScoringStatistics fromString(String value) { - if (value == null) { - return null; - } - ScoringStatistics[] items = ScoringStatistics.values(); - for (ScoringStatistics item : items) { - if (item.toString().equalsIgnoreCase(value)) { - return item; - } - } - return null; + @Generated + public static ScoringStatistics fromString(String name) { + return fromString(name, ScoringStatistics.class); } /** - * {@inheritDoc} + * Gets known ScoringStatistics values. + * + * @return known ScoringStatistics values. */ - @Override - public String toString() { - return this.value; + @Generated + public static Collection values() { + return values(ScoringStatistics.class); } } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/SearchAlias.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SearchAlias.java similarity index 76% rename from sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/SearchAlias.java rename to sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SearchAlias.java index 3f73dbc474e8..fad75d2e38e3 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/SearchAlias.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SearchAlias.java @@ -1,39 +1,41 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) TypeSpec Code Generator. -package com.azure.search.documents.indexes.models; +package com.azure.search.documents.models; import com.azure.core.annotation.Fluent; +import com.azure.core.annotation.Generated; import com.azure.json.JsonReader; import com.azure.json.JsonSerializable; import com.azure.json.JsonToken; import com.azure.json.JsonWriter; import java.io.IOException; -import java.util.ArrayList; import java.util.List; /** - * 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. + * 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. */ @Fluent public final class SearchAlias implements JsonSerializable { /* * The name of the alias. */ + @Generated private final String name; /* * The name of the index this alias maps to. Only one index name may be specified. */ + @Generated private final List indexes; /* * The ETag of the alias. */ + @Generated private String eTag; /** @@ -42,6 +44,7 @@ public final class SearchAlias implements JsonSerializable { * @param name the name value to set. * @param indexes the indexes value to set. */ + @Generated public SearchAlias(String name, List indexes) { this.name = name; this.indexes = indexes; @@ -52,6 +55,7 @@ public SearchAlias(String name, List indexes) { * * @return the name value. */ + @Generated public String getName() { return this.name; } @@ -61,6 +65,7 @@ public String getName() { * * @return the indexes value. */ + @Generated public List getIndexes() { return this.indexes; } @@ -70,6 +75,7 @@ public List getIndexes() { * * @return the eTag value. */ + @Generated public String getETag() { return this.eTag; } @@ -80,6 +86,7 @@ public String getETag() { * @param eTag the eTag value to set. * @return the SearchAlias object itself. */ + @Generated public SearchAlias setETag(String eTag) { this.eTag = eTag; return this; @@ -88,6 +95,7 @@ public SearchAlias setETag(String eTag) { /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); @@ -106,11 +114,10 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { * @throws IllegalStateException If the deserialized JSON object was missing any required properties. * @throws IOException If an error occurs while reading the SearchAlias. */ + @Generated public static SearchAlias fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { - boolean nameFound = false; String name = null; - boolean indexesFound = false; List indexes = null; String eTag = null; while (reader.nextToken() != JsonToken.END_OBJECT) { @@ -119,32 +126,18 @@ public static SearchAlias fromJson(JsonReader jsonReader) throws IOException { if ("name".equals(fieldName)) { name = reader.getString(); - nameFound = true; } else if ("indexes".equals(fieldName)) { indexes = reader.readArray(reader1 -> reader1.getString()); - indexesFound = true; } else if ("@odata.etag".equals(fieldName)) { eTag = reader.getString(); } else { reader.skipChildren(); } } - if (nameFound && indexesFound) { - SearchAlias deserializedSearchAlias = new SearchAlias(name, indexes); - deserializedSearchAlias.eTag = eTag; + SearchAlias deserializedSearchAlias = new SearchAlias(name, indexes); + deserializedSearchAlias.eTag = eTag; - return deserializedSearchAlias; - } - List missingProperties = new ArrayList<>(); - if (!nameFound) { - missingProperties.add("name"); - } - if (!indexesFound) { - missingProperties.add("indexes"); - } - - throw new IllegalStateException( - "Missing required property/properties: " + String.join(", ", missingProperties)); + return deserializedSearchAlias; }); } } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SearchAudience.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SearchAudience.java deleted file mode 100644 index 0396f01968a8..000000000000 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SearchAudience.java +++ /dev/null @@ -1,59 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.search.documents.models; - -import com.azure.core.util.ExpandableStringEnum; - -import java.util.Collection; - -/** - * Cloud audiences available for Search. - */ -public final class SearchAudience extends ExpandableStringEnum { - /** - * The {@link SearchAudience} for Azure China cloud. - */ - public static final SearchAudience AZURE_CHINA = fromString("https://search.azure.cn"); - - /** - * The {@link SearchAudience} for Azure US Government cloud. - */ - public static final SearchAudience AZURE_GOVERNMENT = fromString("https://search.azure.us"); - - /** - * The {@link SearchAudience} for the Azure Public cloud. - */ - public static final SearchAudience AZURE_PUBLIC_CLOUD = fromString("https://search.azure.com"); - - /** - * Creates a new instance of {@link SearchAudience} without a {@link #toString()} value. - *

- * This constructor shouldn't be called as it will produce a {@link SearchAudience} which doesn't have a String enum - * value. - * - * @deprecated Use one of the constants or the {@link #fromString(String)} factory method. - */ - @Deprecated - public SearchAudience() { - } - - /** - * Creates or finds a SearchAudience from its string representation. - * - * @param name a name to look for. - * @return the corresponding SearchAudience. - */ - public static SearchAudience fromString(String name) { - return fromString(name, SearchAudience.class); - } - - /** - * Gets the known SearchAudience values. - * - * @return known SearchAudience values. - */ - public static Collection values() { - return values(SearchAudience.class); - } -} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/implementation/models/SearchDocumentsResult.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SearchDocumentsResult.java similarity index 65% rename from sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/implementation/models/SearchDocumentsResult.java rename to sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SearchDocumentsResult.java index f40023daab8c..0e0004af5081 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/implementation/models/SearchDocumentsResult.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SearchDocumentsResult.java @@ -1,22 +1,15 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) TypeSpec Code Generator. -package com.azure.search.documents.implementation.models; +package com.azure.search.documents.models; +import com.azure.core.annotation.Generated; import com.azure.core.annotation.Immutable; import com.azure.json.JsonReader; import com.azure.json.JsonSerializable; import com.azure.json.JsonToken; import com.azure.json.JsonWriter; -import com.azure.search.documents.models.DebugInfo; -import com.azure.search.documents.models.FacetResult; -import com.azure.search.documents.models.QueryAnswerResult; -import com.azure.search.documents.models.SemanticErrorReason; -import com.azure.search.documents.models.SemanticQueryRewritesResultType; -import com.azure.search.documents.models.SemanticSearchResultsType; import java.io.IOException; import java.util.List; import java.util.Map; @@ -27,127 +20,158 @@ @Immutable public final class SearchDocumentsResult implements JsonSerializable { /* - * 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. + * 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. */ + @Generated private Long count; /* - * A value indicating the percentage of the index that was included in the query, or null if minimumCoverage was not - * specified in the request. + * A value indicating the percentage of the index that was included in the query, + * or null if minimumCoverage was not specified in the request. */ + @Generated private Double coverage; /* - * 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. + * 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. */ + @Generated private Map> facets; /* - * The answers query results for the search operation; null if the answers query parameter was not specified or set - * to 'none'. + * The answers query results for the search operation; null if the answers query + * parameter was not specified or set to 'none'. */ + @Generated private List answers; /* - * 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. + * Debug information that applies to the search results as a whole. + */ + @Generated + private DebugInfo debugInfo; + + /* + * 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 */ + @Generated private SearchRequest nextPageParameters; /* * The sequence of results returned by the query. */ + @Generated private final List results; /* - * 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. + * 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. */ + @Generated private String nextLink; /* * Reason that a partial response was returned for a semantic ranking request. */ + @Generated private SemanticErrorReason semanticPartialResponseReason; /* * Type of partial response that was returned for a semantic ranking request. */ + @Generated private SemanticSearchResultsType semanticPartialResponseType; /* * Type of query rewrite that was used to retrieve documents. */ + @Generated private SemanticQueryRewritesResultType semanticQueryRewritesResultType; - /* - * Debug information that applies to the search results as a whole. - */ - private DebugInfo debugInfo; - /** * Creates an instance of SearchDocumentsResult class. * * @param results the results value to set. */ - public SearchDocumentsResult(List results) { + @Generated + private SearchDocumentsResult(List results) { this.results = results; } /** - * Get the count property: 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. + * Get the count property: 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. * * @return the count value. */ + @Generated public Long getCount() { return this.count; } /** - * Get the coverage property: A value indicating the percentage of the index that was included in the query, or null - * if minimumCoverage was not specified in the request. + * Get the coverage property: A value indicating the percentage of the index that was included in the query, + * or null if minimumCoverage was not specified in the request. * * @return the coverage value. */ + @Generated public Double getCoverage() { return this.coverage; } /** - * Get the facets property: 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. + * Get the facets property: 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. * * @return the facets value. */ + @Generated public Map> getFacets() { return this.facets; } /** - * Get the answers property: The answers query results for the search operation; null if the answers query parameter - * was not specified or set to 'none'. + * Get the answers property: The answers query results for the search operation; null if the answers query + * parameter was not specified or set to 'none'. * * @return the answers value. */ + @Generated public List getAnswers() { return this.answers; } + /** + * Get the debugInfo property: Debug information that applies to the search results as a whole. + * + * @return the debugInfo value. + */ + @Generated + public DebugInfo getDebugInfo() { + return this.debugInfo; + } + /** * Get the nextPageParameters property: 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. + * requested results in a single response. You can use this JSON along with. * * @return the nextPageParameters value. */ + @Generated public SearchRequest getNextPageParameters() { return this.nextPageParameters; } @@ -157,17 +181,20 @@ public SearchRequest getNextPageParameters() { * * @return the results value. */ + @Generated public List getResults() { return this.results; } /** - * Get the nextLink property: 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. + * Get the nextLink property: 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. * * @return the nextLink value. */ + @Generated public String getNextLink() { return this.nextLink; } @@ -178,6 +205,7 @@ public String getNextLink() { * * @return the semanticPartialResponseReason value. */ + @Generated public SemanticErrorReason getSemanticPartialResponseReason() { return this.semanticPartialResponseReason; } @@ -188,6 +216,7 @@ public SemanticErrorReason getSemanticPartialResponseReason() { * * @return the semanticPartialResponseType value. */ + @Generated public SemanticSearchResultsType getSemanticPartialResponseType() { return this.semanticPartialResponseType; } @@ -197,25 +226,30 @@ public SemanticSearchResultsType getSemanticPartialResponseType() { * * @return the semanticQueryRewritesResultType value. */ + @Generated public SemanticQueryRewritesResultType getSemanticQueryRewritesResultType() { return this.semanticQueryRewritesResultType; } - /** - * Get the debugInfo property: Debug information that applies to the search results as a whole. - * - * @return the debugInfo value. - */ - public DebugInfo getDebugInfo() { - return this.debugInfo; - } - /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); + jsonWriter.writeArrayField("value", this.results, (writer, element) -> writer.writeJson(element)); + jsonWriter.writeNumberField("@odata.count", this.count); + jsonWriter.writeNumberField("@search.coverage", this.coverage); + jsonWriter.writeMapField("@search.facets", this.facets, + (writer, element) -> writer.writeArray(element, (writer1, element1) -> writer1.writeJson(element1))); + jsonWriter.writeArrayField("@search.answers", this.answers, (writer, element) -> writer.writeJson(element)); + jsonWriter.writeJsonField("@search.nextPageParameters", this.nextPageParameters); + jsonWriter.writeStringField("@odata.nextLink", this.nextLink); + jsonWriter.writeStringField("@search.semanticPartialResponseReason", + this.semanticPartialResponseReason == null ? null : this.semanticPartialResponseReason.toString()); + jsonWriter.writeStringField("@search.semanticPartialResponseType", + this.semanticPartialResponseType == null ? null : this.semanticPartialResponseType.toString()); return jsonWriter.writeEndObject(); } @@ -228,27 +262,26 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { * @throws IllegalStateException If the deserialized JSON object was missing any required properties. * @throws IOException If an error occurs while reading the SearchDocumentsResult. */ + @Generated public static SearchDocumentsResult fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { - boolean resultsFound = false; List results = null; Long count = null; Double coverage = null; Map> facets = null; List answers = null; + DebugInfo debugInfo = null; SearchRequest nextPageParameters = null; String nextLink = null; SemanticErrorReason semanticPartialResponseReason = null; SemanticSearchResultsType semanticPartialResponseType = null; SemanticQueryRewritesResultType semanticQueryRewritesResultType = null; - DebugInfo debugInfo = null; while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); if ("value".equals(fieldName)) { results = reader.readArray(reader1 -> SearchResult.fromJson(reader1)); - resultsFound = true; } else if ("@odata.count".equals(fieldName)) { count = reader.getNullable(JsonReader::getLong); } else if ("@search.coverage".equals(fieldName)) { @@ -257,6 +290,8 @@ public static SearchDocumentsResult fromJson(JsonReader jsonReader) throws IOExc facets = reader.readMap(reader1 -> reader1.readArray(reader2 -> FacetResult.fromJson(reader2))); } else if ("@search.answers".equals(fieldName)) { answers = reader.readArray(reader1 -> QueryAnswerResult.fromJson(reader1)); + } else if ("@search.debug".equals(fieldName)) { + debugInfo = DebugInfo.fromJson(reader); } else if ("@search.nextPageParameters".equals(fieldName)) { nextPageParameters = SearchRequest.fromJson(reader); } else if ("@odata.nextLink".equals(fieldName)) { @@ -267,28 +302,23 @@ public static SearchDocumentsResult fromJson(JsonReader jsonReader) throws IOExc semanticPartialResponseType = SemanticSearchResultsType.fromString(reader.getString()); } else if ("@search.semanticQueryRewritesResultType".equals(fieldName)) { semanticQueryRewritesResultType = SemanticQueryRewritesResultType.fromString(reader.getString()); - } else if ("@search.debug".equals(fieldName)) { - debugInfo = DebugInfo.fromJson(reader); } else { reader.skipChildren(); } } - if (resultsFound) { - SearchDocumentsResult deserializedSearchDocumentsResult = new SearchDocumentsResult(results); - deserializedSearchDocumentsResult.count = count; - deserializedSearchDocumentsResult.coverage = coverage; - deserializedSearchDocumentsResult.facets = facets; - deserializedSearchDocumentsResult.answers = answers; - deserializedSearchDocumentsResult.nextPageParameters = nextPageParameters; - deserializedSearchDocumentsResult.nextLink = nextLink; - deserializedSearchDocumentsResult.semanticPartialResponseReason = semanticPartialResponseReason; - deserializedSearchDocumentsResult.semanticPartialResponseType = semanticPartialResponseType; - deserializedSearchDocumentsResult.semanticQueryRewritesResultType = semanticQueryRewritesResultType; - deserializedSearchDocumentsResult.debugInfo = debugInfo; + SearchDocumentsResult deserializedSearchDocumentsResult = new SearchDocumentsResult(results); + deserializedSearchDocumentsResult.count = count; + deserializedSearchDocumentsResult.coverage = coverage; + deserializedSearchDocumentsResult.facets = facets; + deserializedSearchDocumentsResult.answers = answers; + deserializedSearchDocumentsResult.debugInfo = debugInfo; + deserializedSearchDocumentsResult.nextPageParameters = nextPageParameters; + deserializedSearchDocumentsResult.nextLink = nextLink; + deserializedSearchDocumentsResult.semanticPartialResponseReason = semanticPartialResponseReason; + deserializedSearchDocumentsResult.semanticPartialResponseType = semanticPartialResponseType; + deserializedSearchDocumentsResult.semanticQueryRewritesResultType = semanticQueryRewritesResultType; - return deserializedSearchDocumentsResult; - } - throw new IllegalStateException("Missing required property: value"); + return deserializedSearchDocumentsResult; }); } } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SearchField.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SearchField.java new file mode 100644 index 000000000000..caf9b17717a4 --- /dev/null +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SearchField.java @@ -0,0 +1,866 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.search.documents.models; + +import com.azure.core.annotation.Fluent; +import com.azure.core.annotation.Generated; +import com.azure.json.JsonReader; +import com.azure.json.JsonSerializable; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import java.io.IOException; +import java.util.List; + +/** + * Represents a field in an index definition, which describes the name, data type, + * and search behavior of a field. + */ +@Fluent +public final class SearchField implements JsonSerializable { + /* + * The name of the field, which must be unique within the fields collection of the + * index or parent field. + */ + @Generated + private final String name; + + /* + * The data type of the field. + */ + @Generated + private final SearchFieldDataType type; + + /* + * 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. + */ + @Generated + private Boolean key; + + /* + * 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. + */ + @Generated + private Boolean retrievable; + + /* + * 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. + */ + @Generated + private Boolean stored; + + /* + * 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. + */ + @Generated + private Boolean searchable; + + /* + * 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. + */ + @Generated + private Boolean filterable; + + /* + * 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. + */ + @Generated + private Boolean sortable; + + /* + * 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. + */ + @Generated + private Boolean facetable; + + /* + * 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. + */ + @Generated + private LexicalAnalyzerName 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. + */ + @Generated + private LexicalAnalyzerName searchAnalyzer; + + /* + * 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. + */ + @Generated + private LexicalAnalyzerName indexAnalyzer; + + /* + * 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. + */ + @Generated + private LexicalNormalizerName normalizer; + + /* + * The dimensionality of the vector field. + */ + @Generated + private Integer vectorSearchDimensions; + + /* + * The name of the vector search profile that specifies the algorithm and + * vectorizer to use when searching the vector field. + */ + @Generated + private String vectorSearchProfileName; + + /* + * The encoding format to interpret the field contents. + */ + @Generated + private VectorEncodingFormat vectorEncodingFormat; + + /* + * 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. + */ + @Generated + private List synonymMaps; + + /* + * 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. + */ + @Generated + private List fields; + + /** + * Creates an instance of SearchField class. + * + * @param name the name value to set. + * @param type the type value to set. + */ + @Generated + public SearchField(String name, SearchFieldDataType type) { + this.name = name; + this.type = type; + } + + /** + * Get the name property: The name of the field, which must be unique within the fields collection of the + * index or parent field. + * + * @return the name value. + */ + @Generated + public String getName() { + return this.name; + } + + /** + * Get the type property: The data type of the field. + * + * @return the type value. + */ + @Generated + public SearchFieldDataType getType() { + return this.type; + } + + /** + * Get the key property: 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. + * + * @return the key value. + */ + @Generated + public Boolean isKey() { + return this.key; + } + + /** + * Set the key property: 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. + * + * @param key the key value to set. + * @return the SearchField object itself. + */ + @Generated + public SearchField setKey(Boolean key) { + this.key = key; + return this; + } + + /** + * Get the retrievable property: 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. + * + * @return the retrievable value. + */ + @Generated + public Boolean isRetrievable() { + return this.retrievable; + } + + /** + * Set the retrievable property: 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. + * + * @param retrievable the retrievable value to set. + * @return the SearchField object itself. + */ + @Generated + public SearchField setRetrievable(Boolean retrievable) { + this.retrievable = retrievable; + return this; + } + + /** + * Get the stored property: 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. + * + * @return the stored value. + */ + @Generated + public Boolean isStored() { + return this.stored; + } + + /** + * Set the stored property: 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. + * + * @param stored the stored value to set. + * @return the SearchField object itself. + */ + @Generated + public SearchField setStored(Boolean stored) { + this.stored = stored; + return this; + } + + /** + * Get the searchable property: 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. + * + * @return the searchable value. + */ + @Generated + public Boolean isSearchable() { + return this.searchable; + } + + /** + * Set the searchable property: 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. + * + * @param searchable the searchable value to set. + * @return the SearchField object itself. + */ + @Generated + public SearchField setSearchable(Boolean searchable) { + this.searchable = searchable; + return this; + } + + /** + * Get the filterable property: 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. + * + * @return the filterable value. + */ + @Generated + public Boolean isFilterable() { + return this.filterable; + } + + /** + * Set the filterable property: 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. + * + * @param filterable the filterable value to set. + * @return the SearchField object itself. + */ + @Generated + public SearchField setFilterable(Boolean filterable) { + this.filterable = filterable; + return this; + } + + /** + * Get the sortable property: 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. + * + * @return the sortable value. + */ + @Generated + public Boolean isSortable() { + return this.sortable; + } + + /** + * Set the sortable property: 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. + * + * @param sortable the sortable value to set. + * @return the SearchField object itself. + */ + @Generated + public SearchField setSortable(Boolean sortable) { + this.sortable = sortable; + return this; + } + + /** + * Get the facetable property: 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. + * + * @return the facetable value. + */ + @Generated + public Boolean isFacetable() { + return this.facetable; + } + + /** + * Set the facetable property: 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. + * + * @param facetable the facetable value to set. + * @return the SearchField object itself. + */ + @Generated + public SearchField setFacetable(Boolean facetable) { + this.facetable = facetable; + return this; + } + + /** + * Get the analyzer property: 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. + * + * @return the analyzer value. + */ + @Generated + public LexicalAnalyzerName getAnalyzer() { + return this.analyzer; + } + + /** + * Set the analyzer property: 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. + * + * @param analyzer the analyzer value to set. + * @return the SearchField object itself. + */ + @Generated + public SearchField setAnalyzer(LexicalAnalyzerName analyzer) { + this.analyzer = analyzer; + return this; + } + + /** + * Get the searchAnalyzer property: 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. + * + * @return the searchAnalyzer value. + */ + @Generated + public LexicalAnalyzerName getSearchAnalyzer() { + return this.searchAnalyzer; + } + + /** + * Set the searchAnalyzer property: 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. + * + * @param searchAnalyzer the searchAnalyzer value to set. + * @return the SearchField object itself. + */ + @Generated + public SearchField setSearchAnalyzer(LexicalAnalyzerName searchAnalyzer) { + this.searchAnalyzer = searchAnalyzer; + return this; + } + + /** + * Get the indexAnalyzer property: 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. + * + * @return the indexAnalyzer value. + */ + @Generated + public LexicalAnalyzerName getIndexAnalyzer() { + return this.indexAnalyzer; + } + + /** + * Set the indexAnalyzer property: 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. + * + * @param indexAnalyzer the indexAnalyzer value to set. + * @return the SearchField object itself. + */ + @Generated + public SearchField setIndexAnalyzer(LexicalAnalyzerName indexAnalyzer) { + this.indexAnalyzer = indexAnalyzer; + return this; + } + + /** + * Get the normalizer property: 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. + * + * @return the normalizer value. + */ + @Generated + public LexicalNormalizerName getNormalizer() { + return this.normalizer; + } + + /** + * Set the normalizer property: 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. + * + * @param normalizer the normalizer value to set. + * @return the SearchField object itself. + */ + @Generated + public SearchField setNormalizer(LexicalNormalizerName normalizer) { + this.normalizer = normalizer; + return this; + } + + /** + * Get the vectorSearchDimensions property: The dimensionality of the vector field. + * + * @return the vectorSearchDimensions value. + */ + @Generated + public Integer getVectorSearchDimensions() { + return this.vectorSearchDimensions; + } + + /** + * Set the vectorSearchDimensions property: The dimensionality of the vector field. + * + * @param vectorSearchDimensions the vectorSearchDimensions value to set. + * @return the SearchField object itself. + */ + @Generated + public SearchField setVectorSearchDimensions(Integer vectorSearchDimensions) { + this.vectorSearchDimensions = vectorSearchDimensions; + return this; + } + + /** + * Get the vectorSearchProfileName property: The name of the vector search profile that specifies the algorithm and + * vectorizer to use when searching the vector field. + * + * @return the vectorSearchProfileName value. + */ + @Generated + public String getVectorSearchProfileName() { + return this.vectorSearchProfileName; + } + + /** + * Set the vectorSearchProfileName property: The name of the vector search profile that specifies the algorithm and + * vectorizer to use when searching the vector field. + * + * @param vectorSearchProfileName the vectorSearchProfileName value to set. + * @return the SearchField object itself. + */ + @Generated + public SearchField setVectorSearchProfileName(String vectorSearchProfileName) { + this.vectorSearchProfileName = vectorSearchProfileName; + return this; + } + + /** + * Get the vectorEncodingFormat property: The encoding format to interpret the field contents. + * + * @return the vectorEncodingFormat value. + */ + @Generated + public VectorEncodingFormat getVectorEncodingFormat() { + return this.vectorEncodingFormat; + } + + /** + * Set the vectorEncodingFormat property: The encoding format to interpret the field contents. + * + * @param vectorEncodingFormat the vectorEncodingFormat value to set. + * @return the SearchField object itself. + */ + @Generated + public SearchField setVectorEncodingFormat(VectorEncodingFormat vectorEncodingFormat) { + this.vectorEncodingFormat = vectorEncodingFormat; + return this; + } + + /** + * Get the synonymMaps property: 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. + * + * @return the synonymMaps value. + */ + @Generated + public List getSynonymMaps() { + return this.synonymMaps; + } + + /** + * Set the synonymMaps property: 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. + * + * @param synonymMaps the synonymMaps value to set. + * @return the SearchField object itself. + */ + @Generated + public SearchField setSynonymMaps(List synonymMaps) { + this.synonymMaps = synonymMaps; + return this; + } + + /** + * Get the fields property: 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. + * + * @return the fields value. + */ + @Generated + public List getFields() { + return this.fields; + } + + /** + * Set the fields property: 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. + * + * @param fields the fields value to set. + * @return the SearchField object itself. + */ + @Generated + public SearchField setFields(List fields) { + this.fields = fields; + return this; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("name", this.name); + jsonWriter.writeStringField("type", this.type == null ? null : this.type.toString()); + jsonWriter.writeBooleanField("key", this.key); + jsonWriter.writeBooleanField("retrievable", this.retrievable); + jsonWriter.writeBooleanField("stored", this.stored); + jsonWriter.writeBooleanField("searchable", this.searchable); + jsonWriter.writeBooleanField("filterable", this.filterable); + jsonWriter.writeBooleanField("sortable", this.sortable); + jsonWriter.writeBooleanField("facetable", this.facetable); + jsonWriter.writeStringField("analyzer", this.analyzer == null ? null : this.analyzer.toString()); + jsonWriter.writeStringField("searchAnalyzer", + this.searchAnalyzer == null ? null : this.searchAnalyzer.toString()); + jsonWriter.writeStringField("indexAnalyzer", this.indexAnalyzer == null ? null : this.indexAnalyzer.toString()); + jsonWriter.writeStringField("normalizer", this.normalizer == null ? null : this.normalizer.toString()); + jsonWriter.writeNumberField("dimensions", this.vectorSearchDimensions); + jsonWriter.writeStringField("vectorSearchProfile", this.vectorSearchProfileName); + jsonWriter.writeStringField("vectorEncoding", + this.vectorEncodingFormat == null ? null : this.vectorEncodingFormat.toString()); + jsonWriter.writeArrayField("synonymMaps", this.synonymMaps, (writer, element) -> writer.writeString(element)); + jsonWriter.writeArrayField("fields", this.fields, (writer, element) -> writer.writeJson(element)); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of SearchField from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of SearchField if the JsonReader was pointing to an instance of it, or null if it was + * pointing to JSON null. + * @throws IllegalStateException If the deserialized JSON object was missing any required properties. + * @throws IOException If an error occurs while reading the SearchField. + */ + @Generated + public static SearchField fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + String name = null; + SearchFieldDataType type = null; + Boolean key = null; + Boolean retrievable = null; + Boolean stored = null; + Boolean searchable = null; + Boolean filterable = null; + Boolean sortable = null; + Boolean facetable = null; + LexicalAnalyzerName analyzer = null; + LexicalAnalyzerName searchAnalyzer = null; + LexicalAnalyzerName indexAnalyzer = null; + LexicalNormalizerName normalizer = null; + Integer vectorSearchDimensions = null; + String vectorSearchProfileName = null; + VectorEncodingFormat vectorEncodingFormat = null; + List synonymMaps = null; + List fields = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("name".equals(fieldName)) { + name = reader.getString(); + } else if ("type".equals(fieldName)) { + type = SearchFieldDataType.fromString(reader.getString()); + } else if ("key".equals(fieldName)) { + key = reader.getNullable(JsonReader::getBoolean); + } else if ("retrievable".equals(fieldName)) { + retrievable = reader.getNullable(JsonReader::getBoolean); + } else if ("stored".equals(fieldName)) { + stored = reader.getNullable(JsonReader::getBoolean); + } else if ("searchable".equals(fieldName)) { + searchable = reader.getNullable(JsonReader::getBoolean); + } else if ("filterable".equals(fieldName)) { + filterable = reader.getNullable(JsonReader::getBoolean); + } else if ("sortable".equals(fieldName)) { + sortable = reader.getNullable(JsonReader::getBoolean); + } else if ("facetable".equals(fieldName)) { + facetable = reader.getNullable(JsonReader::getBoolean); + } else if ("analyzer".equals(fieldName)) { + analyzer = LexicalAnalyzerName.fromString(reader.getString()); + } else if ("searchAnalyzer".equals(fieldName)) { + searchAnalyzer = LexicalAnalyzerName.fromString(reader.getString()); + } else if ("indexAnalyzer".equals(fieldName)) { + indexAnalyzer = LexicalAnalyzerName.fromString(reader.getString()); + } else if ("normalizer".equals(fieldName)) { + normalizer = LexicalNormalizerName.fromString(reader.getString()); + } else if ("dimensions".equals(fieldName)) { + vectorSearchDimensions = reader.getNullable(JsonReader::getInt); + } else if ("vectorSearchProfile".equals(fieldName)) { + vectorSearchProfileName = reader.getString(); + } else if ("vectorEncoding".equals(fieldName)) { + vectorEncodingFormat = VectorEncodingFormat.fromString(reader.getString()); + } else if ("synonymMaps".equals(fieldName)) { + synonymMaps = reader.readArray(reader1 -> reader1.getString()); + } else if ("fields".equals(fieldName)) { + fields = reader.readArray(reader1 -> SearchField.fromJson(reader1)); + } else { + reader.skipChildren(); + } + } + SearchField deserializedSearchField = new SearchField(name, type); + deserializedSearchField.key = key; + deserializedSearchField.retrievable = retrievable; + deserializedSearchField.stored = stored; + deserializedSearchField.searchable = searchable; + deserializedSearchField.filterable = filterable; + deserializedSearchField.sortable = sortable; + deserializedSearchField.facetable = facetable; + deserializedSearchField.analyzer = analyzer; + deserializedSearchField.searchAnalyzer = searchAnalyzer; + deserializedSearchField.indexAnalyzer = indexAnalyzer; + deserializedSearchField.normalizer = normalizer; + deserializedSearchField.vectorSearchDimensions = vectorSearchDimensions; + deserializedSearchField.vectorSearchProfileName = vectorSearchProfileName; + deserializedSearchField.vectorEncodingFormat = vectorEncodingFormat; + deserializedSearchField.synonymMaps = synonymMaps; + deserializedSearchField.fields = fields; + + return deserializedSearchField; + }); + } +} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/SearchFieldDataType.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SearchFieldDataType.java similarity index 75% rename from sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/SearchFieldDataType.java rename to sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SearchFieldDataType.java index 5932418c2a18..d552ccfd6aea 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/SearchFieldDataType.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SearchFieldDataType.java @@ -1,10 +1,10 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. -package com.azure.search.documents.indexes.models; +// Code generated by Microsoft (R) TypeSpec Code Generator. +package com.azure.search.documents.models; + +import com.azure.core.annotation.Generated; import com.azure.core.util.ExpandableStringEnum; import java.util.Collection; @@ -12,109 +12,120 @@ * Defines the data type of a field in a search index. */ public final class SearchFieldDataType extends ExpandableStringEnum { - /** * Indicates that a field contains a string. */ + @Generated public static final SearchFieldDataType STRING = fromString("Edm.String"); /** * Indicates that a field contains a 32-bit signed integer. */ + @Generated public static final SearchFieldDataType INT32 = fromString("Edm.Int32"); /** * Indicates that a field contains a 64-bit signed integer. */ + @Generated public static final SearchFieldDataType INT64 = fromString("Edm.Int64"); /** * Indicates that a field contains an IEEE double-precision floating point number. */ + @Generated public static final SearchFieldDataType DOUBLE = fromString("Edm.Double"); /** * Indicates that a field contains a Boolean value (true or false). */ + @Generated public static final SearchFieldDataType BOOLEAN = fromString("Edm.Boolean"); /** - * Indicates that a field contains a date/time value, including timezone information. + * Indicates that a field contains a date/time value, including timezone + * information. */ + @Generated public static final SearchFieldDataType DATE_TIME_OFFSET = fromString("Edm.DateTimeOffset"); /** - * Indicates that a field contains a geo-location in terms of longitude and latitude. + * Indicates that a field contains a geo-location in terms of longitude and + * latitude. */ + @Generated public static final SearchFieldDataType GEOGRAPHY_POINT = fromString("Edm.GeographyPoint"); /** - * Indicates that a field contains one or more complex objects that in turn have sub-fields of other types. + * Indicates that a field contains one or more complex objects that in turn have + * sub-fields of other types. */ + @Generated public static final SearchFieldDataType COMPLEX = fromString("Edm.ComplexType"); /** - * Indicates that a field contains a single-precision floating point number. This is only valid when used with - * Collection(Edm.Single). + * Indicates that a field contains a single-precision floating point number. This + * is only valid when used with Collection(Edm.Single). */ + @Generated public static final SearchFieldDataType SINGLE = fromString("Edm.Single"); /** - * Indicates that a field contains a half-precision floating point number. This is only valid when used with - * Collection(Edm.Half). + * Indicates that a field contains a half-precision floating point number. This is + * only valid when used with Collection(Edm.Half). */ + @Generated public static final SearchFieldDataType HALF = fromString("Edm.Half"); /** - * Indicates that a field contains a 16-bit signed integer. This is only valid when used with Collection(Edm.Int16). + * Indicates that a field contains a 16-bit signed integer. This is only valid + * when used with Collection(Edm.Int16). */ + @Generated public static final SearchFieldDataType INT16 = fromString("Edm.Int16"); /** - * Indicates that a field contains a 8-bit signed integer. This is only valid when used with Collection(Edm.SByte). + * Indicates that a field contains a 8-bit signed integer. This is only valid when + * used with Collection(Edm.SByte). */ + @Generated public static final SearchFieldDataType SBYTE = fromString("Edm.SByte"); /** - * Indicates that a field contains a 8-bit unsigned integer. This is only valid when used with Collection(Edm.Byte). + * Indicates that a field contains a 8-bit unsigned integer. This is only valid + * when used with Collection(Edm.Byte). */ + @Generated public static final SearchFieldDataType BYTE = fromString("Edm.Byte"); /** * Creates a new instance of SearchFieldDataType value. - * + * * @deprecated Use the {@link #fromString(String)} factory method. */ + @Generated @Deprecated public SearchFieldDataType() { } /** * Creates or finds a SearchFieldDataType from its string representation. - * + * * @param name a name to look for. * @return the corresponding SearchFieldDataType. */ + @Generated public static SearchFieldDataType fromString(String name) { return fromString(name, SearchFieldDataType.class); } /** * Gets known SearchFieldDataType values. - * + * * @return known SearchFieldDataType values. */ + @Generated public static Collection values() { return values(SearchFieldDataType.class); } - - /** - * Returns a collection of a specific SearchFieldDataType. - * - * @param dataType the corresponding SearchFieldDataType - * @return a Collection of the corresponding SearchFieldDataType - */ - public static SearchFieldDataType collection(SearchFieldDataType dataType) { - return fromString(String.format("Collection(%s)", dataType.toString())); - } } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/SearchIndex.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SearchIndex.java similarity index 68% rename from sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/SearchIndex.java rename to sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SearchIndex.java index c28a6e4029f5..5e35b2876546 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/SearchIndex.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SearchIndex.java @@ -1,166 +1,182 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. -package com.azure.search.documents.indexes.models; +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.search.documents.models; import com.azure.core.annotation.Fluent; +import com.azure.core.annotation.Generated; import com.azure.json.JsonReader; import com.azure.json.JsonSerializable; import com.azure.json.JsonToken; import com.azure.json.JsonWriter; import java.io.IOException; -import java.util.Arrays; import java.util.List; /** - * Represents a search index definition, which describes the fields and search behavior of an index. + * Represents a search index definition, which describes the fields and search + * behavior of an index. */ @Fluent public final class SearchIndex implements JsonSerializable { - /* * The name of the index. */ + @Generated private final String name; /* * The fields of the index. */ - private List fields; + @Generated + private final List fields; /* * The scoring profiles for the index. */ + @Generated private List scoringProfiles; /* - * 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. + * 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. */ + @Generated private String defaultScoringProfile; /* * Options to control Cross-Origin Resource Sharing (CORS) for the index. */ + @Generated private CorsOptions corsOptions; /* * The suggesters for the index. */ + @Generated private List suggesters; /* * The analyzers for the index. */ + @Generated private List analyzers; /* * The tokenizers for the index. */ + @Generated private List tokenizers; /* * The token filters for the index. */ + @Generated private List tokenFilters; /* * The character filters for the index. */ + @Generated private List charFilters; /* * The normalizers for the index. */ + @Generated private List normalizers; /* - * 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. + * 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. */ + @Generated private SearchResourceEncryptionKey encryptionKey; /* - * 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. + * 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. */ + @Generated private SimilarityAlgorithm similarity; /* * Defines parameters for a search index that influence semantic capabilities. */ + @Generated private SemanticSearch semanticSearch; /* * Contains configuration options related to vector search. */ + @Generated private VectorSearch vectorSearch; /* * The ETag of the index. */ + @Generated private String eTag; /** * Creates an instance of SearchIndex class. - * + * * @param name the name value to set. + * @param fields the fields value to set. */ - public SearchIndex(String name) { + @Generated + public SearchIndex(String name, List fields) { this.name = name; + this.fields = fields; } /** * Get the name property: The name of the index. - * + * * @return the name value. */ + @Generated public String getName() { return this.name; } /** * Get the fields property: The fields of the index. - * + * * @return the fields value. */ + @Generated public List getFields() { return this.fields; } - /** - * Set the fields property: The fields of the index. - * - * @param fields the fields value to set. - * @return the SearchIndex object itself. - */ - public SearchIndex setFields(List fields) { - this.fields = fields; - return this; - } - /** * Get the scoringProfiles property: The scoring profiles for the index. - * + * * @return the scoringProfiles value. */ + @Generated public List getScoringProfiles() { return this.scoringProfiles; } /** * Set the scoringProfiles property: The scoring profiles for the index. - * + * * @param scoringProfiles the scoringProfiles value to set. * @return the SearchIndex object itself. */ + @Generated public SearchIndex setScoringProfiles(List scoringProfiles) { this.scoringProfiles = scoringProfiles; return this; @@ -168,23 +184,27 @@ public SearchIndex setScoringProfiles(List scoringProfiles) { /** * Get the defaultScoringProfile property: 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. - * + * If + * this property is not set and no scoring profile is specified in the query, then + * default scoring (tf-idf) will be used. + * * @return the defaultScoringProfile value. */ + @Generated public String getDefaultScoringProfile() { return this.defaultScoringProfile; } /** * Set the defaultScoringProfile property: 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. - * + * If + * this property is not set and no scoring profile is specified in the query, then + * default scoring (tf-idf) will be used. + * * @param defaultScoringProfile the defaultScoringProfile value to set. * @return the SearchIndex object itself. */ + @Generated public SearchIndex setDefaultScoringProfile(String defaultScoringProfile) { this.defaultScoringProfile = defaultScoringProfile; return this; @@ -192,19 +212,21 @@ public SearchIndex setDefaultScoringProfile(String defaultScoringProfile) { /** * Get the corsOptions property: Options to control Cross-Origin Resource Sharing (CORS) for the index. - * + * * @return the corsOptions value. */ + @Generated public CorsOptions getCorsOptions() { return this.corsOptions; } /** * Set the corsOptions property: Options to control Cross-Origin Resource Sharing (CORS) for the index. - * + * * @param corsOptions the corsOptions value to set. * @return the SearchIndex object itself. */ + @Generated public SearchIndex setCorsOptions(CorsOptions corsOptions) { this.corsOptions = corsOptions; return this; @@ -212,19 +234,21 @@ public SearchIndex setCorsOptions(CorsOptions corsOptions) { /** * Get the suggesters property: The suggesters for the index. - * + * * @return the suggesters value. */ + @Generated public List getSuggesters() { return this.suggesters; } /** * Set the suggesters property: The suggesters for the index. - * + * * @param suggesters the suggesters value to set. * @return the SearchIndex object itself. */ + @Generated public SearchIndex setSuggesters(List suggesters) { this.suggesters = suggesters; return this; @@ -232,19 +256,21 @@ public SearchIndex setSuggesters(List suggesters) { /** * Get the analyzers property: The analyzers for the index. - * + * * @return the analyzers value. */ + @Generated public List getAnalyzers() { return this.analyzers; } /** * Set the analyzers property: The analyzers for the index. - * + * * @param analyzers the analyzers value to set. * @return the SearchIndex object itself. */ + @Generated public SearchIndex setAnalyzers(List analyzers) { this.analyzers = analyzers; return this; @@ -252,19 +278,21 @@ public SearchIndex setAnalyzers(List analyzers) { /** * Get the tokenizers property: The tokenizers for the index. - * + * * @return the tokenizers value. */ + @Generated public List getTokenizers() { return this.tokenizers; } /** * Set the tokenizers property: The tokenizers for the index. - * + * * @param tokenizers the tokenizers value to set. * @return the SearchIndex object itself. */ + @Generated public SearchIndex setTokenizers(List tokenizers) { this.tokenizers = tokenizers; return this; @@ -272,19 +300,21 @@ public SearchIndex setTokenizers(List tokenizers) { /** * Get the tokenFilters property: The token filters for the index. - * + * * @return the tokenFilters value. */ + @Generated public List getTokenFilters() { return this.tokenFilters; } /** * Set the tokenFilters property: The token filters for the index. - * + * * @param tokenFilters the tokenFilters value to set. * @return the SearchIndex object itself. */ + @Generated public SearchIndex setTokenFilters(List tokenFilters) { this.tokenFilters = tokenFilters; return this; @@ -292,19 +322,21 @@ public SearchIndex setTokenFilters(List tokenFilters) { /** * Get the charFilters property: The character filters for the index. - * + * * @return the charFilters value. */ + @Generated public List getCharFilters() { return this.charFilters; } /** * Set the charFilters property: The character filters for the index. - * + * * @param charFilters the charFilters value to set. * @return the SearchIndex object itself. */ + @Generated public SearchIndex setCharFilters(List charFilters) { this.charFilters = charFilters; return this; @@ -312,19 +344,21 @@ public SearchIndex setCharFilters(List charFilters) { /** * Get the normalizers property: The normalizers for the index. - * + * * @return the normalizers value. */ + @Generated public List getNormalizers() { return this.normalizers; } /** * Set the normalizers property: The normalizers for the index. - * + * * @param normalizers the normalizers value to set. * @return the SearchIndex object itself. */ + @Generated public SearchIndex setNormalizers(List normalizers) { this.normalizers = normalizers; return this; @@ -332,55 +366,65 @@ public SearchIndex setNormalizers(List normalizers) { /** * Get the encryptionKey property: 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 + * 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. - * + * * @return the encryptionKey value. */ + @Generated public SearchResourceEncryptionKey getEncryptionKey() { return this.encryptionKey; } /** * Set the encryptionKey property: 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 + * 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. - * + * * @param encryptionKey the encryptionKey value to set. * @return the SearchIndex object itself. */ + @Generated public SearchIndex setEncryptionKey(SearchResourceEncryptionKey encryptionKey) { this.encryptionKey = encryptionKey; return this; } /** - * Get the similarity property: 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. - * + * Get the similarity property: 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. + * * @return the similarity value. */ + @Generated public SimilarityAlgorithm getSimilarity() { return this.similarity; } /** - * Set the similarity property: 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. - * + * Set the similarity property: 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. + * * @param similarity the similarity value to set. * @return the SearchIndex object itself. */ + @Generated public SearchIndex setSimilarity(SimilarityAlgorithm similarity) { this.similarity = similarity; return this; @@ -388,19 +432,21 @@ public SearchIndex setSimilarity(SimilarityAlgorithm similarity) { /** * Get the semanticSearch property: Defines parameters for a search index that influence semantic capabilities. - * + * * @return the semanticSearch value. */ + @Generated public SemanticSearch getSemanticSearch() { return this.semanticSearch; } /** * Set the semanticSearch property: Defines parameters for a search index that influence semantic capabilities. - * + * * @param semanticSearch the semanticSearch value to set. * @return the SearchIndex object itself. */ + @Generated public SearchIndex setSemanticSearch(SemanticSearch semanticSearch) { this.semanticSearch = semanticSearch; return this; @@ -408,19 +454,21 @@ public SearchIndex setSemanticSearch(SemanticSearch semanticSearch) { /** * Get the vectorSearch property: Contains configuration options related to vector search. - * + * * @return the vectorSearch value. */ + @Generated public VectorSearch getVectorSearch() { return this.vectorSearch; } /** * Set the vectorSearch property: Contains configuration options related to vector search. - * + * * @param vectorSearch the vectorSearch value to set. * @return the SearchIndex object itself. */ + @Generated public SearchIndex setVectorSearch(VectorSearch vectorSearch) { this.vectorSearch = vectorSearch; return this; @@ -428,19 +476,21 @@ public SearchIndex setVectorSearch(VectorSearch vectorSearch) { /** * Get the eTag property: The ETag of the index. - * + * * @return the eTag value. */ + @Generated public String getETag() { return this.eTag; } /** * Set the eTag property: The ETag of the index. - * + * * @param eTag the eTag value to set. * @return the SearchIndex object itself. */ + @Generated public SearchIndex setETag(String eTag) { this.eTag = eTag; return this; @@ -449,6 +499,7 @@ public SearchIndex setETag(String eTag) { /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); @@ -474,16 +525,16 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of SearchIndex from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of SearchIndex if the JsonReader was pointing to an instance of it, or null if it was * pointing to JSON null. * @throws IllegalStateException If the deserialized JSON object was missing any required properties. * @throws IOException If an error occurs while reading the SearchIndex. */ + @Generated public static SearchIndex fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { - boolean nameFound = false; String name = null; List fields = null; List scoringProfiles = null; @@ -503,9 +554,9 @@ public static SearchIndex fromJson(JsonReader jsonReader) throws IOException { while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); + if ("name".equals(fieldName)) { name = reader.getString(); - nameFound = true; } else if ("fields".equals(fieldName)) { fields = reader.readArray(reader1 -> SearchField.fromJson(reader1)); } else if ("scoringProfiles".equals(fieldName)) { @@ -540,114 +591,23 @@ public static SearchIndex fromJson(JsonReader jsonReader) throws IOException { reader.skipChildren(); } } - if (nameFound) { - SearchIndex deserializedSearchIndex = new SearchIndex(name); - deserializedSearchIndex.fields = fields; - deserializedSearchIndex.scoringProfiles = scoringProfiles; - deserializedSearchIndex.defaultScoringProfile = defaultScoringProfile; - deserializedSearchIndex.corsOptions = corsOptions; - deserializedSearchIndex.suggesters = suggesters; - deserializedSearchIndex.analyzers = analyzers; - deserializedSearchIndex.tokenizers = tokenizers; - deserializedSearchIndex.tokenFilters = tokenFilters; - deserializedSearchIndex.charFilters = charFilters; - deserializedSearchIndex.normalizers = normalizers; - deserializedSearchIndex.encryptionKey = encryptionKey; - deserializedSearchIndex.similarity = similarity; - deserializedSearchIndex.semanticSearch = semanticSearch; - deserializedSearchIndex.vectorSearch = vectorSearch; - deserializedSearchIndex.eTag = eTag; - return deserializedSearchIndex; - } - throw new IllegalStateException("Missing required property: name"); + SearchIndex deserializedSearchIndex = new SearchIndex(name, fields); + deserializedSearchIndex.scoringProfiles = scoringProfiles; + deserializedSearchIndex.defaultScoringProfile = defaultScoringProfile; + deserializedSearchIndex.corsOptions = corsOptions; + deserializedSearchIndex.suggesters = suggesters; + deserializedSearchIndex.analyzers = analyzers; + deserializedSearchIndex.tokenizers = tokenizers; + deserializedSearchIndex.tokenFilters = tokenFilters; + deserializedSearchIndex.charFilters = charFilters; + deserializedSearchIndex.normalizers = normalizers; + deserializedSearchIndex.encryptionKey = encryptionKey; + deserializedSearchIndex.similarity = similarity; + deserializedSearchIndex.semanticSearch = semanticSearch; + deserializedSearchIndex.vectorSearch = vectorSearch; + deserializedSearchIndex.eTag = eTag; + + return deserializedSearchIndex; }); } - - /** - * Constructor of {@link SearchIndex}. - * - * @param name The name of the index. - * @param fields The fields of the index. - */ - public SearchIndex(String name, List fields) { - this.name = name; - this.fields = fields; - } - - /** - * Set the fields property: The fields of the index. - * - * @param fields the fields value to set. - * @return the SearchIndex object itself. - */ - public SearchIndex setFields(SearchField... fields) { - this.fields = (fields == null) ? null : Arrays.asList(fields); - return this; - } - - /** - * Set the scoringProfiles property: The scoring profiles for the index. - * - * @param scoringProfiles the scoringProfiles value to set. - * @return the SearchIndex object itself. - */ - public SearchIndex setScoringProfiles(ScoringProfile... scoringProfiles) { - this.scoringProfiles = (scoringProfiles == null) ? null : Arrays.asList(scoringProfiles); - return this; - } - - /** - * Set the suggesters property: The suggesters for the index. - * - * @param suggesters the suggesters value to set. - * @return the SearchIndex object itself. - */ - public SearchIndex setSuggesters(SearchSuggester... suggesters) { - this.suggesters = (suggesters == null) ? null : Arrays.asList(suggesters); - return this; - } - - /** - * Set the analyzers property: The analyzers for the index. - * - * @param analyzers the analyzers value to set. - * @return the SearchIndex object itself. - */ - public SearchIndex setAnalyzers(LexicalAnalyzer... analyzers) { - this.analyzers = (analyzers == null) ? null : Arrays.asList(analyzers); - return this; - } - - /** - * Set the tokenizers property: The tokenizers for the index. - * - * @param tokenizers the tokenizers value to set. - * @return the SearchIndex object itself. - */ - public SearchIndex setTokenizers(LexicalTokenizer... tokenizers) { - this.tokenizers = (tokenizers == null) ? null : Arrays.asList(tokenizers); - return this; - } - - /** - * Set the tokenFilters property: The token filters for the index. - * - * @param tokenFilters the tokenFilters value to set. - * @return the SearchIndex object itself. - */ - public SearchIndex setTokenFilters(TokenFilter... tokenFilters) { - this.tokenFilters = (tokenFilters == null) ? null : Arrays.asList(tokenFilters); - return this; - } - - /** - * Set the charFilters property: The character filters for the index. - * - * @param charFilters the charFilters value to set. - * @return the SearchIndex object itself. - */ - public SearchIndex setCharFilters(CharFilter... charFilters) { - this.charFilters = (charFilters == null) ? null : Arrays.asList(charFilters); - return this; - } } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/SearchIndexer.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SearchIndexer.java similarity index 68% rename from sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/SearchIndexer.java rename to sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SearchIndexer.java index 0a0a5feef95c..b1bf28b937e0 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/SearchIndexer.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SearchIndexer.java @@ -1,17 +1,16 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. -package com.azure.search.documents.indexes.models; +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.search.documents.models; import com.azure.core.annotation.Fluent; +import com.azure.core.annotation.Generated; import com.azure.json.JsonReader; import com.azure.json.JsonSerializable; import com.azure.json.JsonToken; import com.azure.json.JsonWriter; import java.io.IOException; -import java.util.Arrays; import java.util.List; /** @@ -19,112 +18,137 @@ */ @Fluent public final class SearchIndexer implements JsonSerializable { - /* * The name of the indexer. */ + @Generated private final String name; /* * The description of the indexer. */ + @Generated private String description; /* * The name of the datasource from which this indexer reads data. */ - private String dataSourceName; + @Generated + private final String dataSourceName; /* * The name of the skillset executing with this indexer. */ + @Generated private String skillsetName; /* * The name of the index to which this indexer writes data. */ - private String targetIndexName; + @Generated + private final String targetIndexName; /* * The schedule for this indexer. */ + @Generated private IndexingSchedule schedule; /* * Parameters for indexer execution. */ + @Generated private IndexingParameters parameters; /* - * Defines mappings between fields in the data source and corresponding target fields in the index. + * Defines mappings between fields in the data source and corresponding target + * fields in the index. */ + @Generated private List fieldMappings; /* - * Output field mappings are applied after enrichment and immediately before indexing. + * Output field mappings are applied after enrichment and immediately before + * indexing. */ + @Generated private List outputFieldMappings; /* * A value indicating whether the indexer is disabled. Default is false. */ + @Generated private Boolean isDisabled; /* * The ETag of the indexer. */ + @Generated private String eTag; /* - * 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. - */ + * 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. + */ + @Generated private SearchResourceEncryptionKey encryptionKey; /* - * Adds caching to an enrichment pipeline to allow for incremental modification steps without having to rebuild the - * index every time. + * Adds caching to an enrichment pipeline to allow for incremental modification + * steps without having to rebuild the index every time. */ + @Generated private SearchIndexerCache cache; /** * Creates an instance of SearchIndexer class. - * + * * @param name the name value to set. + * @param dataSourceName the dataSourceName value to set. + * @param targetIndexName the targetIndexName value to set. */ - public SearchIndexer(String name) { + @Generated + public SearchIndexer(String name, String dataSourceName, String targetIndexName) { this.name = name; + this.dataSourceName = dataSourceName; + this.targetIndexName = targetIndexName; } /** * Get the name property: The name of the indexer. - * + * * @return the name value. */ + @Generated public String getName() { return this.name; } /** * Get the description property: The description of the indexer. - * + * * @return the description value. */ + @Generated public String getDescription() { return this.description; } /** * Set the description property: The description of the indexer. - * + * * @param description the description value to set. * @return the SearchIndexer object itself. */ + @Generated public SearchIndexer setDescription(String description) { this.description = description; return this; @@ -132,39 +156,31 @@ public SearchIndexer setDescription(String description) { /** * Get the dataSourceName property: The name of the datasource from which this indexer reads data. - * + * * @return the dataSourceName value. */ + @Generated public String getDataSourceName() { return this.dataSourceName; } - /** - * Set the dataSourceName property: The name of the datasource from which this indexer reads data. - * - * @param dataSourceName the dataSourceName value to set. - * @return the SearchIndexer object itself. - */ - public SearchIndexer setDataSourceName(String dataSourceName) { - this.dataSourceName = dataSourceName; - return this; - } - /** * Get the skillsetName property: The name of the skillset executing with this indexer. - * + * * @return the skillsetName value. */ + @Generated public String getSkillsetName() { return this.skillsetName; } /** * Set the skillsetName property: The name of the skillset executing with this indexer. - * + * * @param skillsetName the skillsetName value to set. * @return the SearchIndexer object itself. */ + @Generated public SearchIndexer setSkillsetName(String skillsetName) { this.skillsetName = skillsetName; return this; @@ -172,39 +188,31 @@ public SearchIndexer setSkillsetName(String skillsetName) { /** * Get the targetIndexName property: The name of the index to which this indexer writes data. - * + * * @return the targetIndexName value. */ + @Generated public String getTargetIndexName() { return this.targetIndexName; } - /** - * Set the targetIndexName property: The name of the index to which this indexer writes data. - * - * @param targetIndexName the targetIndexName value to set. - * @return the SearchIndexer object itself. - */ - public SearchIndexer setTargetIndexName(String targetIndexName) { - this.targetIndexName = targetIndexName; - return this; - } - /** * Get the schedule property: The schedule for this indexer. - * + * * @return the schedule value. */ + @Generated public IndexingSchedule getSchedule() { return this.schedule; } /** * Set the schedule property: The schedule for this indexer. - * + * * @param schedule the schedule value to set. * @return the SearchIndexer object itself. */ + @Generated public SearchIndexer setSchedule(IndexingSchedule schedule) { this.schedule = schedule; return this; @@ -212,19 +220,21 @@ public SearchIndexer setSchedule(IndexingSchedule schedule) { /** * Get the parameters property: Parameters for indexer execution. - * + * * @return the parameters value. */ + @Generated public IndexingParameters getParameters() { return this.parameters; } /** * Set the parameters property: Parameters for indexer execution. - * + * * @param parameters the parameters value to set. * @return the SearchIndexer object itself. */ + @Generated public SearchIndexer setParameters(IndexingParameters parameters) { this.parameters = parameters; return this; @@ -233,9 +243,10 @@ public SearchIndexer setParameters(IndexingParameters parameters) { /** * Get the fieldMappings property: Defines mappings between fields in the data source and corresponding target * fields in the index. - * + * * @return the fieldMappings value. */ + @Generated public List getFieldMappings() { return this.fieldMappings; } @@ -243,10 +254,11 @@ public List getFieldMappings() { /** * Set the fieldMappings property: Defines mappings between fields in the data source and corresponding target * fields in the index. - * + * * @param fieldMappings the fieldMappings value to set. * @return the SearchIndexer object itself. */ + @Generated public SearchIndexer setFieldMappings(List fieldMappings) { this.fieldMappings = fieldMappings; return this; @@ -255,9 +267,10 @@ public SearchIndexer setFieldMappings(List fieldMappings) { /** * Get the outputFieldMappings property: Output field mappings are applied after enrichment and immediately before * indexing. - * + * * @return the outputFieldMappings value. */ + @Generated public List getOutputFieldMappings() { return this.outputFieldMappings; } @@ -265,10 +278,11 @@ public List getOutputFieldMappings() { /** * Set the outputFieldMappings property: Output field mappings are applied after enrichment and immediately before * indexing. - * + * * @param outputFieldMappings the outputFieldMappings value to set. * @return the SearchIndexer object itself. */ + @Generated public SearchIndexer setOutputFieldMappings(List outputFieldMappings) { this.outputFieldMappings = outputFieldMappings; return this; @@ -276,19 +290,21 @@ public SearchIndexer setOutputFieldMappings(List outputFieldMappin /** * Get the isDisabled property: A value indicating whether the indexer is disabled. Default is false. - * + * * @return the isDisabled value. */ + @Generated public Boolean isDisabled() { return this.isDisabled; } /** * Set the isDisabled property: A value indicating whether the indexer is disabled. Default is false. - * + * * @param isDisabled the isDisabled value to set. * @return the SearchIndexer object itself. */ + @Generated public SearchIndexer setIsDisabled(Boolean isDisabled) { this.isDisabled = isDisabled; return this; @@ -296,19 +312,21 @@ public SearchIndexer setIsDisabled(Boolean isDisabled) { /** * Get the eTag property: The ETag of the indexer. - * + * * @return the eTag value. */ + @Generated public String getETag() { return this.eTag; } /** * Set the eTag property: The ETag of the indexer. - * + * * @param eTag the eTag value to set. * @return the SearchIndexer object itself. */ + @Generated public SearchIndexer setETag(String eTag) { this.eTag = eTag; return this; @@ -316,55 +334,63 @@ public SearchIndexer setETag(String eTag) { /** * Get the encryptionKey property: 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. - * + * 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. + * * @return the encryptionKey value. */ + @Generated public SearchResourceEncryptionKey getEncryptionKey() { return this.encryptionKey; } /** * Set the encryptionKey property: 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. - * + * 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. + * * @param encryptionKey the encryptionKey value to set. * @return the SearchIndexer object itself. */ + @Generated public SearchIndexer setEncryptionKey(SearchResourceEncryptionKey encryptionKey) { this.encryptionKey = encryptionKey; return this; } /** - * Get the cache property: Adds caching to an enrichment pipeline to allow for incremental modification steps - * without having to rebuild the index every time. - * + * Get the cache property: Adds caching to an enrichment pipeline to allow for incremental modification + * steps without having to rebuild the index every time. + * * @return the cache value. */ + @Generated public SearchIndexerCache getCache() { return this.cache; } /** - * Set the cache property: Adds caching to an enrichment pipeline to allow for incremental modification steps - * without having to rebuild the index every time. - * + * Set the cache property: Adds caching to an enrichment pipeline to allow for incremental modification + * steps without having to rebuild the index every time. + * * @param cache the cache value to set. * @return the SearchIndexer object itself. */ + @Generated public SearchIndexer setCache(SearchIndexerCache cache) { this.cache = cache; return this; @@ -373,14 +399,15 @@ public SearchIndexer setCache(SearchIndexerCache cache) { /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); jsonWriter.writeStringField("name", this.name); - jsonWriter.writeStringField("description", this.description); jsonWriter.writeStringField("dataSourceName", this.dataSourceName); - jsonWriter.writeStringField("skillsetName", this.skillsetName); jsonWriter.writeStringField("targetIndexName", this.targetIndexName); + jsonWriter.writeStringField("description", this.description); + jsonWriter.writeStringField("skillsetName", this.skillsetName); jsonWriter.writeJsonField("schedule", this.schedule); jsonWriter.writeJsonField("parameters", this.parameters); jsonWriter.writeArrayField("fieldMappings", this.fieldMappings, (writer, element) -> writer.writeJson(element)); @@ -395,21 +422,21 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of SearchIndexer from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of SearchIndexer if the JsonReader was pointing to an instance of it, or null if it was * pointing to JSON null. * @throws IllegalStateException If the deserialized JSON object was missing any required properties. * @throws IOException If an error occurs while reading the SearchIndexer. */ + @Generated public static SearchIndexer fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { - boolean nameFound = false; String name = null; - String description = null; String dataSourceName = null; - String skillsetName = null; String targetIndexName = null; + String description = null; + String skillsetName = null; IndexingSchedule schedule = null; IndexingParameters parameters = null; List fieldMappings = null; @@ -421,17 +448,17 @@ public static SearchIndexer fromJson(JsonReader jsonReader) throws IOException { while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); + if ("name".equals(fieldName)) { name = reader.getString(); - nameFound = true; - } else if ("description".equals(fieldName)) { - description = reader.getString(); } else if ("dataSourceName".equals(fieldName)) { dataSourceName = reader.getString(); - } else if ("skillsetName".equals(fieldName)) { - skillsetName = reader.getString(); } else if ("targetIndexName".equals(fieldName)) { targetIndexName = reader.getString(); + } else if ("description".equals(fieldName)) { + description = reader.getString(); + } else if ("skillsetName".equals(fieldName)) { + skillsetName = reader.getString(); } else if ("schedule".equals(fieldName)) { schedule = IndexingSchedule.fromJson(reader); } else if ("parameters".equals(fieldName)) { @@ -452,60 +479,19 @@ public static SearchIndexer fromJson(JsonReader jsonReader) throws IOException { reader.skipChildren(); } } - if (nameFound) { - SearchIndexer deserializedSearchIndexer = new SearchIndexer(name); - deserializedSearchIndexer.description = description; - deserializedSearchIndexer.dataSourceName = dataSourceName; - deserializedSearchIndexer.skillsetName = skillsetName; - deserializedSearchIndexer.targetIndexName = targetIndexName; - deserializedSearchIndexer.schedule = schedule; - deserializedSearchIndexer.parameters = parameters; - deserializedSearchIndexer.fieldMappings = fieldMappings; - deserializedSearchIndexer.outputFieldMappings = outputFieldMappings; - deserializedSearchIndexer.isDisabled = isDisabled; - deserializedSearchIndexer.eTag = eTag; - deserializedSearchIndexer.encryptionKey = encryptionKey; - deserializedSearchIndexer.cache = cache; - return deserializedSearchIndexer; - } - throw new IllegalStateException("Missing required property: name"); + SearchIndexer deserializedSearchIndexer = new SearchIndexer(name, dataSourceName, targetIndexName); + deserializedSearchIndexer.description = description; + deserializedSearchIndexer.skillsetName = skillsetName; + deserializedSearchIndexer.schedule = schedule; + deserializedSearchIndexer.parameters = parameters; + deserializedSearchIndexer.fieldMappings = fieldMappings; + deserializedSearchIndexer.outputFieldMappings = outputFieldMappings; + deserializedSearchIndexer.isDisabled = isDisabled; + deserializedSearchIndexer.eTag = eTag; + deserializedSearchIndexer.encryptionKey = encryptionKey; + deserializedSearchIndexer.cache = cache; + + return deserializedSearchIndexer; }); } - - /** - * Constructor of {@link SearchIndexer}. - * - * @param name The name of the indexer. - * @param dataSourceName The name of the datasource from which this indexer reads data. - * @param targetIndexName The name of the index to which this indexer writes data. - */ - public SearchIndexer(String name, String dataSourceName, String targetIndexName) { - this.name = name; - this.dataSourceName = dataSourceName; - this.targetIndexName = targetIndexName; - } - - /** - * Set the fieldMappings property: Defines mappings between fields in the data source and corresponding target - * fields in the index. - * - * @param fieldMappings the fieldMappings value to set. - * @return the SearchIndexer object itself. - */ - public SearchIndexer setFieldMappings(FieldMapping... fieldMappings) { - this.fieldMappings = (fieldMappings == null) ? null : Arrays.asList(fieldMappings); - return this; - } - - /** - * Set the outputFieldMappings property: Output field mappings are applied after enrichment and immediately before - * indexing. - * - * @param outputFieldMappings the outputFieldMappings value to set. - * @return the SearchIndexer object itself. - */ - public SearchIndexer setOutputFieldMappings(FieldMapping... outputFieldMappings) { - this.outputFieldMappings = (outputFieldMappings == null) ? null : Arrays.asList(outputFieldMappings); - return this; - } } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/SearchIndexerCache.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SearchIndexerCache.java similarity index 68% rename from sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/SearchIndexerCache.java rename to sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SearchIndexerCache.java index 6f8653a18d02..2f062923ede9 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/SearchIndexerCache.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SearchIndexerCache.java @@ -1,12 +1,11 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) TypeSpec Code Generator. -package com.azure.search.documents.indexes.models; +package com.azure.search.documents.models; import com.azure.core.annotation.Fluent; +import com.azure.core.annotation.Generated; import com.azure.json.JsonReader; import com.azure.json.JsonSerializable; import com.azure.json.JsonToken; @@ -14,51 +13,67 @@ import java.io.IOException; /** - * The SearchIndexerCache model. + * The type of the cache. */ @Fluent public final class SearchIndexerCache implements JsonSerializable { /* - * The connection string to the storage account where the cache data will be persisted. + * The connection string to the storage account where the cache data will be + * persisted. */ + @Generated private String storageConnectionString; /* * Specifies whether incremental reprocessing is enabled. */ + @Generated private Boolean enableReprocessing; /* - * 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. + * 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. */ + @Generated private SearchIndexerDataIdentity identity; + /* + * A guid for the SearchIndexerCache. + */ + @Generated + private String id; + /** * Creates an instance of SearchIndexerCache class. */ + @Generated public SearchIndexerCache() { } /** * Get the storageConnectionString property: The connection string to the storage account where the cache data will - * be persisted. + * be + * persisted. * * @return the storageConnectionString value. */ + @Generated public String getStorageConnectionString() { return this.storageConnectionString; } /** * Set the storageConnectionString property: The connection string to the storage account where the cache data will - * be persisted. + * be + * persisted. * * @param storageConnectionString the storageConnectionString value to set. * @return the SearchIndexerCache object itself. */ + @Generated public SearchIndexerCache setStorageConnectionString(String storageConnectionString) { this.storageConnectionString = storageConnectionString; return this; @@ -69,6 +84,7 @@ public SearchIndexerCache setStorageConnectionString(String storageConnectionStr * * @return the enableReprocessing value. */ + @Generated public Boolean isEnableReprocessing() { return this.enableReprocessing; } @@ -79,46 +95,75 @@ public Boolean isEnableReprocessing() { * @param enableReprocessing the enableReprocessing value to set. * @return the SearchIndexerCache object itself. */ + @Generated public SearchIndexerCache setEnableReprocessing(Boolean enableReprocessing) { this.enableReprocessing = enableReprocessing; return this; } /** - * Get the identity property: 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. + * Get the identity property: 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. * * @return the identity value. */ + @Generated public SearchIndexerDataIdentity getIdentity() { return this.identity; } /** - * Set the identity property: 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. + * Set the identity property: 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. * * @param identity the identity value to set. * @return the SearchIndexerCache object itself. */ + @Generated public SearchIndexerCache setIdentity(SearchIndexerDataIdentity identity) { this.identity = identity; return this; } + /** + * Get the id property: A guid for the SearchIndexerCache. + * + * @return the id value. + */ + @Generated + public String getId() { + return this.id; + } + + /** + * Set the id property: A guid for the SearchIndexerCache. + * + * @param id the id value to set. + * @return the SearchIndexerCache object itself. + */ + @Generated + public SearchIndexerCache setId(String id) { + this.id = id; + return this; + } + /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); jsonWriter.writeStringField("storageConnectionString", this.storageConnectionString); jsonWriter.writeBooleanField("enableReprocessing", this.enableReprocessing); jsonWriter.writeJsonField("identity", this.identity); + jsonWriter.writeStringField("id", this.id); return jsonWriter.writeEndObject(); } @@ -130,6 +175,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { * pointing to JSON null. * @throws IOException If an error occurs while reading the SearchIndexerCache. */ + @Generated public static SearchIndexerCache fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { SearchIndexerCache deserializedSearchIndexerCache = new SearchIndexerCache(); @@ -143,6 +189,8 @@ public static SearchIndexerCache fromJson(JsonReader jsonReader) throws IOExcept deserializedSearchIndexerCache.enableReprocessing = reader.getNullable(JsonReader::getBoolean); } else if ("identity".equals(fieldName)) { deserializedSearchIndexerCache.identity = SearchIndexerDataIdentity.fromJson(reader); + } else if ("id".equals(fieldName)) { + deserializedSearchIndexerCache.id = reader.getString(); } else { reader.skipChildren(); } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/SearchIndexerDataContainer.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SearchIndexerDataContainer.java similarity index 71% rename from sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/SearchIndexerDataContainer.java rename to sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SearchIndexerDataContainer.java index 821bfc4597c5..704077b7089b 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/SearchIndexerDataContainer.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SearchIndexerDataContainer.java @@ -1,12 +1,11 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) TypeSpec Code Generator. -package com.azure.search.documents.indexes.models; +package com.azure.search.documents.models; import com.azure.core.annotation.Fluent; +import com.azure.core.annotation.Generated; import com.azure.json.JsonReader; import com.azure.json.JsonSerializable; import com.azure.json.JsonToken; @@ -14,20 +13,23 @@ import java.io.IOException; /** - * Represents information about the entity (such as Azure SQL table or CosmosDB collection) that will be indexed. + * Represents information about the entity (such as Azure SQL table or CosmosDB + * collection) that will be indexed. */ @Fluent public final class SearchIndexerDataContainer implements JsonSerializable { /* - * The name of the table or view (for Azure SQL data source) or collection (for CosmosDB data source) that will be - * indexed. + * The name of the table or view (for Azure SQL data source) or collection (for + * CosmosDB data source) that will be indexed. */ + @Generated private final String name; /* - * 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. + * 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. */ + @Generated private String query; /** @@ -35,37 +37,41 @@ public final class SearchIndexerDataContainer implements JsonSerializable { - boolean nameFound = false; String name = null; String query = null; while (reader.nextToken() != JsonToken.END_OBJECT) { @@ -102,21 +109,16 @@ public static SearchIndexerDataContainer fromJson(JsonReader jsonReader) throws if ("name".equals(fieldName)) { name = reader.getString(); - nameFound = true; } else if ("query".equals(fieldName)) { query = reader.getString(); } else { reader.skipChildren(); } } - if (nameFound) { - SearchIndexerDataContainer deserializedSearchIndexerDataContainer - = new SearchIndexerDataContainer(name); - deserializedSearchIndexerDataContainer.query = query; + SearchIndexerDataContainer deserializedSearchIndexerDataContainer = new SearchIndexerDataContainer(name); + deserializedSearchIndexerDataContainer.query = query; - return deserializedSearchIndexerDataContainer; - } - throw new IllegalStateException("Missing required property: name"); + return deserializedSearchIndexerDataContainer; }); } } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/SearchIndexerDataIdentity.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SearchIndexerDataIdentity.java similarity index 94% rename from sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/SearchIndexerDataIdentity.java rename to sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SearchIndexerDataIdentity.java index d439f5155b9f..cf973c35807a 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/SearchIndexerDataIdentity.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SearchIndexerDataIdentity.java @@ -1,11 +1,10 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) TypeSpec Code Generator. -package com.azure.search.documents.indexes.models; +package com.azure.search.documents.models; +import com.azure.core.annotation.Generated; import com.azure.core.annotation.Immutable; import com.azure.json.JsonReader; import com.azure.json.JsonSerializable; @@ -21,11 +20,13 @@ public class SearchIndexerDataIdentity implements JsonSerializable { String discriminatorValue = null; @@ -83,6 +87,7 @@ public static SearchIndexerDataIdentity fromJson(JsonReader jsonReader) throws I }); } + @Generated static SearchIndexerDataIdentity fromJsonKnownDiscriminator(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { SearchIndexerDataIdentity deserializedSearchIndexerDataIdentity = new SearchIndexerDataIdentity(); diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/SearchIndexerDataNoneIdentity.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SearchIndexerDataNoneIdentity.java similarity index 91% rename from sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/SearchIndexerDataNoneIdentity.java rename to sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SearchIndexerDataNoneIdentity.java index 688ae55e3041..ddff2344aecf 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/SearchIndexerDataNoneIdentity.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SearchIndexerDataNoneIdentity.java @@ -1,11 +1,10 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) TypeSpec Code Generator. -package com.azure.search.documents.indexes.models; +package com.azure.search.documents.models; +import com.azure.core.annotation.Generated; import com.azure.core.annotation.Immutable; import com.azure.json.JsonReader; import com.azure.json.JsonToken; @@ -20,11 +19,13 @@ public final class SearchIndexerDataNoneIdentity extends SearchIndexerDataIdenti /* * A URI fragment specifying the type of identity. */ + @Generated private String odataType = "#Microsoft.Azure.Search.DataNoneIdentity"; /** * Creates an instance of SearchIndexerDataNoneIdentity class. */ + @Generated public SearchIndexerDataNoneIdentity() { } @@ -33,6 +34,7 @@ public SearchIndexerDataNoneIdentity() { * * @return the odataType value. */ + @Generated @Override public String getOdataType() { return this.odataType; @@ -41,6 +43,7 @@ public String getOdataType() { /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); @@ -56,6 +59,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { * if it was pointing to JSON null. * @throws IOException If an error occurs while reading the SearchIndexerDataNoneIdentity. */ + @Generated public static SearchIndexerDataNoneIdentity fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { SearchIndexerDataNoneIdentity deserializedSearchIndexerDataNoneIdentity diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/SearchIndexerDataSourceConnection.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SearchIndexerDataSource.java similarity index 52% rename from sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/SearchIndexerDataSourceConnection.java rename to sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SearchIndexerDataSource.java index 24e63cb2cc49..727e0029719a 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/SearchIndexerDataSourceConnection.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SearchIndexerDataSource.java @@ -1,221 +1,241 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. -package com.azure.search.documents.indexes.models; +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.search.documents.models; import com.azure.core.annotation.Fluent; +import com.azure.core.annotation.Generated; import com.azure.json.JsonReader; import com.azure.json.JsonSerializable; import com.azure.json.JsonToken; import com.azure.json.JsonWriter; -import com.azure.search.documents.indexes.implementation.models.DataSourceCredentials; import java.io.IOException; /** * Represents a datasource definition, which can be used to configure an indexer. */ @Fluent -public final class SearchIndexerDataSourceConnection implements JsonSerializable { - +public final class SearchIndexerDataSource implements JsonSerializable { /* * The name of the datasource. */ + @Generated private final String name; /* * The description of the datasource. */ + @Generated private String description; /* * The type of the datasource. */ - private SearchIndexerDataSourceType type; + @Generated + private final SearchIndexerDataSourceType type; /* * Credentials for the datasource. */ - private DataSourceCredentials credentials; + @Generated + private final DataSourceCredentials credentials; /* * The data container for the datasource. */ - private SearchIndexerDataContainer container; + @Generated + private final SearchIndexerDataContainer container; /* - * 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. + * 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. */ + @Generated private SearchIndexerDataIdentity identity; /* * The data change detection policy for the datasource. */ + @Generated private DataChangeDetectionPolicy dataChangeDetectionPolicy; /* * The data deletion detection policy for the datasource. */ + @Generated private DataDeletionDetectionPolicy dataDeletionDetectionPolicy; /* * The ETag of the data source. */ + @Generated private String eTag; /* - * 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. - */ + * 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. + */ + @Generated private SearchResourceEncryptionKey encryptionKey; /** - * Creates an instance of SearchIndexerDataSourceConnection class. - * + * Creates an instance of SearchIndexerDataSource class. + * * @param name the name value to set. + * @param type the type value to set. + * @param credentials the credentials value to set. + * @param container the container value to set. */ - public SearchIndexerDataSourceConnection(String name) { + @Generated + public SearchIndexerDataSource(String name, SearchIndexerDataSourceType type, DataSourceCredentials credentials, + SearchIndexerDataContainer container) { this.name = name; + this.type = type; + this.credentials = credentials; + this.container = container; } /** * Get the name property: The name of the datasource. - * + * * @return the name value. */ + @Generated public String getName() { return this.name; } /** * Get the description property: The description of the datasource. - * + * * @return the description value. */ + @Generated public String getDescription() { return this.description; } /** * Set the description property: The description of the datasource. - * + * * @param description the description value to set. - * @return the SearchIndexerDataSourceConnection object itself. + * @return the SearchIndexerDataSource object itself. */ - public SearchIndexerDataSourceConnection setDescription(String description) { + @Generated + public SearchIndexerDataSource setDescription(String description) { this.description = description; return this; } /** * Get the type property: The type of the datasource. - * + * * @return the type value. */ + @Generated public SearchIndexerDataSourceType getType() { return this.type; } /** - * Set the type property: The type of the datasource. - * - * @param type the type value to set. - * @return the SearchIndexerDataSourceConnection object itself. + * Get the credentials property: Credentials for the datasource. + * + * @return the credentials value. */ - public SearchIndexerDataSourceConnection setType(SearchIndexerDataSourceType type) { - this.type = type; - return this; + @Generated + public DataSourceCredentials getCredentials() { + return this.credentials; } /** * Get the container property: The data container for the datasource. - * + * * @return the container value. */ + @Generated public SearchIndexerDataContainer getContainer() { return this.container; } /** - * Set the container property: The data container for the datasource. - * - * @param container the container value to set. - * @return the SearchIndexerDataSourceConnection object itself. - */ - public SearchIndexerDataSourceConnection setContainer(SearchIndexerDataContainer container) { - this.container = container; - return this; - } - - /** - * Get the identity property: 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. - * + * Get the identity property: 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. + * * @return the identity value. */ + @Generated public SearchIndexerDataIdentity getIdentity() { return this.identity; } /** - * Set the identity property: 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. - * + * Set the identity property: 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. + * * @param identity the identity value to set. - * @return the SearchIndexerDataSourceConnection object itself. + * @return the SearchIndexerDataSource object itself. */ - public SearchIndexerDataSourceConnection setIdentity(SearchIndexerDataIdentity identity) { + @Generated + public SearchIndexerDataSource setIdentity(SearchIndexerDataIdentity identity) { this.identity = identity; return this; } /** * Get the dataChangeDetectionPolicy property: The data change detection policy for the datasource. - * + * * @return the dataChangeDetectionPolicy value. */ + @Generated public DataChangeDetectionPolicy getDataChangeDetectionPolicy() { return this.dataChangeDetectionPolicy; } /** * Set the dataChangeDetectionPolicy property: The data change detection policy for the datasource. - * + * * @param dataChangeDetectionPolicy the dataChangeDetectionPolicy value to set. - * @return the SearchIndexerDataSourceConnection object itself. + * @return the SearchIndexerDataSource object itself. */ - public SearchIndexerDataSourceConnection - setDataChangeDetectionPolicy(DataChangeDetectionPolicy dataChangeDetectionPolicy) { + @Generated + public SearchIndexerDataSource setDataChangeDetectionPolicy(DataChangeDetectionPolicy dataChangeDetectionPolicy) { this.dataChangeDetectionPolicy = dataChangeDetectionPolicy; return this; } /** * Get the dataDeletionDetectionPolicy property: The data deletion detection policy for the datasource. - * + * * @return the dataDeletionDetectionPolicy value. */ + @Generated public DataDeletionDetectionPolicy getDataDeletionDetectionPolicy() { return this.dataDeletionDetectionPolicy; } /** * Set the dataDeletionDetectionPolicy property: The data deletion detection policy for the datasource. - * + * * @param dataDeletionDetectionPolicy the dataDeletionDetectionPolicy value to set. - * @return the SearchIndexerDataSourceConnection object itself. + * @return the SearchIndexerDataSource object itself. */ - public SearchIndexerDataSourceConnection + @Generated + public SearchIndexerDataSource setDataDeletionDetectionPolicy(DataDeletionDetectionPolicy dataDeletionDetectionPolicy) { this.dataDeletionDetectionPolicy = dataDeletionDetectionPolicy; return this; @@ -223,52 +243,62 @@ public DataDeletionDetectionPolicy getDataDeletionDetectionPolicy() { /** * Get the eTag property: The ETag of the data source. - * + * * @return the eTag value. */ + @Generated public String getETag() { return this.eTag; } /** * Set the eTag property: The ETag of the data source. - * + * * @param eTag the eTag value to set. - * @return the SearchIndexerDataSourceConnection object itself. + * @return the SearchIndexerDataSource object itself. */ - public SearchIndexerDataSourceConnection setETag(String eTag) { + @Generated + public SearchIndexerDataSource setETag(String eTag) { this.eTag = eTag; return this; } /** * Get the encryptionKey property: 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. - * + * 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. + * * @return the encryptionKey value. */ + @Generated public SearchResourceEncryptionKey getEncryptionKey() { return this.encryptionKey; } /** * Set the encryptionKey property: 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. - * + * 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. + * * @param encryptionKey the encryptionKey value to set. - * @return the SearchIndexerDataSourceConnection object itself. + * @return the SearchIndexerDataSource object itself. */ - public SearchIndexerDataSourceConnection setEncryptionKey(SearchResourceEncryptionKey encryptionKey) { + @Generated + public SearchIndexerDataSource setEncryptionKey(SearchResourceEncryptionKey encryptionKey) { this.encryptionKey = encryptionKey; return this; } @@ -276,14 +306,15 @@ public SearchIndexerDataSourceConnection setEncryptionKey(SearchResourceEncrypti /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); jsonWriter.writeStringField("name", this.name); - jsonWriter.writeStringField("description", this.description); jsonWriter.writeStringField("type", this.type == null ? null : this.type.toString()); jsonWriter.writeJsonField("credentials", this.credentials); jsonWriter.writeJsonField("container", this.container); + jsonWriter.writeStringField("description", this.description); jsonWriter.writeJsonField("identity", this.identity); jsonWriter.writeJsonField("dataChangeDetectionPolicy", this.dataChangeDetectionPolicy); jsonWriter.writeJsonField("dataDeletionDetectionPolicy", this.dataDeletionDetectionPolicy); @@ -293,22 +324,22 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { } /** - * Reads an instance of SearchIndexerDataSourceConnection from the JsonReader. - * + * Reads an instance of SearchIndexerDataSource from the JsonReader. + * * @param jsonReader The JsonReader being read. - * @return An instance of SearchIndexerDataSourceConnection if the JsonReader was pointing to an instance of it, or - * null if it was pointing to JSON null. + * @return An instance of SearchIndexerDataSource if the JsonReader was pointing to an instance of it, or null if it + * was pointing to JSON null. * @throws IllegalStateException If the deserialized JSON object was missing any required properties. - * @throws IOException If an error occurs while reading the SearchIndexerDataSourceConnection. + * @throws IOException If an error occurs while reading the SearchIndexerDataSource. */ - public static SearchIndexerDataSourceConnection fromJson(JsonReader jsonReader) throws IOException { + @Generated + public static SearchIndexerDataSource fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { - boolean nameFound = false; String name = null; - String description = null; SearchIndexerDataSourceType type = null; DataSourceCredentials credentials = null; SearchIndexerDataContainer container = null; + String description = null; SearchIndexerDataIdentity identity = null; DataChangeDetectionPolicy dataChangeDetectionPolicy = null; DataDeletionDetectionPolicy dataDeletionDetectionPolicy = null; @@ -317,17 +348,17 @@ public static SearchIndexerDataSourceConnection fromJson(JsonReader jsonReader) while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); + if ("name".equals(fieldName)) { name = reader.getString(); - nameFound = true; - } else if ("description".equals(fieldName)) { - description = reader.getString(); } else if ("type".equals(fieldName)) { type = SearchIndexerDataSourceType.fromString(reader.getString()); } else if ("credentials".equals(fieldName)) { credentials = DataSourceCredentials.fromJson(reader); } else if ("container".equals(fieldName)) { container = SearchIndexerDataContainer.fromJson(reader); + } else if ("description".equals(fieldName)) { + description = reader.getString(); } else if ("identity".equals(fieldName)) { identity = SearchIndexerDataIdentity.fromJson(reader); } else if ("dataChangeDetectionPolicy".equals(fieldName)) { @@ -342,64 +373,16 @@ public static SearchIndexerDataSourceConnection fromJson(JsonReader jsonReader) reader.skipChildren(); } } - if (nameFound) { - SearchIndexerDataSourceConnection deserializedSearchIndexerDataSourceConnection - = new SearchIndexerDataSourceConnection(name); - deserializedSearchIndexerDataSourceConnection.description = description; - deserializedSearchIndexerDataSourceConnection.type = type; - deserializedSearchIndexerDataSourceConnection.credentials = credentials; - deserializedSearchIndexerDataSourceConnection.container = container; - deserializedSearchIndexerDataSourceConnection.identity = identity; - deserializedSearchIndexerDataSourceConnection.dataChangeDetectionPolicy = dataChangeDetectionPolicy; - deserializedSearchIndexerDataSourceConnection.dataDeletionDetectionPolicy = dataDeletionDetectionPolicy; - deserializedSearchIndexerDataSourceConnection.eTag = eTag; - deserializedSearchIndexerDataSourceConnection.encryptionKey = encryptionKey; - return deserializedSearchIndexerDataSourceConnection; - } - throw new IllegalStateException("Missing required property: name"); + SearchIndexerDataSource deserializedSearchIndexerDataSource + = new SearchIndexerDataSource(name, type, credentials, container); + deserializedSearchIndexerDataSource.description = description; + deserializedSearchIndexerDataSource.identity = identity; + deserializedSearchIndexerDataSource.dataChangeDetectionPolicy = dataChangeDetectionPolicy; + deserializedSearchIndexerDataSource.dataDeletionDetectionPolicy = dataDeletionDetectionPolicy; + deserializedSearchIndexerDataSource.eTag = eTag; + deserializedSearchIndexerDataSource.encryptionKey = encryptionKey; + + return deserializedSearchIndexerDataSource; }); } - - /** - * Constructor of {@link SearchIndexerDataSourceConnection}. - * - * @param name The name of the datasource. - * @param type The type of the datasource. - * @param connectionString The connection string for the datasource. - * @param container The data container for the datasource. - */ - public SearchIndexerDataSourceConnection(String name, SearchIndexerDataSourceType type, String connectionString, - SearchIndexerDataContainer container) { - this.name = name; - this.type = type; - this.credentials - = (connectionString == null) ? null : new DataSourceCredentials().setConnectionString(connectionString); - this.container = container; - } - - /** - * Get the connectionString property: The connection string for the datasource. - * - * @return the connectionString value. - */ - public String getConnectionString() { - return (credentials == null) ? null : credentials.getConnectionString(); - } - - /** - * Set the connectionString property: The connection string for the datasource. - * - * @param connectionString the connectionString value to set. - * @return the SearchIndexerDataSourceConnection object itself. - */ - public SearchIndexerDataSourceConnection setConnectionString(String connectionString) { - if (connectionString == null) { - this.credentials = null; - } else if (credentials == null) { - this.credentials = new DataSourceCredentials().setConnectionString(connectionString); - } else { - credentials.setConnectionString(connectionString); - } - return this; - } } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/SearchIndexerDataSourceType.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SearchIndexerDataSourceType.java similarity index 88% rename from sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/SearchIndexerDataSourceType.java rename to sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SearchIndexerDataSourceType.java index 1606fe793b14..696d2cda1f1d 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/SearchIndexerDataSourceType.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SearchIndexerDataSourceType.java @@ -1,11 +1,10 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) TypeSpec Code Generator. -package com.azure.search.documents.indexes.models; +package com.azure.search.documents.models; +import com.azure.core.annotation.Generated; import com.azure.core.util.ExpandableStringEnum; import java.util.Collection; @@ -16,36 +15,43 @@ public final class SearchIndexerDataSourceType extends ExpandableStringEnum values() { return values(SearchIndexerDataSourceType.class); } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/SearchIndexerDataUserAssignedIdentity.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SearchIndexerDataUserAssignedIdentity.java similarity index 79% rename from sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/SearchIndexerDataUserAssignedIdentity.java rename to sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SearchIndexerDataUserAssignedIdentity.java index 58a14351ab3c..0e7ffbfe8816 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/SearchIndexerDataUserAssignedIdentity.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SearchIndexerDataUserAssignedIdentity.java @@ -1,11 +1,10 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) TypeSpec Code Generator. -package com.azure.search.documents.indexes.models; +package com.azure.search.documents.models; +import com.azure.core.annotation.Generated; import com.azure.core.annotation.Immutable; import com.azure.json.JsonReader; import com.azure.json.JsonToken; @@ -20,13 +19,16 @@ public final class SearchIndexerDataUserAssignedIdentity extends SearchIndexerDa /* * A URI fragment specifying the type of identity. */ + @Generated private String odataType = "#Microsoft.Azure.Search.DataUserAssignedIdentity"; /* - * The fully qualified Azure resource Id of a user assigned managed identity typically in the form + * 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. */ + @Generated private final String resourceId; /** @@ -34,6 +36,7 @@ public final class SearchIndexerDataUserAssignedIdentity extends SearchIndexerDa * * @param resourceId the resourceId value to set. */ + @Generated public SearchIndexerDataUserAssignedIdentity(String resourceId) { this.resourceId = resourceId; } @@ -43,19 +46,21 @@ public SearchIndexerDataUserAssignedIdentity(String resourceId) { * * @return the odataType value. */ + @Generated @Override public String getOdataType() { return this.odataType; } /** - * Get the resourceId property: The fully qualified Azure resource Id of a user assigned managed identity typically - * in the form + * Get the resourceId property: 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. * * @return the resourceId value. */ + @Generated public String getResourceId() { return this.resourceId; } @@ -63,6 +68,7 @@ public String getResourceId() { /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); @@ -80,9 +86,9 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { * @throws IllegalStateException If the deserialized JSON object was missing any required properties. * @throws IOException If an error occurs while reading the SearchIndexerDataUserAssignedIdentity. */ + @Generated public static SearchIndexerDataUserAssignedIdentity fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { - boolean resourceIdFound = false; String resourceId = null; String odataType = "#Microsoft.Azure.Search.DataUserAssignedIdentity"; while (reader.nextToken() != JsonToken.END_OBJECT) { @@ -91,21 +97,17 @@ public static SearchIndexerDataUserAssignedIdentity fromJson(JsonReader jsonRead if ("userAssignedIdentity".equals(fieldName)) { resourceId = reader.getString(); - resourceIdFound = true; } else if ("@odata.type".equals(fieldName)) { odataType = reader.getString(); } else { reader.skipChildren(); } } - if (resourceIdFound) { - SearchIndexerDataUserAssignedIdentity deserializedSearchIndexerDataUserAssignedIdentity - = new SearchIndexerDataUserAssignedIdentity(resourceId); - deserializedSearchIndexerDataUserAssignedIdentity.odataType = odataType; + SearchIndexerDataUserAssignedIdentity deserializedSearchIndexerDataUserAssignedIdentity + = new SearchIndexerDataUserAssignedIdentity(resourceId); + deserializedSearchIndexerDataUserAssignedIdentity.odataType = odataType; - return deserializedSearchIndexerDataUserAssignedIdentity; - } - throw new IllegalStateException("Missing required property: userAssignedIdentity"); + return deserializedSearchIndexerDataUserAssignedIdentity; }); } } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/SearchIndexerError.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SearchIndexerError.java similarity index 68% rename from sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/SearchIndexerError.java rename to sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SearchIndexerError.java index 2e5548e479b4..319872f45f79 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/SearchIndexerError.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SearchIndexerError.java @@ -1,19 +1,16 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) TypeSpec Code Generator. -package com.azure.search.documents.indexes.models; +package com.azure.search.documents.models; +import com.azure.core.annotation.Generated; import com.azure.core.annotation.Immutable; import com.azure.json.JsonReader; import com.azure.json.JsonSerializable; import com.azure.json.JsonToken; import com.azure.json.JsonWriter; import java.io.IOException; -import java.util.ArrayList; -import java.util.List; /** * Represents an item- or document-level indexing error. @@ -23,34 +20,44 @@ public final class SearchIndexerError implements JsonSerializable { - boolean errorMessageFound = false; String errorMessage = null; - boolean statusCodeFound = false; int statusCode = 0; String key = null; String name = null; @@ -157,10 +180,8 @@ public static SearchIndexerError fromJson(JsonReader jsonReader) throws IOExcept if ("errorMessage".equals(fieldName)) { errorMessage = reader.getString(); - errorMessageFound = true; } else if ("statusCode".equals(fieldName)) { statusCode = reader.getInt(); - statusCodeFound = true; } else if ("key".equals(fieldName)) { key = reader.getString(); } else if ("name".equals(fieldName)) { @@ -173,25 +194,13 @@ public static SearchIndexerError fromJson(JsonReader jsonReader) throws IOExcept reader.skipChildren(); } } - if (errorMessageFound && statusCodeFound) { - SearchIndexerError deserializedSearchIndexerError = new SearchIndexerError(errorMessage, statusCode); - deserializedSearchIndexerError.key = key; - deserializedSearchIndexerError.name = name; - deserializedSearchIndexerError.details = details; - deserializedSearchIndexerError.documentationLink = documentationLink; - - return deserializedSearchIndexerError; - } - List missingProperties = new ArrayList<>(); - if (!errorMessageFound) { - missingProperties.add("errorMessage"); - } - if (!statusCodeFound) { - missingProperties.add("statusCode"); - } + SearchIndexerError deserializedSearchIndexerError = new SearchIndexerError(errorMessage, statusCode); + deserializedSearchIndexerError.key = key; + deserializedSearchIndexerError.name = name; + deserializedSearchIndexerError.details = details; + deserializedSearchIndexerError.documentationLink = documentationLink; - throw new IllegalStateException( - "Missing required property/properties: " + String.join(", ", missingProperties)); + return deserializedSearchIndexerError; }); } } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/SearchIndexerIndexProjection.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SearchIndexerIndexProjection.java similarity index 77% rename from sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/SearchIndexerIndexProjection.java rename to sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SearchIndexerIndexProjection.java index e142a7258e7b..b0ad040d3dc6 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/SearchIndexerIndexProjection.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SearchIndexerIndexProjection.java @@ -1,12 +1,11 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) TypeSpec Code Generator. -package com.azure.search.documents.indexes.models; +package com.azure.search.documents.models; import com.azure.core.annotation.Fluent; +import com.azure.core.annotation.Generated; import com.azure.json.JsonReader; import com.azure.json.JsonSerializable; import com.azure.json.JsonToken; @@ -22,12 +21,14 @@ public final class SearchIndexerIndexProjection implements JsonSerializable selectors; /* - * 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. + * 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. */ + @Generated private SearchIndexerIndexProjectionsParameters parameters; /** @@ -35,6 +36,7 @@ public final class SearchIndexerIndexProjection implements JsonSerializable selectors) { this.selectors = selectors; } @@ -44,27 +46,30 @@ public SearchIndexerIndexProjection(List s * * @return the selectors value. */ + @Generated public List getSelectors() { return this.selectors; } /** - * Get the parameters property: 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. + * Get the parameters property: 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. * * @return the parameters value. */ + @Generated public SearchIndexerIndexProjectionsParameters getParameters() { return this.parameters; } /** - * Set the parameters property: 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. + * Set the parameters property: 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. * * @param parameters the parameters value to set. * @return the SearchIndexerIndexProjection object itself. */ + @Generated public SearchIndexerIndexProjection setParameters(SearchIndexerIndexProjectionsParameters parameters) { this.parameters = parameters; return this; @@ -73,6 +78,7 @@ public SearchIndexerIndexProjection setParameters(SearchIndexerIndexProjectionsP /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); @@ -90,9 +96,9 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { * @throws IllegalStateException If the deserialized JSON object was missing any required properties. * @throws IOException If an error occurs while reading the SearchIndexerIndexProjection. */ + @Generated public static SearchIndexerIndexProjection fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { - boolean selectorsFound = false; List selectors = null; SearchIndexerIndexProjectionsParameters parameters = null; while (reader.nextToken() != JsonToken.END_OBJECT) { @@ -101,21 +107,17 @@ public static SearchIndexerIndexProjection fromJson(JsonReader jsonReader) throw if ("selectors".equals(fieldName)) { selectors = reader.readArray(reader1 -> SearchIndexerIndexProjectionSelector.fromJson(reader1)); - selectorsFound = true; } else if ("parameters".equals(fieldName)) { parameters = SearchIndexerIndexProjectionsParameters.fromJson(reader); } else { reader.skipChildren(); } } - if (selectorsFound) { - SearchIndexerIndexProjection deserializedSearchIndexerIndexProjection - = new SearchIndexerIndexProjection(selectors); - deserializedSearchIndexerIndexProjection.parameters = parameters; + SearchIndexerIndexProjection deserializedSearchIndexerIndexProjection + = new SearchIndexerIndexProjection(selectors); + deserializedSearchIndexerIndexProjection.parameters = parameters; - return deserializedSearchIndexerIndexProjection; - } - throw new IllegalStateException("Missing required property: selectors"); + return deserializedSearchIndexerIndexProjection; }); } } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/SearchIndexerIndexProjectionSelector.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SearchIndexerIndexProjectionSelector.java similarity index 74% rename from sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/SearchIndexerIndexProjectionSelector.java rename to sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SearchIndexerIndexProjectionSelector.java index 85eef43efcf2..0a4bc3c9bde3 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/SearchIndexerIndexProjectionSelector.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SearchIndexerIndexProjectionSelector.java @@ -1,18 +1,16 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) TypeSpec Code Generator. -package com.azure.search.documents.indexes.models; +package com.azure.search.documents.models; +import com.azure.core.annotation.Generated; import com.azure.core.annotation.Immutable; import com.azure.json.JsonReader; import com.azure.json.JsonSerializable; import com.azure.json.JsonToken; import com.azure.json.JsonWriter; import java.io.IOException; -import java.util.ArrayList; import java.util.List; /** @@ -24,23 +22,28 @@ public final class SearchIndexerIndexProjectionSelector /* * Name of the search index to project to. Must have a key field with the 'keyword' analyzer set. */ + @Generated private final String targetIndexName; /* - * 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. + * 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. */ + @Generated private final String parentKeyFieldName; /* - * Source context for the projections. Represents the cardinality at which the document will be split into multiple - * sub documents. + * Source context for the projections. Represents the cardinality at which the + * document will be split into multiple sub documents. */ + @Generated private final String sourceContext; /* - * Mappings for the projection, or which source should be mapped to which field in the target index. + * Mappings for the projection, or which source should be mapped to which field in + * the target index. */ + @Generated private final List mappings; /** @@ -51,6 +54,7 @@ public final class SearchIndexerIndexProjectionSelector * @param sourceContext the sourceContext value to set. * @param mappings the mappings value to set. */ + @Generated public SearchIndexerIndexProjectionSelector(String targetIndexName, String parentKeyFieldName, String sourceContext, List mappings) { this.targetIndexName = targetIndexName; @@ -65,6 +69,7 @@ public SearchIndexerIndexProjectionSelector(String targetIndexName, String paren * * @return the targetIndexName value. */ + @Generated public String getTargetIndexName() { return this.targetIndexName; } @@ -75,6 +80,7 @@ public String getTargetIndexName() { * * @return the parentKeyFieldName value. */ + @Generated public String getParentKeyFieldName() { return this.parentKeyFieldName; } @@ -85,16 +91,18 @@ public String getParentKeyFieldName() { * * @return the sourceContext value. */ + @Generated public String getSourceContext() { return this.sourceContext; } /** - * Get the mappings property: Mappings for the projection, or which source should be mapped to which field in the - * target index. + * Get the mappings property: Mappings for the projection, or which source should be mapped to which field in + * the target index. * * @return the mappings value. */ + @Generated public List getMappings() { return this.mappings; } @@ -102,6 +110,7 @@ public List getMappings() { /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); @@ -121,15 +130,12 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { * @throws IllegalStateException If the deserialized JSON object was missing any required properties. * @throws IOException If an error occurs while reading the SearchIndexerIndexProjectionSelector. */ + @Generated public static SearchIndexerIndexProjectionSelector fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { - boolean targetIndexNameFound = false; String targetIndexName = null; - boolean parentKeyFieldNameFound = false; String parentKeyFieldName = null; - boolean sourceContextFound = false; String sourceContext = null; - boolean mappingsFound = false; List mappings = null; while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); @@ -137,40 +143,18 @@ public static SearchIndexerIndexProjectionSelector fromJson(JsonReader jsonReade if ("targetIndexName".equals(fieldName)) { targetIndexName = reader.getString(); - targetIndexNameFound = true; } else if ("parentKeyFieldName".equals(fieldName)) { parentKeyFieldName = reader.getString(); - parentKeyFieldNameFound = true; } else if ("sourceContext".equals(fieldName)) { sourceContext = reader.getString(); - sourceContextFound = true; } else if ("mappings".equals(fieldName)) { mappings = reader.readArray(reader1 -> InputFieldMappingEntry.fromJson(reader1)); - mappingsFound = true; } else { reader.skipChildren(); } } - if (targetIndexNameFound && parentKeyFieldNameFound && sourceContextFound && mappingsFound) { - return new SearchIndexerIndexProjectionSelector(targetIndexName, parentKeyFieldName, sourceContext, - mappings); - } - List missingProperties = new ArrayList<>(); - if (!targetIndexNameFound) { - missingProperties.add("targetIndexName"); - } - if (!parentKeyFieldNameFound) { - missingProperties.add("parentKeyFieldName"); - } - if (!sourceContextFound) { - missingProperties.add("sourceContext"); - } - if (!mappingsFound) { - missingProperties.add("mappings"); - } - - throw new IllegalStateException( - "Missing required property/properties: " + String.join(", ", missingProperties)); + return new SearchIndexerIndexProjectionSelector(targetIndexName, parentKeyFieldName, sourceContext, + mappings); }); } } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/SearchIndexerIndexProjectionsParameters.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SearchIndexerIndexProjectionsParameters.java similarity index 72% rename from sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/SearchIndexerIndexProjectionsParameters.java rename to sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SearchIndexerIndexProjectionsParameters.java index cdedeff26b03..0fa9133566fe 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/SearchIndexerIndexProjectionsParameters.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SearchIndexerIndexProjectionsParameters.java @@ -1,12 +1,12 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) TypeSpec Code Generator. -package com.azure.search.documents.indexes.models; +package com.azure.search.documents.models; import com.azure.core.annotation.Fluent; +import com.azure.core.annotation.Generated; +import com.azure.core.util.BinaryData; import com.azure.json.JsonReader; import com.azure.json.JsonSerializable; import com.azure.json.JsonToken; @@ -16,26 +16,30 @@ import java.util.Map; /** - * 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. + * 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. */ @Fluent public final class SearchIndexerIndexProjectionsParameters implements JsonSerializable { /* - * Defines behavior of the index projections in relation to the rest of the indexer. + * Defines behavior of the index projections in relation to the rest of the + * indexer. */ + @Generated private IndexProjectionMode projectionMode; /* - * 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. + * 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. */ - private Map additionalProperties; + @Generated + private Map additionalProperties; /** * Creates an instance of SearchIndexerIndexProjectionsParameters class. */ + @Generated public SearchIndexerIndexProjectionsParameters() { } @@ -45,6 +49,7 @@ public SearchIndexerIndexProjectionsParameters() { * * @return the projectionMode value. */ + @Generated public IndexProjectionMode getProjectionMode() { return this.projectionMode; } @@ -56,6 +61,7 @@ public IndexProjectionMode getProjectionMode() { * @param projectionMode the projectionMode value to set. * @return the SearchIndexerIndexProjectionsParameters object itself. */ + @Generated public SearchIndexerIndexProjectionsParameters setProjectionMode(IndexProjectionMode projectionMode) { this.projectionMode = projectionMode; return this; @@ -63,22 +69,27 @@ public SearchIndexerIndexProjectionsParameters setProjectionMode(IndexProjection /** * Get the additionalProperties property: 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. + * name + * is the name of a specific property. Each value must be of a primitive type. * * @return the additionalProperties value. */ - public Map getAdditionalProperties() { + @Generated + public Map getAdditionalProperties() { return this.additionalProperties; } /** * Set the additionalProperties property: 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. + * name + * is the name of a specific property. Each value must be of a primitive type. * * @param additionalProperties the additionalProperties value to set. * @return the SearchIndexerIndexProjectionsParameters object itself. */ - public SearchIndexerIndexProjectionsParameters setAdditionalProperties(Map additionalProperties) { + @Generated + public SearchIndexerIndexProjectionsParameters + setAdditionalProperties(Map additionalProperties) { this.additionalProperties = additionalProperties; return this; } @@ -86,14 +97,20 @@ public SearchIndexerIndexProjectionsParameters setAdditionalProperties(Map additionalProperty : additionalProperties.entrySet()) { - jsonWriter.writeUntypedField(additionalProperty.getKey(), additionalProperty.getValue()); + for (Map.Entry additionalProperty : additionalProperties.entrySet()) { + jsonWriter.writeFieldName(additionalProperty.getKey()); + if (additionalProperty.getValue() == null) { + jsonWriter.writeNull(); + } else { + additionalProperty.getValue().writeTo(jsonWriter); + } } } return jsonWriter.writeEndObject(); @@ -107,11 +124,12 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { * it, or null if it was pointing to JSON null. * @throws IOException If an error occurs while reading the SearchIndexerIndexProjectionsParameters. */ + @Generated public static SearchIndexerIndexProjectionsParameters fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { SearchIndexerIndexProjectionsParameters deserializedSearchIndexerIndexProjectionsParameters = new SearchIndexerIndexProjectionsParameters(); - Map additionalProperties = null; + Map additionalProperties = null; while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); @@ -124,7 +142,8 @@ public static SearchIndexerIndexProjectionsParameters fromJson(JsonReader jsonRe additionalProperties = new LinkedHashMap<>(); } - additionalProperties.put(fieldName, reader.readUntyped()); + additionalProperties.put(fieldName, + reader.getNullable(nonNullReader -> BinaryData.fromObject(nonNullReader.readUntyped()))); } } deserializedSearchIndexerIndexProjectionsParameters.additionalProperties = additionalProperties; diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/SearchIndexerKnowledgeStore.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SearchIndexerKnowledgeStore.java similarity index 66% rename from sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/SearchIndexerKnowledgeStore.java rename to sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SearchIndexerKnowledgeStore.java index e9d10e3b2243..2cfea4d32b57 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/SearchIndexerKnowledgeStore.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SearchIndexerKnowledgeStore.java @@ -1,47 +1,52 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) TypeSpec Code Generator. -package com.azure.search.documents.indexes.models; +package com.azure.search.documents.models; import com.azure.core.annotation.Fluent; +import com.azure.core.annotation.Generated; import com.azure.json.JsonReader; import com.azure.json.JsonSerializable; import com.azure.json.JsonToken; import com.azure.json.JsonWriter; import java.io.IOException; -import java.util.ArrayList; import java.util.List; /** - * Definition of additional projections to azure blob, table, or files, of enriched data. + * Definition of additional projections to azure blob, table, or files, of + * enriched data. */ @Fluent public final class SearchIndexerKnowledgeStore implements JsonSerializable { /* * The connection string to the storage account projections will be stored in. */ + @Generated private final String storageConnectionString; /* * A list of additional projections to perform during indexing. */ + @Generated private final List projections; /* - * 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. + * 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. */ + @Generated private SearchIndexerDataIdentity identity; /* - * 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. + * 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. */ + @Generated private SearchIndexerKnowledgeStoreParameters parameters; /** @@ -50,6 +55,7 @@ public final class SearchIndexerKnowledgeStore implements JsonSerializable projections) { this.storageConnectionString = storageConnectionString; @@ -62,6 +68,7 @@ public SearchIndexerKnowledgeStore(String storageConnectionString, * * @return the storageConnectionString value. */ + @Generated public String getStorageConnectionString() { return this.storageConnectionString; } @@ -71,53 +78,62 @@ public String getStorageConnectionString() { * * @return the projections value. */ + @Generated public List getProjections() { return this.projections; } /** - * Get the identity property: 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. + * Get the identity property: 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. * * @return the identity value. */ + @Generated public SearchIndexerDataIdentity getIdentity() { return this.identity; } /** - * Set the identity property: 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. + * Set the identity property: 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. * * @param identity the identity value to set. * @return the SearchIndexerKnowledgeStore object itself. */ + @Generated public SearchIndexerKnowledgeStore setIdentity(SearchIndexerDataIdentity identity) { this.identity = identity; return this; } /** - * Get the parameters property: 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. + * Get the parameters property: 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. * * @return the parameters value. */ + @Generated public SearchIndexerKnowledgeStoreParameters getParameters() { return this.parameters; } /** - * Set the parameters property: 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. + * Set the parameters property: 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. * * @param parameters the parameters value to set. * @return the SearchIndexerKnowledgeStore object itself. */ + @Generated public SearchIndexerKnowledgeStore setParameters(SearchIndexerKnowledgeStoreParameters parameters) { this.parameters = parameters; return this; @@ -126,6 +142,7 @@ public SearchIndexerKnowledgeStore setParameters(SearchIndexerKnowledgeStorePara /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); @@ -145,11 +162,10 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { * @throws IllegalStateException If the deserialized JSON object was missing any required properties. * @throws IOException If an error occurs while reading the SearchIndexerKnowledgeStore. */ + @Generated public static SearchIndexerKnowledgeStore fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { - boolean storageConnectionStringFound = false; String storageConnectionString = null; - boolean projectionsFound = false; List projections = null; SearchIndexerDataIdentity identity = null; SearchIndexerKnowledgeStoreParameters parameters = null; @@ -159,10 +175,8 @@ public static SearchIndexerKnowledgeStore fromJson(JsonReader jsonReader) throws if ("storageConnectionString".equals(fieldName)) { storageConnectionString = reader.getString(); - storageConnectionStringFound = true; } else if ("projections".equals(fieldName)) { projections = reader.readArray(reader1 -> SearchIndexerKnowledgeStoreProjection.fromJson(reader1)); - projectionsFound = true; } else if ("identity".equals(fieldName)) { identity = SearchIndexerDataIdentity.fromJson(reader); } else if ("parameters".equals(fieldName)) { @@ -171,24 +185,12 @@ public static SearchIndexerKnowledgeStore fromJson(JsonReader jsonReader) throws reader.skipChildren(); } } - if (storageConnectionStringFound && projectionsFound) { - SearchIndexerKnowledgeStore deserializedSearchIndexerKnowledgeStore - = new SearchIndexerKnowledgeStore(storageConnectionString, projections); - deserializedSearchIndexerKnowledgeStore.identity = identity; - deserializedSearchIndexerKnowledgeStore.parameters = parameters; + SearchIndexerKnowledgeStore deserializedSearchIndexerKnowledgeStore + = new SearchIndexerKnowledgeStore(storageConnectionString, projections); + deserializedSearchIndexerKnowledgeStore.identity = identity; + deserializedSearchIndexerKnowledgeStore.parameters = parameters; - return deserializedSearchIndexerKnowledgeStore; - } - List missingProperties = new ArrayList<>(); - if (!storageConnectionStringFound) { - missingProperties.add("storageConnectionString"); - } - if (!projectionsFound) { - missingProperties.add("projections"); - } - - throw new IllegalStateException( - "Missing required property/properties: " + String.join(", ", missingProperties)); + return deserializedSearchIndexerKnowledgeStore; }); } } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SearchIndexerKnowledgeStoreBlobProjectionSelector.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SearchIndexerKnowledgeStoreBlobProjectionSelector.java new file mode 100644 index 000000000000..54f811d28d89 --- /dev/null +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SearchIndexerKnowledgeStoreBlobProjectionSelector.java @@ -0,0 +1,161 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.search.documents.models; + +import com.azure.core.annotation.Fluent; +import com.azure.core.annotation.Generated; +import com.azure.json.JsonReader; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import java.io.IOException; +import java.util.List; + +/** + * Abstract class to share properties between concrete selectors. + */ +@Fluent +public class SearchIndexerKnowledgeStoreBlobProjectionSelector extends SearchIndexerKnowledgeStoreProjectionSelector { + /* + * Blob container to store projections in. + */ + @Generated + private final String storageContainer; + + /** + * Creates an instance of SearchIndexerKnowledgeStoreBlobProjectionSelector class. + * + * @param storageContainer the storageContainer value to set. + */ + @Generated + public SearchIndexerKnowledgeStoreBlobProjectionSelector(String storageContainer) { + this.storageContainer = storageContainer; + } + + /** + * Get the storageContainer property: Blob container to store projections in. + * + * @return the storageContainer value. + */ + @Generated + public String getStorageContainer() { + return this.storageContainer; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public SearchIndexerKnowledgeStoreBlobProjectionSelector setReferenceKeyName(String referenceKeyName) { + super.setReferenceKeyName(referenceKeyName); + return this; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public SearchIndexerKnowledgeStoreBlobProjectionSelector setGeneratedKeyName(String generatedKeyName) { + super.setGeneratedKeyName(generatedKeyName); + return this; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public SearchIndexerKnowledgeStoreBlobProjectionSelector setSource(String source) { + super.setSource(source); + return this; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public SearchIndexerKnowledgeStoreBlobProjectionSelector setSourceContext(String sourceContext) { + super.setSourceContext(sourceContext); + return this; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public SearchIndexerKnowledgeStoreBlobProjectionSelector setInputs(List inputs) { + super.setInputs(inputs); + return this; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("referenceKeyName", getReferenceKeyName()); + jsonWriter.writeStringField("generatedKeyName", getGeneratedKeyName()); + jsonWriter.writeStringField("source", getSource()); + jsonWriter.writeStringField("sourceContext", getSourceContext()); + jsonWriter.writeArrayField("inputs", getInputs(), (writer, element) -> writer.writeJson(element)); + jsonWriter.writeStringField("storageContainer", this.storageContainer); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of SearchIndexerKnowledgeStoreBlobProjectionSelector from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of SearchIndexerKnowledgeStoreBlobProjectionSelector if the JsonReader was pointing to an + * instance of it, or null if it was pointing to JSON null. + * @throws IllegalStateException If the deserialized JSON object was missing any required properties. + * @throws IOException If an error occurs while reading the SearchIndexerKnowledgeStoreBlobProjectionSelector. + */ + @Generated + public static SearchIndexerKnowledgeStoreBlobProjectionSelector fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + String referenceKeyName = null; + String generatedKeyName = null; + String source = null; + String sourceContext = null; + List inputs = null; + String storageContainer = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("referenceKeyName".equals(fieldName)) { + referenceKeyName = reader.getString(); + } else if ("generatedKeyName".equals(fieldName)) { + generatedKeyName = reader.getString(); + } else if ("source".equals(fieldName)) { + source = reader.getString(); + } else if ("sourceContext".equals(fieldName)) { + sourceContext = reader.getString(); + } else if ("inputs".equals(fieldName)) { + inputs = reader.readArray(reader1 -> InputFieldMappingEntry.fromJson(reader1)); + } else if ("storageContainer".equals(fieldName)) { + storageContainer = reader.getString(); + } else { + reader.skipChildren(); + } + } + SearchIndexerKnowledgeStoreBlobProjectionSelector deserializedSearchIndexerKnowledgeStoreBlobProjectionSelector + = new SearchIndexerKnowledgeStoreBlobProjectionSelector(storageContainer); + deserializedSearchIndexerKnowledgeStoreBlobProjectionSelector.setReferenceKeyName(referenceKeyName); + deserializedSearchIndexerKnowledgeStoreBlobProjectionSelector.setGeneratedKeyName(generatedKeyName); + deserializedSearchIndexerKnowledgeStoreBlobProjectionSelector.setSource(source); + deserializedSearchIndexerKnowledgeStoreBlobProjectionSelector.setSourceContext(sourceContext); + deserializedSearchIndexerKnowledgeStoreBlobProjectionSelector.setInputs(inputs); + + return deserializedSearchIndexerKnowledgeStoreBlobProjectionSelector; + }); + } +} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/SearchIndexerKnowledgeStoreFileProjectionSelector.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SearchIndexerKnowledgeStoreFileProjectionSelector.java similarity index 78% rename from sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/SearchIndexerKnowledgeStoreFileProjectionSelector.java rename to sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SearchIndexerKnowledgeStoreFileProjectionSelector.java index b8235670a187..dfb8e8282b04 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/SearchIndexerKnowledgeStoreFileProjectionSelector.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SearchIndexerKnowledgeStoreFileProjectionSelector.java @@ -1,12 +1,11 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) TypeSpec Code Generator. -package com.azure.search.documents.indexes.models; +package com.azure.search.documents.models; import com.azure.core.annotation.Fluent; +import com.azure.core.annotation.Generated; import com.azure.json.JsonReader; import com.azure.json.JsonToken; import com.azure.json.JsonWriter; @@ -24,6 +23,7 @@ public final class SearchIndexerKnowledgeStoreFileProjectionSelector * * @param storageContainer the storageContainer value to set. */ + @Generated public SearchIndexerKnowledgeStoreFileProjectionSelector(String storageContainer) { super(storageContainer); } @@ -31,6 +31,7 @@ public SearchIndexerKnowledgeStoreFileProjectionSelector(String storageContainer /** * {@inheritDoc} */ + @Generated @Override public SearchIndexerKnowledgeStoreFileProjectionSelector setReferenceKeyName(String referenceKeyName) { super.setReferenceKeyName(referenceKeyName); @@ -40,6 +41,7 @@ public SearchIndexerKnowledgeStoreFileProjectionSelector setReferenceKeyName(Str /** * {@inheritDoc} */ + @Generated @Override public SearchIndexerKnowledgeStoreFileProjectionSelector setGeneratedKeyName(String generatedKeyName) { super.setGeneratedKeyName(generatedKeyName); @@ -49,6 +51,7 @@ public SearchIndexerKnowledgeStoreFileProjectionSelector setGeneratedKeyName(Str /** * {@inheritDoc} */ + @Generated @Override public SearchIndexerKnowledgeStoreFileProjectionSelector setSource(String source) { super.setSource(source); @@ -58,6 +61,7 @@ public SearchIndexerKnowledgeStoreFileProjectionSelector setSource(String source /** * {@inheritDoc} */ + @Generated @Override public SearchIndexerKnowledgeStoreFileProjectionSelector setSourceContext(String sourceContext) { super.setSourceContext(sourceContext); @@ -67,6 +71,7 @@ public SearchIndexerKnowledgeStoreFileProjectionSelector setSourceContext(String /** * {@inheritDoc} */ + @Generated @Override public SearchIndexerKnowledgeStoreFileProjectionSelector setInputs(List inputs) { super.setInputs(inputs); @@ -76,6 +81,7 @@ public SearchIndexerKnowledgeStoreFileProjectionSelector setInputs(List { - boolean storageContainerFound = false; String storageContainer = null; String referenceKeyName = null; String generatedKeyName = null; @@ -112,7 +118,6 @@ public static SearchIndexerKnowledgeStoreFileProjectionSelector fromJson(JsonRea if ("storageContainer".equals(fieldName)) { storageContainer = reader.getString(); - storageContainerFound = true; } else if ("referenceKeyName".equals(fieldName)) { referenceKeyName = reader.getString(); } else if ("generatedKeyName".equals(fieldName)) { @@ -127,18 +132,15 @@ public static SearchIndexerKnowledgeStoreFileProjectionSelector fromJson(JsonRea reader.skipChildren(); } } - if (storageContainerFound) { - SearchIndexerKnowledgeStoreFileProjectionSelector deserializedSearchIndexerKnowledgeStoreFileProjectionSelector - = new SearchIndexerKnowledgeStoreFileProjectionSelector(storageContainer); - deserializedSearchIndexerKnowledgeStoreFileProjectionSelector.setReferenceKeyName(referenceKeyName); - deserializedSearchIndexerKnowledgeStoreFileProjectionSelector.setGeneratedKeyName(generatedKeyName); - deserializedSearchIndexerKnowledgeStoreFileProjectionSelector.setSource(source); - deserializedSearchIndexerKnowledgeStoreFileProjectionSelector.setSourceContext(sourceContext); - deserializedSearchIndexerKnowledgeStoreFileProjectionSelector.setInputs(inputs); + SearchIndexerKnowledgeStoreFileProjectionSelector deserializedSearchIndexerKnowledgeStoreFileProjectionSelector + = new SearchIndexerKnowledgeStoreFileProjectionSelector(storageContainer); + deserializedSearchIndexerKnowledgeStoreFileProjectionSelector.setReferenceKeyName(referenceKeyName); + deserializedSearchIndexerKnowledgeStoreFileProjectionSelector.setGeneratedKeyName(generatedKeyName); + deserializedSearchIndexerKnowledgeStoreFileProjectionSelector.setSource(source); + deserializedSearchIndexerKnowledgeStoreFileProjectionSelector.setSourceContext(sourceContext); + deserializedSearchIndexerKnowledgeStoreFileProjectionSelector.setInputs(inputs); - return deserializedSearchIndexerKnowledgeStoreFileProjectionSelector; - } - throw new IllegalStateException("Missing required property: storageContainer"); + return deserializedSearchIndexerKnowledgeStoreFileProjectionSelector; }); } } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/SearchIndexerKnowledgeStoreObjectProjectionSelector.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SearchIndexerKnowledgeStoreObjectProjectionSelector.java similarity index 78% rename from sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/SearchIndexerKnowledgeStoreObjectProjectionSelector.java rename to sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SearchIndexerKnowledgeStoreObjectProjectionSelector.java index 027bea52e0fd..c7690d00284f 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/SearchIndexerKnowledgeStoreObjectProjectionSelector.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SearchIndexerKnowledgeStoreObjectProjectionSelector.java @@ -1,12 +1,11 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) TypeSpec Code Generator. -package com.azure.search.documents.indexes.models; +package com.azure.search.documents.models; import com.azure.core.annotation.Fluent; +import com.azure.core.annotation.Generated; import com.azure.json.JsonReader; import com.azure.json.JsonToken; import com.azure.json.JsonWriter; @@ -24,6 +23,7 @@ public final class SearchIndexerKnowledgeStoreObjectProjectionSelector * * @param storageContainer the storageContainer value to set. */ + @Generated public SearchIndexerKnowledgeStoreObjectProjectionSelector(String storageContainer) { super(storageContainer); } @@ -31,6 +31,7 @@ public SearchIndexerKnowledgeStoreObjectProjectionSelector(String storageContain /** * {@inheritDoc} */ + @Generated @Override public SearchIndexerKnowledgeStoreObjectProjectionSelector setReferenceKeyName(String referenceKeyName) { super.setReferenceKeyName(referenceKeyName); @@ -40,6 +41,7 @@ public SearchIndexerKnowledgeStoreObjectProjectionSelector setReferenceKeyName(S /** * {@inheritDoc} */ + @Generated @Override public SearchIndexerKnowledgeStoreObjectProjectionSelector setGeneratedKeyName(String generatedKeyName) { super.setGeneratedKeyName(generatedKeyName); @@ -49,6 +51,7 @@ public SearchIndexerKnowledgeStoreObjectProjectionSelector setGeneratedKeyName(S /** * {@inheritDoc} */ + @Generated @Override public SearchIndexerKnowledgeStoreObjectProjectionSelector setSource(String source) { super.setSource(source); @@ -58,6 +61,7 @@ public SearchIndexerKnowledgeStoreObjectProjectionSelector setSource(String sour /** * {@inheritDoc} */ + @Generated @Override public SearchIndexerKnowledgeStoreObjectProjectionSelector setSourceContext(String sourceContext) { super.setSourceContext(sourceContext); @@ -67,6 +71,7 @@ public SearchIndexerKnowledgeStoreObjectProjectionSelector setSourceContext(Stri /** * {@inheritDoc} */ + @Generated @Override public SearchIndexerKnowledgeStoreObjectProjectionSelector setInputs(List inputs) { super.setInputs(inputs); @@ -76,6 +81,7 @@ public SearchIndexerKnowledgeStoreObjectProjectionSelector setInputs(List { - boolean storageContainerFound = false; String storageContainer = null; String referenceKeyName = null; String generatedKeyName = null; @@ -113,7 +119,6 @@ public static SearchIndexerKnowledgeStoreObjectProjectionSelector fromJson(JsonR if ("storageContainer".equals(fieldName)) { storageContainer = reader.getString(); - storageContainerFound = true; } else if ("referenceKeyName".equals(fieldName)) { referenceKeyName = reader.getString(); } else if ("generatedKeyName".equals(fieldName)) { @@ -128,18 +133,15 @@ public static SearchIndexerKnowledgeStoreObjectProjectionSelector fromJson(JsonR reader.skipChildren(); } } - if (storageContainerFound) { - SearchIndexerKnowledgeStoreObjectProjectionSelector deserializedSearchIndexerKnowledgeStoreObjectProjectionSelector - = new SearchIndexerKnowledgeStoreObjectProjectionSelector(storageContainer); - deserializedSearchIndexerKnowledgeStoreObjectProjectionSelector.setReferenceKeyName(referenceKeyName); - deserializedSearchIndexerKnowledgeStoreObjectProjectionSelector.setGeneratedKeyName(generatedKeyName); - deserializedSearchIndexerKnowledgeStoreObjectProjectionSelector.setSource(source); - deserializedSearchIndexerKnowledgeStoreObjectProjectionSelector.setSourceContext(sourceContext); - deserializedSearchIndexerKnowledgeStoreObjectProjectionSelector.setInputs(inputs); + SearchIndexerKnowledgeStoreObjectProjectionSelector deserializedSearchIndexerKnowledgeStoreObjectProjectionSelector + = new SearchIndexerKnowledgeStoreObjectProjectionSelector(storageContainer); + deserializedSearchIndexerKnowledgeStoreObjectProjectionSelector.setReferenceKeyName(referenceKeyName); + deserializedSearchIndexerKnowledgeStoreObjectProjectionSelector.setGeneratedKeyName(generatedKeyName); + deserializedSearchIndexerKnowledgeStoreObjectProjectionSelector.setSource(source); + deserializedSearchIndexerKnowledgeStoreObjectProjectionSelector.setSourceContext(sourceContext); + deserializedSearchIndexerKnowledgeStoreObjectProjectionSelector.setInputs(inputs); - return deserializedSearchIndexerKnowledgeStoreObjectProjectionSelector; - } - throw new IllegalStateException("Missing required property: storageContainer"); + return deserializedSearchIndexerKnowledgeStoreObjectProjectionSelector; }); } } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/SearchIndexerKnowledgeStoreParameters.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SearchIndexerKnowledgeStoreParameters.java similarity index 72% rename from sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/SearchIndexerKnowledgeStoreParameters.java rename to sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SearchIndexerKnowledgeStoreParameters.java index d4340cb0a054..1ba290004085 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/SearchIndexerKnowledgeStoreParameters.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SearchIndexerKnowledgeStoreParameters.java @@ -1,12 +1,12 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) TypeSpec Code Generator. -package com.azure.search.documents.indexes.models; +package com.azure.search.documents.models; import com.azure.core.annotation.Fluent; +import com.azure.core.annotation.Generated; +import com.azure.core.util.BinaryData; import com.azure.json.JsonReader; import com.azure.json.JsonSerializable; import com.azure.json.JsonToken; @@ -16,46 +16,54 @@ import java.util.Map; /** - * 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. + * 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. */ @Fluent public final class SearchIndexerKnowledgeStoreParameters implements JsonSerializable { /* - * Whether or not projections should synthesize a generated key name if one isn't already present. + * Whether or not projections should synthesize a generated key name if one isn't + * already present. */ + @Generated private Boolean synthesizeGeneratedKeyName; /* - * 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. + * 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. */ - private Map additionalProperties; + @Generated + private Map additionalProperties; /** * Creates an instance of SearchIndexerKnowledgeStoreParameters class. */ + @Generated public SearchIndexerKnowledgeStoreParameters() { } /** * Get the synthesizeGeneratedKeyName property: Whether or not projections should synthesize a generated key name if - * one isn't already present. + * one isn't + * already present. * * @return the synthesizeGeneratedKeyName value. */ + @Generated public Boolean isSynthesizeGeneratedKeyName() { return this.synthesizeGeneratedKeyName; } /** * Set the synthesizeGeneratedKeyName property: Whether or not projections should synthesize a generated key name if - * one isn't already present. + * one isn't + * already present. * * @param synthesizeGeneratedKeyName the synthesizeGeneratedKeyName value to set. * @return the SearchIndexerKnowledgeStoreParameters object itself. */ + @Generated public SearchIndexerKnowledgeStoreParameters setSynthesizeGeneratedKeyName(Boolean synthesizeGeneratedKeyName) { this.synthesizeGeneratedKeyName = synthesizeGeneratedKeyName; return this; @@ -63,22 +71,26 @@ public SearchIndexerKnowledgeStoreParameters setSynthesizeGeneratedKeyName(Boole /** * Get the additionalProperties property: 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. + * name is + * the name of a specific property. Each value must be of a primitive type. * * @return the additionalProperties value. */ - public Map getAdditionalProperties() { + @Generated + public Map getAdditionalProperties() { return this.additionalProperties; } /** * Set the additionalProperties property: 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. + * name is + * the name of a specific property. Each value must be of a primitive type. * * @param additionalProperties the additionalProperties value to set. * @return the SearchIndexerKnowledgeStoreParameters object itself. */ - public SearchIndexerKnowledgeStoreParameters setAdditionalProperties(Map additionalProperties) { + @Generated + public SearchIndexerKnowledgeStoreParameters setAdditionalProperties(Map additionalProperties) { this.additionalProperties = additionalProperties; return this; } @@ -86,13 +98,19 @@ public SearchIndexerKnowledgeStoreParameters setAdditionalProperties(Map additionalProperty : additionalProperties.entrySet()) { - jsonWriter.writeUntypedField(additionalProperty.getKey(), additionalProperty.getValue()); + for (Map.Entry additionalProperty : additionalProperties.entrySet()) { + jsonWriter.writeFieldName(additionalProperty.getKey()); + if (additionalProperty.getValue() == null) { + jsonWriter.writeNull(); + } else { + additionalProperty.getValue().writeTo(jsonWriter); + } } } return jsonWriter.writeEndObject(); @@ -106,11 +124,12 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { * or null if it was pointing to JSON null. * @throws IOException If an error occurs while reading the SearchIndexerKnowledgeStoreParameters. */ + @Generated public static SearchIndexerKnowledgeStoreParameters fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { SearchIndexerKnowledgeStoreParameters deserializedSearchIndexerKnowledgeStoreParameters = new SearchIndexerKnowledgeStoreParameters(); - Map additionalProperties = null; + Map additionalProperties = null; while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); @@ -123,7 +142,8 @@ public static SearchIndexerKnowledgeStoreParameters fromJson(JsonReader jsonRead additionalProperties = new LinkedHashMap<>(); } - additionalProperties.put(fieldName, reader.readUntyped()); + additionalProperties.put(fieldName, + reader.getNullable(nonNullReader -> BinaryData.fromObject(nonNullReader.readUntyped()))); } } deserializedSearchIndexerKnowledgeStoreParameters.additionalProperties = additionalProperties; diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/SearchIndexerKnowledgeStoreProjection.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SearchIndexerKnowledgeStoreProjection.java similarity index 94% rename from sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/SearchIndexerKnowledgeStoreProjection.java rename to sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SearchIndexerKnowledgeStoreProjection.java index 9410e3dce8bc..37cac5f2382b 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/SearchIndexerKnowledgeStoreProjection.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SearchIndexerKnowledgeStoreProjection.java @@ -1,12 +1,11 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) TypeSpec Code Generator. -package com.azure.search.documents.indexes.models; +package com.azure.search.documents.models; import com.azure.core.annotation.Fluent; +import com.azure.core.annotation.Generated; import com.azure.json.JsonReader; import com.azure.json.JsonSerializable; import com.azure.json.JsonToken; @@ -23,21 +22,25 @@ public final class SearchIndexerKnowledgeStoreProjection /* * Projections to Azure Table storage. */ + @Generated private List tables; /* * Projections to Azure Blob storage. */ + @Generated private List objects; /* * Projections to Azure File storage. */ + @Generated private List files; /** * Creates an instance of SearchIndexerKnowledgeStoreProjection class. */ + @Generated public SearchIndexerKnowledgeStoreProjection() { } @@ -46,6 +49,7 @@ public SearchIndexerKnowledgeStoreProjection() { * * @return the tables value. */ + @Generated public List getTables() { return this.tables; } @@ -56,6 +60,7 @@ public List getTables() { * @param tables the tables value to set. * @return the SearchIndexerKnowledgeStoreProjection object itself. */ + @Generated public SearchIndexerKnowledgeStoreProjection setTables(List tables) { this.tables = tables; @@ -67,6 +72,7 @@ public List getTables() { * * @return the objects value. */ + @Generated public List getObjects() { return this.objects; } @@ -77,6 +83,7 @@ public List getObjects() { * @param objects the objects value to set. * @return the SearchIndexerKnowledgeStoreProjection object itself. */ + @Generated public SearchIndexerKnowledgeStoreProjection setObjects(List objects) { this.objects = objects; @@ -88,6 +95,7 @@ public List getObjects() { * * @return the files value. */ + @Generated public List getFiles() { return this.files; } @@ -98,6 +106,7 @@ public List getFiles() { * @param files the files value to set. * @return the SearchIndexerKnowledgeStoreProjection object itself. */ + @Generated public SearchIndexerKnowledgeStoreProjection setFiles(List files) { this.files = files; @@ -107,6 +116,7 @@ public List getFiles() { /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); @@ -124,6 +134,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { * or null if it was pointing to JSON null. * @throws IOException If an error occurs while reading the SearchIndexerKnowledgeStoreProjection. */ + @Generated public static SearchIndexerKnowledgeStoreProjection fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { SearchIndexerKnowledgeStoreProjection deserializedSearchIndexerKnowledgeStoreProjection diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/SearchIndexerKnowledgeStoreProjectionSelector.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SearchIndexerKnowledgeStoreProjectionSelector.java similarity index 64% rename from sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/SearchIndexerKnowledgeStoreProjectionSelector.java rename to sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SearchIndexerKnowledgeStoreProjectionSelector.java index 6fd77a3c1e9d..8552ff2b8d3d 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/SearchIndexerKnowledgeStoreProjectionSelector.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SearchIndexerKnowledgeStoreProjectionSelector.java @@ -1,13 +1,14 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) TypeSpec Code Generator. -package com.azure.search.documents.indexes.models; +package com.azure.search.documents.models; import com.azure.core.annotation.Fluent; +import com.azure.core.annotation.Generated; +import com.azure.json.JsonReader; import com.azure.json.JsonSerializable; +import com.azure.json.JsonToken; import com.azure.json.JsonWriter; import java.io.IOException; import java.util.List; @@ -21,31 +22,37 @@ public class SearchIndexerKnowledgeStoreProjectionSelector /* * Name of reference key to different projection. */ + @Generated private String referenceKeyName; /* * Name of generated key to store projection under. */ + @Generated private String generatedKeyName; /* * Source data to project. */ + @Generated private String source; /* * Source context for complex projections. */ + @Generated private String sourceContext; /* * Nested inputs for complex projections. */ + @Generated private List inputs; /** * Creates an instance of SearchIndexerKnowledgeStoreProjectionSelector class. */ + @Generated public SearchIndexerKnowledgeStoreProjectionSelector() { } @@ -54,6 +61,7 @@ public SearchIndexerKnowledgeStoreProjectionSelector() { * * @return the referenceKeyName value. */ + @Generated public String getReferenceKeyName() { return this.referenceKeyName; } @@ -64,6 +72,7 @@ public String getReferenceKeyName() { * @param referenceKeyName the referenceKeyName value to set. * @return the SearchIndexerKnowledgeStoreProjectionSelector object itself. */ + @Generated public SearchIndexerKnowledgeStoreProjectionSelector setReferenceKeyName(String referenceKeyName) { this.referenceKeyName = referenceKeyName; return this; @@ -74,6 +83,7 @@ public SearchIndexerKnowledgeStoreProjectionSelector setReferenceKeyName(String * * @return the generatedKeyName value. */ + @Generated public String getGeneratedKeyName() { return this.generatedKeyName; } @@ -84,6 +94,7 @@ public String getGeneratedKeyName() { * @param generatedKeyName the generatedKeyName value to set. * @return the SearchIndexerKnowledgeStoreProjectionSelector object itself. */ + @Generated public SearchIndexerKnowledgeStoreProjectionSelector setGeneratedKeyName(String generatedKeyName) { this.generatedKeyName = generatedKeyName; return this; @@ -94,6 +105,7 @@ public SearchIndexerKnowledgeStoreProjectionSelector setGeneratedKeyName(String * * @return the source value. */ + @Generated public String getSource() { return this.source; } @@ -104,6 +116,7 @@ public String getSource() { * @param source the source value to set. * @return the SearchIndexerKnowledgeStoreProjectionSelector object itself. */ + @Generated public SearchIndexerKnowledgeStoreProjectionSelector setSource(String source) { this.source = source; return this; @@ -114,6 +127,7 @@ public SearchIndexerKnowledgeStoreProjectionSelector setSource(String source) { * * @return the sourceContext value. */ + @Generated public String getSourceContext() { return this.sourceContext; } @@ -124,6 +138,7 @@ public String getSourceContext() { * @param sourceContext the sourceContext value to set. * @return the SearchIndexerKnowledgeStoreProjectionSelector object itself. */ + @Generated public SearchIndexerKnowledgeStoreProjectionSelector setSourceContext(String sourceContext) { this.sourceContext = sourceContext; return this; @@ -134,6 +149,7 @@ public SearchIndexerKnowledgeStoreProjectionSelector setSourceContext(String sou * * @return the inputs value. */ + @Generated public List getInputs() { return this.inputs; } @@ -144,6 +160,7 @@ public List getInputs() { * @param inputs the inputs value to set. * @return the SearchIndexerKnowledgeStoreProjectionSelector object itself. */ + @Generated public SearchIndexerKnowledgeStoreProjectionSelector setInputs(List inputs) { this.inputs = inputs; return this; @@ -152,6 +169,7 @@ public SearchIndexerKnowledgeStoreProjectionSelector setInputs(List { + SearchIndexerKnowledgeStoreProjectionSelector deserializedSearchIndexerKnowledgeStoreProjectionSelector + = new SearchIndexerKnowledgeStoreProjectionSelector(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("referenceKeyName".equals(fieldName)) { + deserializedSearchIndexerKnowledgeStoreProjectionSelector.referenceKeyName = reader.getString(); + } else if ("generatedKeyName".equals(fieldName)) { + deserializedSearchIndexerKnowledgeStoreProjectionSelector.generatedKeyName = reader.getString(); + } else if ("source".equals(fieldName)) { + deserializedSearchIndexerKnowledgeStoreProjectionSelector.source = reader.getString(); + } else if ("sourceContext".equals(fieldName)) { + deserializedSearchIndexerKnowledgeStoreProjectionSelector.sourceContext = reader.getString(); + } else if ("inputs".equals(fieldName)) { + List inputs + = reader.readArray(reader1 -> InputFieldMappingEntry.fromJson(reader1)); + deserializedSearchIndexerKnowledgeStoreProjectionSelector.inputs = inputs; + } else { + reader.skipChildren(); + } + } + + return deserializedSearchIndexerKnowledgeStoreProjectionSelector; + }); + } } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/SearchIndexerKnowledgeStoreTableProjectionSelector.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SearchIndexerKnowledgeStoreTableProjectionSelector.java similarity index 79% rename from sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/SearchIndexerKnowledgeStoreTableProjectionSelector.java rename to sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SearchIndexerKnowledgeStoreTableProjectionSelector.java index 73e3ac6cef3e..9ba0f5ead24c 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/SearchIndexerKnowledgeStoreTableProjectionSelector.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SearchIndexerKnowledgeStoreTableProjectionSelector.java @@ -1,12 +1,11 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) TypeSpec Code Generator. -package com.azure.search.documents.indexes.models; +package com.azure.search.documents.models; import com.azure.core.annotation.Fluent; +import com.azure.core.annotation.Generated; import com.azure.json.JsonReader; import com.azure.json.JsonToken; import com.azure.json.JsonWriter; @@ -22,6 +21,7 @@ public final class SearchIndexerKnowledgeStoreTableProjectionSelector /* * Name of the Azure table to store projected data in. */ + @Generated private final String tableName; /** @@ -29,6 +29,7 @@ public final class SearchIndexerKnowledgeStoreTableProjectionSelector * * @param tableName the tableName value to set. */ + @Generated public SearchIndexerKnowledgeStoreTableProjectionSelector(String tableName) { this.tableName = tableName; } @@ -38,6 +39,7 @@ public SearchIndexerKnowledgeStoreTableProjectionSelector(String tableName) { * * @return the tableName value. */ + @Generated public String getTableName() { return this.tableName; } @@ -45,6 +47,7 @@ public String getTableName() { /** * {@inheritDoc} */ + @Generated @Override public SearchIndexerKnowledgeStoreTableProjectionSelector setReferenceKeyName(String referenceKeyName) { super.setReferenceKeyName(referenceKeyName); @@ -54,6 +57,7 @@ public SearchIndexerKnowledgeStoreTableProjectionSelector setReferenceKeyName(St /** * {@inheritDoc} */ + @Generated @Override public SearchIndexerKnowledgeStoreTableProjectionSelector setGeneratedKeyName(String generatedKeyName) { super.setGeneratedKeyName(generatedKeyName); @@ -63,6 +67,7 @@ public SearchIndexerKnowledgeStoreTableProjectionSelector setGeneratedKeyName(St /** * {@inheritDoc} */ + @Generated @Override public SearchIndexerKnowledgeStoreTableProjectionSelector setSource(String source) { super.setSource(source); @@ -72,6 +77,7 @@ public SearchIndexerKnowledgeStoreTableProjectionSelector setSource(String sourc /** * {@inheritDoc} */ + @Generated @Override public SearchIndexerKnowledgeStoreTableProjectionSelector setSourceContext(String sourceContext) { super.setSourceContext(sourceContext); @@ -81,6 +87,7 @@ public SearchIndexerKnowledgeStoreTableProjectionSelector setSourceContext(Strin /** * {@inheritDoc} */ + @Generated @Override public SearchIndexerKnowledgeStoreTableProjectionSelector setInputs(List inputs) { super.setInputs(inputs); @@ -90,6 +97,7 @@ public SearchIndexerKnowledgeStoreTableProjectionSelector setInputs(List { @@ -119,7 +128,6 @@ public static SearchIndexerKnowledgeStoreTableProjectionSelector fromJson(JsonRe String source = null; String sourceContext = null; List inputs = null; - boolean tableNameFound = false; String tableName = null; while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); @@ -137,23 +145,19 @@ public static SearchIndexerKnowledgeStoreTableProjectionSelector fromJson(JsonRe inputs = reader.readArray(reader1 -> InputFieldMappingEntry.fromJson(reader1)); } else if ("tableName".equals(fieldName)) { tableName = reader.getString(); - tableNameFound = true; } else { reader.skipChildren(); } } - if (tableNameFound) { - SearchIndexerKnowledgeStoreTableProjectionSelector deserializedSearchIndexerKnowledgeStoreTableProjectionSelector - = new SearchIndexerKnowledgeStoreTableProjectionSelector(tableName); - deserializedSearchIndexerKnowledgeStoreTableProjectionSelector.setReferenceKeyName(referenceKeyName); - deserializedSearchIndexerKnowledgeStoreTableProjectionSelector.setGeneratedKeyName(generatedKeyName); - deserializedSearchIndexerKnowledgeStoreTableProjectionSelector.setSource(source); - deserializedSearchIndexerKnowledgeStoreTableProjectionSelector.setSourceContext(sourceContext); - deserializedSearchIndexerKnowledgeStoreTableProjectionSelector.setInputs(inputs); + SearchIndexerKnowledgeStoreTableProjectionSelector deserializedSearchIndexerKnowledgeStoreTableProjectionSelector + = new SearchIndexerKnowledgeStoreTableProjectionSelector(tableName); + deserializedSearchIndexerKnowledgeStoreTableProjectionSelector.setReferenceKeyName(referenceKeyName); + deserializedSearchIndexerKnowledgeStoreTableProjectionSelector.setGeneratedKeyName(generatedKeyName); + deserializedSearchIndexerKnowledgeStoreTableProjectionSelector.setSource(source); + deserializedSearchIndexerKnowledgeStoreTableProjectionSelector.setSourceContext(sourceContext); + deserializedSearchIndexerKnowledgeStoreTableProjectionSelector.setInputs(inputs); - return deserializedSearchIndexerKnowledgeStoreTableProjectionSelector; - } - throw new IllegalStateException("Missing required property: tableName"); + return deserializedSearchIndexerKnowledgeStoreTableProjectionSelector; }); } } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/SearchIndexerLimits.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SearchIndexerLimits.java similarity index 79% rename from sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/SearchIndexerLimits.java rename to sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SearchIndexerLimits.java index 02b92d0a0206..4dc00636252d 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/SearchIndexerLimits.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SearchIndexerLimits.java @@ -1,12 +1,12 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) TypeSpec Code Generator. -package com.azure.search.documents.indexes.models; +package com.azure.search.documents.models; +import com.azure.core.annotation.Generated; import com.azure.core.annotation.Immutable; +import com.azure.core.util.CoreUtils; import com.azure.json.JsonReader; import com.azure.json.JsonSerializable; import com.azure.json.JsonToken; @@ -15,29 +15,35 @@ import java.time.Duration; /** - * The SearchIndexerLimits model. + * Represents the limits that can be applied to an indexer. */ @Immutable public final class SearchIndexerLimits implements JsonSerializable { /* * The maximum duration that the indexer is permitted to run for one execution. */ + @Generated private Duration maxRunTime; /* - * The maximum size of a document, in bytes, which will be considered valid for indexing. + * The maximum size of a document, in bytes, which will be considered valid for + * indexing. */ + @Generated private Long maxDocumentExtractionSize; /* - * The maximum number of characters that will be extracted from a document picked up for indexing. + * The maximum number of characters that will be extracted from a document picked + * up for indexing. */ + @Generated private Long maxDocumentContentCharactersToExtract; /** * Creates an instance of SearchIndexerLimits class. */ - public SearchIndexerLimits() { + @Generated + private SearchIndexerLimits() { } /** @@ -45,26 +51,31 @@ public SearchIndexerLimits() { * * @return the maxRunTime value. */ + @Generated public Duration getMaxRunTime() { return this.maxRunTime; } /** * Get the maxDocumentExtractionSize property: The maximum size of a document, in bytes, which will be considered - * valid for indexing. + * valid for + * indexing. * * @return the maxDocumentExtractionSize value. */ + @Generated public Long getMaxDocumentExtractionSize() { return this.maxDocumentExtractionSize; } /** * Get the maxDocumentContentCharactersToExtract property: The maximum number of characters that will be extracted - * from a document picked up for indexing. + * from a document picked + * up for indexing. * * @return the maxDocumentContentCharactersToExtract value. */ + @Generated public Long getMaxDocumentContentCharactersToExtract() { return this.maxDocumentContentCharactersToExtract; } @@ -72,9 +83,14 @@ public Long getMaxDocumentContentCharactersToExtract() { /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); + jsonWriter.writeStringField("maxRunTime", CoreUtils.durationToStringWithDays(this.maxRunTime)); + jsonWriter.writeNumberField("maxDocumentExtractionSize", this.maxDocumentExtractionSize); + jsonWriter.writeNumberField("maxDocumentContentCharactersToExtract", + this.maxDocumentContentCharactersToExtract); return jsonWriter.writeEndObject(); } @@ -86,6 +102,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { * pointing to JSON null. * @throws IOException If an error occurs while reading the SearchIndexerLimits. */ + @Generated public static SearchIndexerLimits fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { SearchIndexerLimits deserializedSearchIndexerLimits = new SearchIndexerLimits(); diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/SearchIndexerSkill.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SearchIndexerSkill.java similarity index 76% rename from sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/SearchIndexerSkill.java rename to sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SearchIndexerSkill.java index bf65c2fe7c7b..ea9fa61c69c2 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/SearchIndexerSkill.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SearchIndexerSkill.java @@ -1,22 +1,16 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) TypeSpec Code Generator. -package com.azure.search.documents.indexes.models; +package com.azure.search.documents.models; import com.azure.core.annotation.Fluent; +import com.azure.core.annotation.Generated; import com.azure.json.JsonReader; import com.azure.json.JsonSerializable; import com.azure.json.JsonToken; import com.azure.json.JsonWriter; -import com.azure.search.documents.indexes.implementation.models.EntityRecognitionSkillV1; -import com.azure.search.documents.indexes.implementation.models.EntityRecognitionSkillV3; -import com.azure.search.documents.indexes.implementation.models.SentimentSkillV1; -import com.azure.search.documents.indexes.implementation.models.SentimentSkillV3; import java.io.IOException; -import java.util.ArrayList; import java.util.List; /** @@ -25,36 +19,46 @@ @Fluent public class SearchIndexerSkill implements JsonSerializable { /* - * A URI fragment specifying the type of skill. + * The discriminator for derived types. */ + @Generated private String odataType = "SearchIndexerSkill"; /* - * 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 '#'. + * 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 '#'. */ + @Generated private String name; /* - * The description of the skill which describes the inputs, outputs, and usage of the skill. + * The description of the skill which describes the inputs, outputs, and usage of + * the skill. */ + @Generated private String description; /* - * 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. + * 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. */ + @Generated private String context; /* - * Inputs of the skills could be a column in the source data set, or the output of an upstream skill. + * Inputs of the skills could be a column in the source data set, or the output of + * an upstream skill. */ + @Generated private final List inputs; /* - * 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. + * 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. */ + @Generated private final List outputs; /** @@ -63,104 +67,116 @@ public class SearchIndexerSkill implements JsonSerializable * @param inputs the inputs value to set. * @param outputs the outputs value to set. */ + @Generated public SearchIndexerSkill(List inputs, List outputs) { this.inputs = inputs; this.outputs = outputs; } /** - * Get the odataType property: A URI fragment specifying the type of skill. + * Get the odataType property: The discriminator for derived types. * * @return the odataType value. */ + @Generated public String getOdataType() { return this.odataType; } /** - * Get the name property: 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 - * '#'. + * Get the name property: 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 '#'. * * @return the name value. */ + @Generated public String getName() { return this.name; } /** - * Set the name property: 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 - * '#'. + * Set the name property: 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 '#'. * * @param name the name value to set. * @return the SearchIndexerSkill object itself. */ + @Generated public SearchIndexerSkill setName(String name) { this.name = name; return this; } /** - * Get the description property: The description of the skill which describes the inputs, outputs, and usage of the - * skill. + * Get the description property: The description of the skill which describes the inputs, outputs, and usage of + * the skill. * * @return the description value. */ + @Generated public String getDescription() { return this.description; } /** - * Set the description property: The description of the skill which describes the inputs, outputs, and usage of the - * skill. + * Set the description property: The description of the skill which describes the inputs, outputs, and usage of + * the skill. * * @param description the description value to set. * @return the SearchIndexerSkill object itself. */ + @Generated public SearchIndexerSkill setDescription(String description) { this.description = description; return this; } /** - * Get the context property: 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. + * Get the context property: 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. * * @return the context value. */ + @Generated public String getContext() { return this.context; } /** - * Set the context property: 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. + * Set the context property: 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. * * @param context the context value to set. * @return the SearchIndexerSkill object itself. */ + @Generated public SearchIndexerSkill setContext(String context) { this.context = context; return this; } /** - * Get the inputs property: Inputs of the skills could be a column in the source data set, or the output of an - * upstream skill. + * Get the inputs property: Inputs of the skills could be a column in the source data set, or the output of + * an upstream skill. * * @return the inputs value. */ + @Generated public List getInputs() { return this.inputs; } /** - * Get the outputs property: 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. + * Get the outputs property: 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. * * @return the outputs value. */ + @Generated public List getOutputs() { return this.outputs; } @@ -168,6 +184,7 @@ public List getOutputs() { /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); @@ -189,6 +206,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { * @throws IllegalStateException If the deserialized JSON object was missing any required properties. * @throws IOException If an error occurs while reading the SearchIndexerSkill. */ + @Generated public static SearchIndexerSkill fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { String discriminatorValue = null; @@ -219,12 +237,18 @@ public static SearchIndexerSkill fromJson(JsonReader jsonReader) throws IOExcept return ShaperSkill.fromJson(readerToUse.reset()); } else if ("#Microsoft.Skills.Text.MergeSkill".equals(discriminatorValue)) { return MergeSkill.fromJson(readerToUse.reset()); + } else if ("#Microsoft.Skills.Text.EntityRecognitionSkill".equals(discriminatorValue)) { + return EntityRecognitionSkill.fromJson(readerToUse.reset()); + } else if ("#Microsoft.Skills.Text.SentimentSkill".equals(discriminatorValue)) { + return SentimentSkill.fromJson(readerToUse.reset()); } else if ("#Microsoft.Skills.Text.V3.SentimentSkill".equals(discriminatorValue)) { return SentimentSkillV3.fromJson(readerToUse.reset()); } else if ("#Microsoft.Skills.Text.V3.EntityLinkingSkill".equals(discriminatorValue)) { return EntityLinkingSkill.fromJson(readerToUse.reset()); } else if ("#Microsoft.Skills.Text.V3.EntityRecognitionSkill".equals(discriminatorValue)) { return EntityRecognitionSkillV3.fromJson(readerToUse.reset()); + } else if ("#Microsoft.Skills.Text.PIIDetectionSkill".equals(discriminatorValue)) { + return PIIDetectionSkill.fromJson(readerToUse.reset()); } else if ("#Microsoft.Skills.Text.SplitSkill".equals(discriminatorValue)) { return SplitSkill.fromJson(readerToUse.reset()); } else if ("#Microsoft.Skills.Text.CustomEntityLookupSkill".equals(discriminatorValue)) { @@ -243,12 +267,6 @@ public static SearchIndexerSkill fromJson(JsonReader jsonReader) throws IOExcept return AzureOpenAIEmbeddingSkill.fromJson(readerToUse.reset()); } else if ("#Microsoft.Skills.Vision.VectorizeSkill".equals(discriminatorValue)) { return VisionVectorizeSkill.fromJson(readerToUse.reset()); - } else if ("#Microsoft.Skills.Text.PIIDetectionSkill".equals(discriminatorValue)) { - return PiiDetectionSkill.fromJson(readerToUse.reset()); - } else if ("#Microsoft.Skills.Text.EntityRecognitionSkill".equals(discriminatorValue)) { - return EntityRecognitionSkillV1.fromJson(readerToUse.reset()); - } else if ("#Microsoft.Skills.Text.SentimentSkill".equals(discriminatorValue)) { - return SentimentSkillV1.fromJson(readerToUse.reset()); } else { return fromJsonKnownDiscriminator(readerToUse.reset()); } @@ -256,11 +274,10 @@ public static SearchIndexerSkill fromJson(JsonReader jsonReader) throws IOExcept }); } + @Generated static SearchIndexerSkill fromJsonKnownDiscriminator(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { - boolean inputsFound = false; List inputs = null; - boolean outputsFound = false; List outputs = null; String odataType = null; String name = null; @@ -272,10 +289,8 @@ static SearchIndexerSkill fromJsonKnownDiscriminator(JsonReader jsonReader) thro if ("inputs".equals(fieldName)) { inputs = reader.readArray(reader1 -> InputFieldMappingEntry.fromJson(reader1)); - inputsFound = true; } else if ("outputs".equals(fieldName)) { outputs = reader.readArray(reader1 -> OutputFieldMappingEntry.fromJson(reader1)); - outputsFound = true; } else if ("@odata.type".equals(fieldName)) { odataType = reader.getString(); } else if ("name".equals(fieldName)) { @@ -288,25 +303,13 @@ static SearchIndexerSkill fromJsonKnownDiscriminator(JsonReader jsonReader) thro reader.skipChildren(); } } - if (inputsFound && outputsFound) { - SearchIndexerSkill deserializedSearchIndexerSkill = new SearchIndexerSkill(inputs, outputs); - deserializedSearchIndexerSkill.odataType = odataType; - deserializedSearchIndexerSkill.name = name; - deserializedSearchIndexerSkill.description = description; - deserializedSearchIndexerSkill.context = context; - - return deserializedSearchIndexerSkill; - } - List missingProperties = new ArrayList<>(); - if (!inputsFound) { - missingProperties.add("inputs"); - } - if (!outputsFound) { - missingProperties.add("outputs"); - } + SearchIndexerSkill deserializedSearchIndexerSkill = new SearchIndexerSkill(inputs, outputs); + deserializedSearchIndexerSkill.odataType = odataType; + deserializedSearchIndexerSkill.name = name; + deserializedSearchIndexerSkill.description = description; + deserializedSearchIndexerSkill.context = context; - throw new IllegalStateException( - "Missing required property/properties: " + String.join(", ", missingProperties)); + return deserializedSearchIndexerSkill; }); } } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/SearchIndexerSkillset.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SearchIndexerSkillset.java similarity index 67% rename from sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/SearchIndexerSkillset.java rename to sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SearchIndexerSkillset.java index 7b0abe477e86..8fbf42fc28a5 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/SearchIndexerSkillset.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SearchIndexerSkillset.java @@ -1,17 +1,16 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. -package com.azure.search.documents.indexes.models; +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.search.documents.models; import com.azure.core.annotation.Fluent; +import com.azure.core.annotation.Generated; import com.azure.json.JsonReader; import com.azure.json.JsonSerializable; import com.azure.json.JsonToken; import com.azure.json.JsonWriter; import java.io.IOException; -import java.util.Arrays; import java.util.List; /** @@ -19,86 +18,103 @@ */ @Fluent public final class SearchIndexerSkillset implements JsonSerializable { - /* * The name of the skillset. */ + @Generated private final String name; /* * The description of the skillset. */ + @Generated private String description; /* * A list of skills in the skillset. */ - private List skills; + @Generated + private final List skills; /* * Details about the Azure AI service to be used when running skills. */ + @Generated private CognitiveServicesAccount cognitiveServicesAccount; /* - * Definition of additional projections to Azure blob, table, or files, of enriched data. + * Definition of additional projections to Azure blob, table, or files, of + * enriched data. */ + @Generated private SearchIndexerKnowledgeStore knowledgeStore; /* * Definition of additional projections to secondary search index(es). */ + @Generated private SearchIndexerIndexProjection indexProjection; /* * The ETag of the skillset. */ + @Generated private String eTag; /* - * 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. + * 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. */ + @Generated private SearchResourceEncryptionKey encryptionKey; /** * Creates an instance of SearchIndexerSkillset class. - * + * * @param name the name value to set. + * @param skills the skills value to set. */ - public SearchIndexerSkillset(String name) { + @Generated + public SearchIndexerSkillset(String name, List skills) { this.name = name; + this.skills = skills; } /** * Get the name property: The name of the skillset. - * + * * @return the name value. */ + @Generated public String getName() { return this.name; } /** * Get the description property: The description of the skillset. - * + * * @return the description value. */ + @Generated public String getDescription() { return this.description; } /** * Set the description property: The description of the skillset. - * + * * @param description the description value to set. * @return the SearchIndexerSkillset object itself. */ + @Generated public SearchIndexerSkillset setDescription(String description) { this.description = description; return this; @@ -106,61 +122,55 @@ public SearchIndexerSkillset setDescription(String description) { /** * Get the skills property: A list of skills in the skillset. - * + * * @return the skills value. */ + @Generated public List getSkills() { return this.skills; } - /** - * Set the skills property: A list of skills in the skillset. - * - * @param skills the skills value to set. - * @return the SearchIndexerSkillset object itself. - */ - public SearchIndexerSkillset setSkills(List skills) { - this.skills = skills; - return this; - } - /** * Get the cognitiveServicesAccount property: Details about the Azure AI service to be used when running skills. - * + * * @return the cognitiveServicesAccount value. */ + @Generated public CognitiveServicesAccount getCognitiveServicesAccount() { return this.cognitiveServicesAccount; } /** * Set the cognitiveServicesAccount property: Details about the Azure AI service to be used when running skills. - * + * * @param cognitiveServicesAccount the cognitiveServicesAccount value to set. * @return the SearchIndexerSkillset object itself. */ + @Generated public SearchIndexerSkillset setCognitiveServicesAccount(CognitiveServicesAccount cognitiveServicesAccount) { this.cognitiveServicesAccount = cognitiveServicesAccount; return this; } /** - * Get the knowledgeStore property: Definition of additional projections to Azure blob, table, or files, of enriched - * data. - * + * Get the knowledgeStore property: Definition of additional projections to Azure blob, table, or files, of + * enriched data. + * * @return the knowledgeStore value. */ + @Generated public SearchIndexerKnowledgeStore getKnowledgeStore() { return this.knowledgeStore; } /** - * Set the knowledgeStore property: Definition of additional projections to Azure blob, table, or files, of enriched - * data. - * + * Set the knowledgeStore property: Definition of additional projections to Azure blob, table, or files, of + * enriched data. + * * @param knowledgeStore the knowledgeStore value to set. * @return the SearchIndexerSkillset object itself. */ + @Generated public SearchIndexerSkillset setKnowledgeStore(SearchIndexerKnowledgeStore knowledgeStore) { this.knowledgeStore = knowledgeStore; return this; @@ -168,19 +178,21 @@ public SearchIndexerSkillset setKnowledgeStore(SearchIndexerKnowledgeStore knowl /** * Get the indexProjection property: Definition of additional projections to secondary search index(es). - * + * * @return the indexProjection value. */ + @Generated public SearchIndexerIndexProjection getIndexProjection() { return this.indexProjection; } /** * Set the indexProjection property: Definition of additional projections to secondary search index(es). - * + * * @param indexProjection the indexProjection value to set. * @return the SearchIndexerSkillset object itself. */ + @Generated public SearchIndexerSkillset setIndexProjection(SearchIndexerIndexProjection indexProjection) { this.indexProjection = indexProjection; return this; @@ -188,19 +200,21 @@ public SearchIndexerSkillset setIndexProjection(SearchIndexerIndexProjection ind /** * Get the eTag property: The ETag of the skillset. - * + * * @return the eTag value. */ + @Generated public String getETag() { return this.eTag; } /** * Set the eTag property: The ETag of the skillset. - * + * * @param eTag the eTag value to set. * @return the SearchIndexerSkillset object itself. */ + @Generated public SearchIndexerSkillset setETag(String eTag) { this.eTag = eTag; return this; @@ -208,31 +222,39 @@ public SearchIndexerSkillset setETag(String eTag) { /** * Get the encryptionKey property: 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. - * + * 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. + * * @return the encryptionKey value. */ + @Generated public SearchResourceEncryptionKey getEncryptionKey() { return this.encryptionKey; } /** * Set the encryptionKey property: 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. - * + * 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. + * * @param encryptionKey the encryptionKey value to set. * @return the SearchIndexerSkillset object itself. */ + @Generated public SearchIndexerSkillset setEncryptionKey(SearchResourceEncryptionKey encryptionKey) { this.encryptionKey = encryptionKey; return this; @@ -241,12 +263,13 @@ public SearchIndexerSkillset setEncryptionKey(SearchResourceEncryptionKey encryp /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); jsonWriter.writeStringField("name", this.name); - jsonWriter.writeStringField("description", this.description); jsonWriter.writeArrayField("skills", this.skills, (writer, element) -> writer.writeJson(element)); + jsonWriter.writeStringField("description", this.description); jsonWriter.writeJsonField("cognitiveServices", this.cognitiveServicesAccount); jsonWriter.writeJsonField("knowledgeStore", this.knowledgeStore); jsonWriter.writeJsonField("indexProjections", this.indexProjection); @@ -257,19 +280,19 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of SearchIndexerSkillset from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of SearchIndexerSkillset if the JsonReader was pointing to an instance of it, or null if it * was pointing to JSON null. * @throws IllegalStateException If the deserialized JSON object was missing any required properties. * @throws IOException If an error occurs while reading the SearchIndexerSkillset. */ + @Generated public static SearchIndexerSkillset fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { - boolean nameFound = false; String name = null; - String description = null; List skills = null; + String description = null; CognitiveServicesAccount cognitiveServicesAccount = null; SearchIndexerKnowledgeStore knowledgeStore = null; SearchIndexerIndexProjection indexProjection = null; @@ -278,13 +301,13 @@ public static SearchIndexerSkillset fromJson(JsonReader jsonReader) throws IOExc while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); + if ("name".equals(fieldName)) { name = reader.getString(); - nameFound = true; - } else if ("description".equals(fieldName)) { - description = reader.getString(); } else if ("skills".equals(fieldName)) { skills = reader.readArray(reader1 -> SearchIndexerSkill.fromJson(reader1)); + } else if ("description".equals(fieldName)) { + description = reader.getString(); } else if ("cognitiveServices".equals(fieldName)) { cognitiveServicesAccount = CognitiveServicesAccount.fromJson(reader); } else if ("knowledgeStore".equals(fieldName)) { @@ -299,42 +322,15 @@ public static SearchIndexerSkillset fromJson(JsonReader jsonReader) throws IOExc reader.skipChildren(); } } - if (nameFound) { - SearchIndexerSkillset deserializedSearchIndexerSkillset = new SearchIndexerSkillset(name); - deserializedSearchIndexerSkillset.description = description; - deserializedSearchIndexerSkillset.skills = skills; - deserializedSearchIndexerSkillset.cognitiveServicesAccount = cognitiveServicesAccount; - deserializedSearchIndexerSkillset.knowledgeStore = knowledgeStore; - deserializedSearchIndexerSkillset.indexProjection = indexProjection; - deserializedSearchIndexerSkillset.eTag = eTag; - deserializedSearchIndexerSkillset.encryptionKey = encryptionKey; - return deserializedSearchIndexerSkillset; - } - throw new IllegalStateException("Missing required property: name"); - }); - } + SearchIndexerSkillset deserializedSearchIndexerSkillset = new SearchIndexerSkillset(name, skills); + deserializedSearchIndexerSkillset.description = description; + deserializedSearchIndexerSkillset.cognitiveServicesAccount = cognitiveServicesAccount; + deserializedSearchIndexerSkillset.knowledgeStore = knowledgeStore; + deserializedSearchIndexerSkillset.indexProjection = indexProjection; + deserializedSearchIndexerSkillset.eTag = eTag; + deserializedSearchIndexerSkillset.encryptionKey = encryptionKey; - /** - * /** - * Creates an instance of SearchIndexerSkillset class. - * - * @param name The name of the skillset. - * @param skills The skills in the skillset. - * / - */ - public SearchIndexerSkillset(String name, List skills) { - this(name); - this.skills = skills; - } - - /** - * Set the skills property: A list of skills in the skillset. - * - * @param skills the skills value to set. - * @return the SearchIndexerSkillset object itself. - */ - public SearchIndexerSkillset setSkills(SearchIndexerSkill... skills) { - this.skills = (skills == null) ? null : Arrays.asList(skills); - return this; + return deserializedSearchIndexerSkillset; + }); } } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/SearchIndexerStatus.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SearchIndexerStatus.java similarity index 74% rename from sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/SearchIndexerStatus.java rename to sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SearchIndexerStatus.java index 70d70fb08e08..572f6f1bed14 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/SearchIndexerStatus.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SearchIndexerStatus.java @@ -1,18 +1,16 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) TypeSpec Code Generator. -package com.azure.search.documents.indexes.models; +package com.azure.search.documents.models; +import com.azure.core.annotation.Generated; import com.azure.core.annotation.Immutable; import com.azure.json.JsonReader; import com.azure.json.JsonSerializable; import com.azure.json.JsonToken; import com.azure.json.JsonWriter; import java.io.IOException; -import java.util.ArrayList; import java.util.List; /** @@ -23,21 +21,25 @@ public final class SearchIndexerStatus implements JsonSerializable executionHistory; /* * The execution limits for the indexer. */ + @Generated private final SearchIndexerLimits limits; /** @@ -47,7 +49,8 @@ public final class SearchIndexerStatus implements JsonSerializable executionHistory, + @Generated + private SearchIndexerStatus(IndexerStatus status, List executionHistory, SearchIndexerLimits limits) { this.status = status; this.executionHistory = executionHistory; @@ -59,6 +62,7 @@ public SearchIndexerStatus(IndexerStatus status, List ex * * @return the status value. */ + @Generated public IndexerStatus getStatus() { return this.status; } @@ -68,6 +72,7 @@ public IndexerStatus getStatus() { * * @return the lastResult value. */ + @Generated public IndexerExecutionResult getLastResult() { return this.lastResult; } @@ -78,6 +83,7 @@ public IndexerExecutionResult getLastResult() { * * @return the executionHistory value. */ + @Generated public List getExecutionHistory() { return this.executionHistory; } @@ -87,6 +93,7 @@ public List getExecutionHistory() { * * @return the limits value. */ + @Generated public SearchIndexerLimits getLimits() { return this.limits; } @@ -94,9 +101,15 @@ public SearchIndexerLimits getLimits() { /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); + jsonWriter.writeStringField("status", this.status == null ? null : this.status.toString()); + jsonWriter.writeArrayField("executionHistory", this.executionHistory, + (writer, element) -> writer.writeJson(element)); + jsonWriter.writeJsonField("limits", this.limits); + jsonWriter.writeJsonField("lastResult", this.lastResult); return jsonWriter.writeEndObject(); } @@ -109,13 +122,11 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { * @throws IllegalStateException If the deserialized JSON object was missing any required properties. * @throws IOException If an error occurs while reading the SearchIndexerStatus. */ + @Generated public static SearchIndexerStatus fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { - boolean statusFound = false; IndexerStatus status = null; - boolean executionHistoryFound = false; List executionHistory = null; - boolean limitsFound = false; SearchIndexerLimits limits = null; IndexerExecutionResult lastResult = null; while (reader.nextToken() != JsonToken.END_OBJECT) { @@ -124,39 +135,21 @@ public static SearchIndexerStatus fromJson(JsonReader jsonReader) throws IOExcep if ("status".equals(fieldName)) { status = IndexerStatus.fromString(reader.getString()); - statusFound = true; } else if ("executionHistory".equals(fieldName)) { executionHistory = reader.readArray(reader1 -> IndexerExecutionResult.fromJson(reader1)); - executionHistoryFound = true; } else if ("limits".equals(fieldName)) { limits = SearchIndexerLimits.fromJson(reader); - limitsFound = true; } else if ("lastResult".equals(fieldName)) { lastResult = IndexerExecutionResult.fromJson(reader); } else { reader.skipChildren(); } } - if (statusFound && executionHistoryFound && limitsFound) { - SearchIndexerStatus deserializedSearchIndexerStatus - = new SearchIndexerStatus(status, executionHistory, limits); - deserializedSearchIndexerStatus.lastResult = lastResult; + SearchIndexerStatus deserializedSearchIndexerStatus + = new SearchIndexerStatus(status, executionHistory, limits); + deserializedSearchIndexerStatus.lastResult = lastResult; - return deserializedSearchIndexerStatus; - } - List missingProperties = new ArrayList<>(); - if (!statusFound) { - missingProperties.add("status"); - } - if (!executionHistoryFound) { - missingProperties.add("executionHistory"); - } - if (!limitsFound) { - missingProperties.add("limits"); - } - - throw new IllegalStateException( - "Missing required property/properties: " + String.join(", ", missingProperties)); + return deserializedSearchIndexerStatus; }); } } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/SearchIndexerWarning.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SearchIndexerWarning.java similarity index 72% rename from sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/SearchIndexerWarning.java rename to sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SearchIndexerWarning.java index 979233e6c340..e6dd57ff2f76 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/SearchIndexerWarning.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SearchIndexerWarning.java @@ -1,11 +1,10 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) TypeSpec Code Generator. -package com.azure.search.documents.indexes.models; +package com.azure.search.documents.models; +import com.azure.core.annotation.Generated; import com.azure.core.annotation.Immutable; import com.azure.json.JsonReader; import com.azure.json.JsonSerializable; @@ -21,28 +20,35 @@ public final class SearchIndexerWarning implements JsonSerializable { - boolean messageFound = false; String message = null; String key = null; String name = null; @@ -134,7 +153,6 @@ public static SearchIndexerWarning fromJson(JsonReader jsonReader) throws IOExce if ("message".equals(fieldName)) { message = reader.getString(); - messageFound = true; } else if ("key".equals(fieldName)) { key = reader.getString(); } else if ("name".equals(fieldName)) { @@ -147,16 +165,13 @@ public static SearchIndexerWarning fromJson(JsonReader jsonReader) throws IOExce reader.skipChildren(); } } - if (messageFound) { - SearchIndexerWarning deserializedSearchIndexerWarning = new SearchIndexerWarning(message); - deserializedSearchIndexerWarning.key = key; - deserializedSearchIndexerWarning.name = name; - deserializedSearchIndexerWarning.details = details; - deserializedSearchIndexerWarning.documentationLink = documentationLink; - - return deserializedSearchIndexerWarning; - } - throw new IllegalStateException("Missing required property: message"); + SearchIndexerWarning deserializedSearchIndexerWarning = new SearchIndexerWarning(message); + deserializedSearchIndexerWarning.key = key; + deserializedSearchIndexerWarning.name = name; + deserializedSearchIndexerWarning.details = details; + deserializedSearchIndexerWarning.documentationLink = documentationLink; + + return deserializedSearchIndexerWarning; }); } } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SearchMode.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SearchMode.java index 992764eb1ec7..fdd4701e581f 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SearchMode.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SearchMode.java @@ -1,58 +1,60 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.search.documents.models; +import com.azure.core.annotation.Generated; +import com.azure.core.util.ExpandableStringEnum; +import java.util.Collection; + /** - * Specifies whether any or all of the search terms must be matched in order to count the document as a match. + * Specifies whether any or all of the search terms must be matched in order to + * count the document as a match. */ -public enum SearchMode { +public final class SearchMode extends ExpandableStringEnum { /** - * Any of the search terms must be matched in order to count the document as a match. + * Any of the search terms must be matched in order to count the document as a + * match. */ - ANY("any"), + @Generated + public static final SearchMode ANY = fromString("any"); /** - * All of the search terms must be matched in order to count the document as a match. + * All of the search terms must be matched in order to count the document as a + * match. */ - ALL("all"); + @Generated + public static final SearchMode ALL = fromString("all"); /** - * The actual serialized value for a SearchMode instance. + * Creates a new instance of SearchMode value. + * + * @deprecated Use the {@link #fromString(String)} factory method. */ - private final String value; - - SearchMode(String value) { - this.value = value; + @Generated + @Deprecated + public SearchMode() { } /** - * Parses a serialized value to a SearchMode instance. + * Creates or finds a SearchMode from its string representation. * - * @param value the serialized value to parse. - * @return the parsed SearchMode object, or null if unable to parse. + * @param name a name to look for. + * @return the corresponding SearchMode. */ - public static SearchMode fromString(String value) { - if (value == null) { - return null; - } - SearchMode[] items = SearchMode.values(); - for (SearchMode item : items) { - if (item.toString().equalsIgnoreCase(value)) { - return item; - } - } - return null; + @Generated + public static SearchMode fromString(String name) { + return fromString(name, SearchMode.class); } /** - * {@inheritDoc} + * Gets known SearchMode values. + * + * @return known SearchMode values. */ - @Override - public String toString() { - return this.value; + @Generated + public static Collection values() { + return values(SearchMode.class); } } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SearchOptions.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SearchOptions.java deleted file mode 100644 index 98cae7068f55..000000000000 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SearchOptions.java +++ /dev/null @@ -1,672 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.search.documents.models; - -import com.azure.core.annotation.Fluent; - -import java.util.Arrays; -import java.util.List; - -/** - * Additional parameters for searchGet operation. - */ -@Fluent -public final class SearchOptions { - /* - * 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. - */ - private Boolean includeTotalCount; - - /* - * 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. - */ - private List facets; - - /* - * The OData $filter expression to apply to the search query. - */ - private String filter; - - /* - * The list of field names to use for hit highlights. Only searchable fields can be used for hit highlighting. - */ - private List highlightFields; - - /* - * A string tag that is appended to hit highlights. Must be set with highlightPreTag. Default is </em>. - */ - private String highlightPostTag; - - /* - * A string tag that is prepended to hit highlights. Must be set with highlightPostTag. Default is <em>. - */ - private String highlightPreTag; - - /* - * 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. - */ - private Double minimumCoverage; - - /* - * 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. - */ - private List orderBy; - - /* - * A value that specifies the syntax of the search query. The default is 'simple'. Use 'full' if your query uses the - * Lucene query syntax. - */ - private QueryType queryType; - - /* - * 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). - */ - private List scoringParameters; - - /* - * The name of a scoring profile to evaluate match scores for matching documents in order to sort the results. - */ - private String scoringProfile; - - /* - * 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. - */ - private List searchFields; - - /* - * A value that specifies whether any or all of the search terms must be matched in order to count the document as a - * match. - */ - private SearchMode searchMode; - - /* - * 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. - */ - private ScoringStatistics scoringStatistics; - - /* - * 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. - */ - private String sessionId; - - /* - * The list of fields to retrieve. If unspecified, all fields marked as retrievable in the schema are included. - */ - private List select; - - /* - * 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. - */ - private Integer skip; - - /* - * 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. - */ - private Integer top; - - /* - * Enables a debugging tool that can be used to further explore your search results. - */ - private QueryDebugMode debug; - - /* - * The language of the query. - */ - private QueryLanguage queryLanguage; - - /* - * Improve search recall by spell-correcting individual search query terms. - */ - private QuerySpellerType speller; - - private SemanticSearchOptions semanticSearchOptions; - private VectorSearchOptions vectorSearchOptions; - - /** - * Creates an instance of {@link SearchOptions}. - */ - public SearchOptions() { - } - - /** - * Get the includeTotalCount property: 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. - * - * @return the includeTotalCount value. - */ - public Boolean isTotalCountIncluded() { - return this.includeTotalCount; - } - - /** - * Set the includeTotalCount property: 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. - * - * @param includeTotalCount the includeTotalCount value to set. - * @return the SearchOptions object itself. - */ - public SearchOptions setIncludeTotalCount(Boolean includeTotalCount) { - this.includeTotalCount = includeTotalCount; - return this; - } - - /** - * Get the facets property: 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. - * - * @return the facets value. - */ - public List getFacets() { - return this.facets; - } - - /** - * Set the facets property: 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. - * - * @param facets the facets value to set. - * @return the SearchOptions object itself. - */ - public SearchOptions setFacets(String... facets) { - this.facets = (facets == null) ? null : java.util.Arrays.asList(facets); - return this; - } - - /** - * Get the filter property: The OData $filter expression to apply to the search query. - * - * @return the filter value. - */ - public String getFilter() { - return this.filter; - } - - /** - * Set the filter property: The OData $filter expression to apply to the search query. - * - * @param filter the filter value to set. - * @return the SearchOptions object itself. - */ - public SearchOptions setFilter(String filter) { - this.filter = filter; - return this; - } - - /** - * Get the highlightFields property: The list of field names to use for hit highlights. Only searchable fields can - * be used for hit highlighting. - * - * @return the highlightFields value. - */ - public List getHighlightFields() { - return this.highlightFields; - } - - /** - * Set the highlightFields property: The list of field names to use for hit highlights. Only searchable fields can - * be used for hit highlighting. - * - * @param highlightFields the highlightFields value to set. - * @return the SearchOptions object itself. - */ - public SearchOptions setHighlightFields(String... highlightFields) { - this.highlightFields = (highlightFields == null) ? null : Arrays.asList(highlightFields); - return this; - } - - /** - * Get the highlightPostTag property: A string tag that is appended to hit highlights. Must be set with - * highlightPreTag. Default is &lt;/em&gt;. - * - * @return the highlightPostTag value. - */ - public String getHighlightPostTag() { - return this.highlightPostTag; - } - - /** - * Set the highlightPostTag property: A string tag that is appended to hit highlights. Must be set with - * highlightPreTag. Default is &lt;/em&gt;. - * - * @param highlightPostTag the highlightPostTag value to set. - * @return the SearchOptions object itself. - */ - public SearchOptions setHighlightPostTag(String highlightPostTag) { - this.highlightPostTag = highlightPostTag; - return this; - } - - /** - * Get the highlightPreTag property: A string tag that is prepended to hit highlights. Must be set with - * highlightPostTag. Default is &lt;em&gt;. - * - * @return the highlightPreTag value. - */ - public String getHighlightPreTag() { - return this.highlightPreTag; - } - - /** - * Set the highlightPreTag property: A string tag that is prepended to hit highlights. Must be set with - * highlightPostTag. Default is &lt;em&gt;. - * - * @param highlightPreTag the highlightPreTag value to set. - * @return the SearchOptions object itself. - */ - public SearchOptions setHighlightPreTag(String highlightPreTag) { - this.highlightPreTag = highlightPreTag; - return this; - } - - /** - * Get the minimumCoverage property: 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. - * - * @return the minimumCoverage value. - */ - public Double getMinimumCoverage() { - return this.minimumCoverage; - } - - /** - * Set the minimumCoverage property: 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. - * - * @param minimumCoverage the minimumCoverage value to set. - * @return the SearchOptions object itself. - */ - public SearchOptions setMinimumCoverage(Double minimumCoverage) { - this.minimumCoverage = minimumCoverage; - return this; - } - - /** - * Get the orderBy property: 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. - * - * @return the orderBy value. - */ - public List getOrderBy() { - return this.orderBy; - } - - /** - * Set the orderBy property: 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. - * - * @param orderBy the orderBy value to set. - * @return the SearchOptions object itself. - */ - public SearchOptions setOrderBy(String... orderBy) { - this.orderBy = (orderBy == null) ? null : java.util.Arrays.asList(orderBy); - return this; - } - - /** - * Get the queryType property: A value that specifies the syntax of the search query. The default is 'simple'. Use - * 'full' if your query uses the Lucene query syntax. - * - * @return the queryType value. - */ - public QueryType getQueryType() { - return this.queryType; - } - - /** - * Set the queryType property: A value that specifies the syntax of the search query. The default is 'simple'. Use - * 'full' if your query uses the Lucene query syntax. - * - * @param queryType the queryType value to set. - * @return the SearchOptions object itself. - */ - public SearchOptions setQueryType(QueryType queryType) { - this.queryType = queryType; - return this; - } - - /** - * Get the scoringParameters property: 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). - * - * @return the scoringParameters value. - */ - public List getScoringParameters() { - return this.scoringParameters; - } - - /** - * Set the scoringParameters property: 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). - * - * @param scoringParameters the scoringParameters value to set. - * @return the SearchOptions object itself. - */ - public SearchOptions setScoringParameters(ScoringParameter... scoringParameters) { - this.scoringParameters = (scoringParameters == null) ? null : Arrays.asList(scoringParameters); - return this; - } - - /** - * Get the scoringProfile property: The name of a scoring profile to evaluate match scores for matching documents in - * order to sort the results. - * - * @return the scoringProfile value. - */ - public String getScoringProfile() { - return this.scoringProfile; - } - - /** - * Set the scoringProfile property: The name of a scoring profile to evaluate match scores for matching documents in - * order to sort the results. - * - * @param scoringProfile the scoringProfile value to set. - * @return the SearchOptions object itself. - */ - public SearchOptions setScoringProfile(String scoringProfile) { - this.scoringProfile = scoringProfile; - return this; - } - - /** - * Get the searchFields property: 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. - * - * @return the searchFields value. - */ - public List getSearchFields() { - return this.searchFields; - } - - /** - * Set the searchFields property: 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. - * - * @param searchFields the searchFields value to set. - * @return the SearchOptions object itself. - */ - public SearchOptions setSearchFields(String... searchFields) { - this.searchFields = (searchFields == null) ? null : java.util.Arrays.asList(searchFields); - return this; - } - - /** - * Get the searchMode property: A value that specifies whether any or all of the search terms must be matched in - * order to count the document as a match. - * - * @return the searchMode value. - */ - public SearchMode getSearchMode() { - return this.searchMode; - } - - /** - * Set the searchMode property: A value that specifies whether any or all of the search terms must be matched in - * order to count the document as a match. - * - * @param searchMode the searchMode value to set. - * @return the SearchOptions object itself. - */ - public SearchOptions setSearchMode(SearchMode searchMode) { - this.searchMode = searchMode; - return this; - } - - /** - * Get the scoringStatistics property: 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. - * - * @return the scoringStatistics value. - */ - public ScoringStatistics getScoringStatistics() { - return this.scoringStatistics; - } - - /** - * Set the scoringStatistics property: 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. - * - * @param scoringStatistics the scoringStatistics value to set. - * @return the SearchOptions object itself. - */ - public SearchOptions setScoringStatistics(ScoringStatistics scoringStatistics) { - this.scoringStatistics = scoringStatistics; - return this; - } - - /** - * Get the sessionId property: 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. - * - * @return the sessionId value. - */ - public String getSessionId() { - return this.sessionId; - } - - /** - * Set the sessionId property: 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. - * - * @param sessionId the sessionId value to set. - * @return the SearchOptions object itself. - */ - public SearchOptions setSessionId(String sessionId) { - this.sessionId = sessionId; - return this; - } - - /** - * Get the select property: The list of fields to retrieve. If unspecified, all fields marked as retrievable in the - * schema are included. - * - * @return the select value. - */ - public List getSelect() { - return this.select; - } - - /** - * Set the select property: The list of fields to retrieve. If unspecified, all fields marked as retrievable in the - * schema are included. - * - * @param select the select value to set. - * @return the SearchOptions object itself. - */ - public SearchOptions setSelect(String... select) { - this.select = (select == null) ? null : java.util.Arrays.asList(select); - return this; - } - - /** - * Get the skip property: 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. - * - * @return the skip value. - */ - public Integer getSkip() { - return this.skip; - } - - /** - * Set the skip property: 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. - * - * @param skip the skip value to set. - * @return the SearchOptions object itself. - */ - public SearchOptions setSkip(Integer skip) { - this.skip = skip; - return this; - } - - /** - * Get the top property: 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. - * - * @return the top value. - */ - public Integer getTop() { - return this.top; - } - - /** - * Set the top property: 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. - * - * @param top the top value to set. - * @return the SearchOptions object itself. - */ - public SearchOptions setTop(Integer top) { - this.top = top; - return this; - } - - /** - * Get the debug property: Enables a debugging tool that can be used to further explore your search results. - * - * @return the debug value. - */ - public QueryDebugMode getDebug() { - return this.debug; - } - - /** - * Set the debug property: Enables a debugging tool that can be used to further explore your search results. - * - * @param debug the debug value to set. - * @return the SearchOptions object itself. - */ - public SearchOptions setDebug(QueryDebugMode debug) { - this.debug = debug; - return this; - } - - /** - * Get the queryLanguage property: The language of the query. - * - * @return the queryLanguage value. - */ - public QueryLanguage getQueryLanguage() { - return this.queryLanguage; - } - - /** - * Set the queryLanguage property: The language of the query. - * - * @param queryLanguage the queryLanguage value to set. - * @return the SearchOptions object itself. - */ - public SearchOptions setQueryLanguage(QueryLanguage queryLanguage) { - this.queryLanguage = queryLanguage; - return this; - } - - /** - * Get the speller property: Improve search recall by spell-correcting individual search query terms. - * - * @return the speller value. - */ - public QuerySpellerType getSpeller() { - return this.speller; - } - - /** - * Set the speller property: Improve search recall by spell-correcting individual search query terms. - * - * @param speller the speller value to set. - * @return the SearchOptions object itself. - */ - public SearchOptions setSpeller(QuerySpellerType speller) { - this.speller = speller; - return this; - } - - /** - * Gets the semantic search options. - * - * @return the semantic search options. - */ - public SemanticSearchOptions getSemanticSearchOptions() { - return this.semanticSearchOptions; - } - - /** - * Sets the semantic search options. - * - * @param semanticSearchOptions the semantic search options. - * @return the SearchOptions object itself. - */ - public SearchOptions setSemanticSearchOptions(SemanticSearchOptions semanticSearchOptions) { - this.semanticSearchOptions = semanticSearchOptions; - return this; - } - - /** - * Sets the vector search options for vector and hybrid search queries. - * - * @param vectorSearchOptions the vector search options. - * @return the SearchOptions object itself. - */ - public SearchOptions setVectorSearchOptions(VectorSearchOptions vectorSearchOptions) { - this.vectorSearchOptions = vectorSearchOptions; - return this; - } - - /** - * Get the vector search options for vector and hybrid search queries. - * - * @return the vector search options. - */ - public VectorSearchOptions getVectorSearchOptions() { - return this.vectorSearchOptions; - } -} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/implementation/models/SearchRequest.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SearchRequest.java similarity index 64% rename from sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/implementation/models/SearchRequest.java rename to sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SearchRequest.java index 9a8b417e5e35..f24578af2b49 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/implementation/models/SearchRequest.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SearchRequest.java @@ -1,292 +1,333 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) TypeSpec Code Generator. -package com.azure.search.documents.implementation.models; +package com.azure.search.documents.models; import com.azure.core.annotation.Fluent; +import com.azure.core.annotation.Generated; import com.azure.json.JsonReader; import com.azure.json.JsonSerializable; import com.azure.json.JsonToken; import com.azure.json.JsonWriter; -import com.azure.search.documents.models.HybridSearch; -import com.azure.search.documents.models.QueryDebugMode; -import com.azure.search.documents.models.QueryLanguage; -import com.azure.search.documents.models.QuerySpellerType; -import com.azure.search.documents.models.QueryType; -import com.azure.search.documents.models.ScoringStatistics; -import com.azure.search.documents.models.SearchMode; -import com.azure.search.documents.models.SemanticErrorMode; -import com.azure.search.documents.models.VectorFilterMode; -import com.azure.search.documents.models.VectorQuery; import java.io.IOException; import java.util.List; /** - * Parameters for filtering, sorting, faceting, paging, and other search query behaviors. + * Parameters for filtering, sorting, faceting, paging, and other search query + * behaviors. */ @Fluent public final class SearchRequest implements JsonSerializable { /* - * 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. + * 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. */ + @Generated private Boolean includeTotalResultCount; /* - * 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. + * 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. */ + @Generated private List facets; /* * The OData $filter expression to apply to the search query. */ + @Generated private String filter; /* - * The comma-separated list of field names to use for hit highlights. Only searchable fields can be used for hit - * highlighting. + * The comma-separated list of field names to use for hit highlights. Only + * searchable fields can be used for hit highlighting. */ + @Generated private String highlightFields; /* - * A string tag that is appended to hit highlights. Must be set with highlightPreTag. Default is </em>. + * A string tag that is appended to hit highlights. Must be set with + * highlightPreTag. Default is </em>. */ + @Generated private String highlightPostTag; /* - * A string tag that is prepended to hit highlights. Must be set with highlightPostTag. Default is <em>. + * A string tag that is prepended to hit highlights. Must be set with + * highlightPostTag. Default is <em>. */ + @Generated private String highlightPreTag; /* - * 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. + * 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. */ + @Generated private Double minimumCoverage; /* - * 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. - */ + * 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. + */ + @Generated private String orderBy; /* - * A value that specifies the syntax of the search query. The default is 'simple'. Use 'full' if your query uses the - * Lucene query syntax. + * A value that specifies the syntax of the search query. The default is 'simple'. + * Use 'full' if your query uses the Lucene query syntax. */ + @Generated private QueryType queryType; /* - * 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. + * 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. */ + @Generated private ScoringStatistics scoringStatistics; /* - * 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. - */ + * 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. + */ + @Generated private String sessionId; /* - * 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). + * 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). */ + @Generated private List scoringParameters; /* - * The name of a scoring profile to evaluate match scores for matching documents in order to sort the results. + * The name of a scoring profile to evaluate match scores for matching documents + * in order to sort the results. */ + @Generated private String scoringProfile; /* - * Enables a debugging tool that can be used to further explore your reranked results. + * Enables a debugging tool that can be used to further explore your reranked + * results. */ + @Generated private QueryDebugMode debug; /* - * A full-text search query expression; Use "*" or omit this parameter to match all documents. + * A full-text search query expression; Use "*" or omit this parameter to match + * all documents. */ + @Generated private String searchText; /* - * 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. + * 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. */ + @Generated private String searchFields; /* - * A value that specifies whether any or all of the search terms must be matched in order to count the document as a - * match. + * A value that specifies whether any or all of the search terms must be matched + * in order to count the document as a match. */ + @Generated private SearchMode searchMode; /* * A value that specifies the language of the search query. */ + @Generated private QueryLanguage queryLanguage; /* - * A value that specified the type of the speller to use to spell-correct individual search query terms. + * A value that specified the type of the speller to use to spell-correct + * individual search query terms. */ + @Generated private QuerySpellerType speller; /* - * The comma-separated list of fields to retrieve. If unspecified, all fields marked as retrievable in the schema - * are included. + * The comma-separated list of fields to retrieve. If unspecified, all fields + * marked as retrievable in the schema are included. */ + @Generated private String select; /* - * 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 + * 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. */ + @Generated private Integer skip; /* - * 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. + * 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. */ + @Generated private Integer top; /* - * The name of a semantic configuration that will be used when processing documents for queries of type semantic. + * The name of a semantic configuration that will be used when processing + * documents for queries of type semantic. */ + @Generated private String semanticConfiguration; /* - * Allows the user to choose whether a semantic call should fail completely (default / current behavior), or to - * return partial results. + * Allows the user to choose whether a semantic call should fail completely + * (default / current behavior), or to return partial results. */ + @Generated private SemanticErrorMode semanticErrorHandling; /* - * 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. + * 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. */ + @Generated private Integer semanticMaxWaitInMilliseconds; /* - * 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. + * 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. */ + @Generated private String semanticQuery; /* - * 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'. + * A value that specifies whether answers should be returned as part of the search + * response. */ - private String answers; + @Generated + private QueryAnswerType answers; /* - * 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'. + * A value that specifies whether captions should be returned as part of the + * search response. */ - private String captions; + @Generated + private QueryCaptionType captions; /* - * 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) 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`. + * A value that specifies whether query rewrites should be generated to augment + * the search query. */ - private String queryRewrites; + @Generated + private QueryRewritesType queryRewrites; /* * The comma-separated list of field names used for semantic ranking. */ + @Generated private String semanticFields; /* * The query parameters for vector and hybrid search queries. */ + @Generated private List vectorQueries; /* - * Determines whether or not filters are applied before or after the vector search is performed. Default is - * 'preFilter' for new indexes. + * Determines whether or not filters are applied before or after the vector search + * is performed. Default is 'preFilter' for new indexes. */ + @Generated private VectorFilterMode vectorFilterMode; /* * The query parameters to configure hybrid search behaviors. */ + @Generated private HybridSearch hybridSearch; /** * Creates an instance of SearchRequest class. */ + @Generated public SearchRequest() { } /** * Get the includeTotalResultCount property: 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 is + * false. Setting this value to true may have a performance impact. Note that the + * count returned is an approximation. * * @return the includeTotalResultCount value. */ + @Generated public Boolean isIncludeTotalResultCount() { return this.includeTotalResultCount; } /** * Set the includeTotalResultCount property: 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 is + * false. Setting this value to true may have a performance impact. Note that the + * count returned is an approximation. * * @param includeTotalResultCount the includeTotalResultCount value to set. * @return the SearchRequest object itself. */ + @Generated public SearchRequest setIncludeTotalResultCount(Boolean includeTotalResultCount) { this.includeTotalResultCount = includeTotalResultCount; return this; } /** - * Get the facets property: 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. + * Get the facets property: 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. * * @return the facets value. */ + @Generated public List getFacets() { return this.facets; } /** - * Set the facets property: 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. + * Set the facets property: 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. * * @param facets the facets value to set. * @return the SearchRequest object itself. */ + @Generated public SearchRequest setFacets(List facets) { this.facets = facets; return this; @@ -297,6 +338,7 @@ public SearchRequest setFacets(List facets) { * * @return the filter value. */ + @Generated public String getFilter() { return this.filter; } @@ -307,6 +349,7 @@ public String getFilter() { * @param filter the filter value to set. * @return the SearchRequest object itself. */ + @Generated public SearchRequest setFilter(String filter) { this.filter = filter; return this; @@ -318,6 +361,7 @@ public SearchRequest setFilter(String filter) { * * @return the highlightFields value. */ + @Generated public String getHighlightFields() { return this.highlightFields; } @@ -329,6 +373,7 @@ public String getHighlightFields() { * @param highlightFields the highlightFields value to set. * @return the SearchRequest object itself. */ + @Generated public SearchRequest setHighlightFields(String highlightFields) { this.highlightFields = highlightFields; return this; @@ -340,6 +385,7 @@ public SearchRequest setHighlightFields(String highlightFields) { * * @return the highlightPostTag value. */ + @Generated public String getHighlightPostTag() { return this.highlightPostTag; } @@ -351,6 +397,7 @@ public String getHighlightPostTag() { * @param highlightPostTag the highlightPostTag value to set. * @return the SearchRequest object itself. */ + @Generated public SearchRequest setHighlightPostTag(String highlightPostTag) { this.highlightPostTag = highlightPostTag; return this; @@ -362,6 +409,7 @@ public SearchRequest setHighlightPostTag(String highlightPostTag) { * * @return the highlightPreTag value. */ + @Generated public String getHighlightPreTag() { return this.highlightPreTag; } @@ -373,6 +421,7 @@ public String getHighlightPreTag() { * @param highlightPreTag the highlightPreTag value to set. * @return the SearchRequest object itself. */ + @Generated public SearchRequest setHighlightPreTag(String highlightPreTag) { this.highlightPreTag = highlightPreTag; return this; @@ -380,73 +429,85 @@ public SearchRequest setHighlightPreTag(String highlightPreTag) { /** * Get the minimumCoverage property: 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. + * 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. * * @return the minimumCoverage value. */ + @Generated public Double getMinimumCoverage() { return this.minimumCoverage; } /** * Set the minimumCoverage property: 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. + * 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. * * @param minimumCoverage the minimumCoverage value to set. * @return the SearchRequest object itself. */ + @Generated public SearchRequest setMinimumCoverage(Double minimumCoverage) { this.minimumCoverage = minimumCoverage; return this; } /** - * Get the orderBy property: 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. + * Get the orderBy property: 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. * * @return the orderBy value. */ + @Generated public String getOrderBy() { return this.orderBy; } /** - * Set the orderBy property: 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. + * Set the orderBy property: 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. * * @param orderBy the orderBy value to set. * @return the SearchRequest object itself. */ + @Generated public SearchRequest setOrderBy(String orderBy) { this.orderBy = orderBy; return this; } /** - * Get the queryType property: A value that specifies the syntax of the search query. The default is 'simple'. Use - * 'full' if your query uses the Lucene query syntax. + * Get the queryType property: A value that specifies the syntax of the search query. The default is 'simple'. + * Use 'full' if your query uses the Lucene query syntax. * * @return the queryType value. */ + @Generated public QueryType getQueryType() { return this.queryType; } /** - * Set the queryType property: A value that specifies the syntax of the search query. The default is 'simple'. Use - * 'full' if your query uses the Lucene query syntax. + * Set the queryType property: A value that specifies the syntax of the search query. The default is 'simple'. + * Use 'full' if your query uses the Lucene query syntax. * * @param queryType the queryType value to set. * @return the SearchRequest object itself. */ + @Generated public SearchRequest setQueryType(QueryType queryType) { this.queryType = queryType; return this; @@ -454,53 +515,63 @@ public SearchRequest setQueryType(QueryType queryType) { /** * Get the scoringStatistics property: 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. + * 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. * * @return the scoringStatistics value. */ + @Generated public ScoringStatistics getScoringStatistics() { return this.scoringStatistics; } /** * Set the scoringStatistics property: 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. + * 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. * * @param scoringStatistics the scoringStatistics value to set. * @return the SearchRequest object itself. */ + @Generated public SearchRequest setScoringStatistics(ScoringStatistics scoringStatistics) { this.scoringStatistics = scoringStatistics; return this; } /** - * Get the sessionId property: 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. + * Get the sessionId property: 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. * * @return the sessionId value. */ + @Generated public String getSessionId() { return this.sessionId; } /** - * Set the sessionId property: 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. + * Set the sessionId property: 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. * * @param sessionId the sessionId value to set. * @return the SearchRequest object itself. */ + @Generated public SearchRequest setSessionId(String sessionId) { this.sessionId = sessionId; return this; @@ -508,87 +579,99 @@ public SearchRequest setSessionId(String sessionId) { /** * Get the scoringParameters property: 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). + * 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). * * @return the scoringParameters value. */ + @Generated public List getScoringParameters() { return this.scoringParameters; } /** * Set the scoringParameters property: 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). + * 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). * * @param scoringParameters the scoringParameters value to set. * @return the SearchRequest object itself. */ + @Generated public SearchRequest setScoringParameters(List scoringParameters) { this.scoringParameters = scoringParameters; return this; } /** - * Get the scoringProfile property: The name of a scoring profile to evaluate match scores for matching documents in - * order to sort the results. + * Get the scoringProfile property: The name of a scoring profile to evaluate match scores for matching documents + * in order to sort the results. * * @return the scoringProfile value. */ + @Generated public String getScoringProfile() { return this.scoringProfile; } /** - * Set the scoringProfile property: The name of a scoring profile to evaluate match scores for matching documents in - * order to sort the results. + * Set the scoringProfile property: The name of a scoring profile to evaluate match scores for matching documents + * in order to sort the results. * * @param scoringProfile the scoringProfile value to set. * @return the SearchRequest object itself. */ + @Generated public SearchRequest setScoringProfile(String scoringProfile) { this.scoringProfile = scoringProfile; return this; } /** - * Get the debug property: Enables a debugging tool that can be used to further explore your reranked results. + * Get the debug property: Enables a debugging tool that can be used to further explore your reranked + * results. * * @return the debug value. */ + @Generated public QueryDebugMode getDebug() { return this.debug; } /** - * Set the debug property: Enables a debugging tool that can be used to further explore your reranked results. + * Set the debug property: Enables a debugging tool that can be used to further explore your reranked + * results. * * @param debug the debug value to set. * @return the SearchRequest object itself. */ + @Generated public SearchRequest setDebug(QueryDebugMode debug) { this.debug = debug; return this; } /** - * Get the searchText property: A full-text search query expression; Use "*" or omit this parameter to match all - * documents. + * Get the searchText property: A full-text search query expression; Use "*" or omit this parameter to match + * all documents. * * @return the searchText value. */ + @Generated public String getSearchText() { return this.searchText; } /** - * Set the searchText property: A full-text search query expression; Use "*" or omit this parameter to match all - * documents. + * Set the searchText property: A full-text search query expression; Use "*" or omit this parameter to match + * all documents. * * @param searchText the searchText value to set. * @return the SearchRequest object itself. */ + @Generated public SearchRequest setSearchText(String searchText) { this.searchText = searchText; return this; @@ -596,45 +679,51 @@ public SearchRequest setSearchText(String searchText) { /** * Get the searchFields property: 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. + * 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. * * @return the searchFields value. */ + @Generated public String getSearchFields() { return this.searchFields; } /** * Set the searchFields property: 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. + * 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. * * @param searchFields the searchFields value to set. * @return the SearchRequest object itself. */ + @Generated public SearchRequest setSearchFields(String searchFields) { this.searchFields = searchFields; return this; } /** - * Get the searchMode property: A value that specifies whether any or all of the search terms must be matched in - * order to count the document as a match. + * Get the searchMode property: A value that specifies whether any or all of the search terms must be matched + * in order to count the document as a match. * * @return the searchMode value. */ + @Generated public SearchMode getSearchMode() { return this.searchMode; } /** - * Set the searchMode property: A value that specifies whether any or all of the search terms must be matched in - * order to count the document as a match. + * Set the searchMode property: A value that specifies whether any or all of the search terms must be matched + * in order to count the document as a match. * * @param searchMode the searchMode value to set. * @return the SearchRequest object itself. */ + @Generated public SearchRequest setSearchMode(SearchMode searchMode) { this.searchMode = searchMode; return this; @@ -645,6 +734,7 @@ public SearchRequest setSearchMode(SearchMode searchMode) { * * @return the queryLanguage value. */ + @Generated public QueryLanguage getQueryLanguage() { return this.queryLanguage; } @@ -655,98 +745,113 @@ public QueryLanguage getQueryLanguage() { * @param queryLanguage the queryLanguage value to set. * @return the SearchRequest object itself. */ + @Generated public SearchRequest setQueryLanguage(QueryLanguage queryLanguage) { this.queryLanguage = queryLanguage; return this; } /** - * Get the speller property: A value that specified the type of the speller to use to spell-correct individual - * search query terms. + * Get the speller property: A value that specified the type of the speller to use to spell-correct + * individual search query terms. * * @return the speller value. */ + @Generated public QuerySpellerType getSpeller() { return this.speller; } /** - * Set the speller property: A value that specified the type of the speller to use to spell-correct individual - * search query terms. + * Set the speller property: A value that specified the type of the speller to use to spell-correct + * individual search query terms. * * @param speller the speller value to set. * @return the SearchRequest object itself. */ + @Generated public SearchRequest setSpeller(QuerySpellerType speller) { this.speller = speller; return this; } /** - * Get the select property: The comma-separated list of fields to retrieve. If unspecified, all fields marked as - * retrievable in the schema are included. + * Get the select property: The comma-separated list of fields to retrieve. If unspecified, all fields + * marked as retrievable in the schema are included. * * @return the select value. */ + @Generated public String getSelect() { return this.select; } /** - * Set the select property: The comma-separated list of fields to retrieve. If unspecified, all fields marked as - * retrievable in the schema are included. + * Set the select property: The comma-separated list of fields to retrieve. If unspecified, all fields + * marked as retrievable in the schema are included. * * @param select the select value to set. * @return the SearchRequest object itself. */ + @Generated public SearchRequest setSelect(String select) { this.select = select; return this; } /** - * Get the skip property: 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. + * Get the skip property: 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. * * @return the skip value. */ + @Generated public Integer getSkip() { return this.skip; } /** - * Set the skip property: 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. + * Set the skip property: 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. * * @param skip the skip value to set. * @return the SearchRequest object itself. */ + @Generated public SearchRequest setSkip(Integer skip) { this.skip = skip; return this; } /** - * Get the top property: 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. + * Get the top property: 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. * * @return the top value. */ + @Generated public Integer getTop() { return this.top; } /** - * Set the top property: 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. + * Set the top property: 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. * * @param top the top value to set. * @return the SearchRequest object itself. */ + @Generated public SearchRequest setTop(Integer top) { this.top = top; return this; @@ -758,6 +863,7 @@ public SearchRequest setTop(Integer top) { * * @return the semanticConfiguration value. */ + @Generated public String getSemanticConfiguration() { return this.semanticConfiguration; } @@ -769,6 +875,7 @@ public String getSemanticConfiguration() { * @param semanticConfiguration the semanticConfiguration value to set. * @return the SearchRequest object itself. */ + @Generated public SearchRequest setSemanticConfiguration(String semanticConfiguration) { this.semanticConfiguration = semanticConfiguration; return this; @@ -780,6 +887,7 @@ public SearchRequest setSemanticConfiguration(String semanticConfiguration) { * * @return the semanticErrorHandling value. */ + @Generated public SemanticErrorMode getSemanticErrorHandling() { return this.semanticErrorHandling; } @@ -791,6 +899,7 @@ public SemanticErrorMode getSemanticErrorHandling() { * @param semanticErrorHandling the semanticErrorHandling value to set. * @return the SearchRequest object itself. */ + @Generated public SearchRequest setSemanticErrorHandling(SemanticErrorMode semanticErrorHandling) { this.semanticErrorHandling = semanticErrorHandling; return this; @@ -798,21 +907,25 @@ public SearchRequest setSemanticErrorHandling(SemanticErrorMode semanticErrorHan /** * Get the semanticMaxWaitInMilliseconds property: 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. + * takes for + * semantic enrichment to finish processing before the request fails. * * @return the semanticMaxWaitInMilliseconds value. */ + @Generated public Integer getSemanticMaxWaitInMilliseconds() { return this.semanticMaxWaitInMilliseconds; } /** * Set the semanticMaxWaitInMilliseconds property: 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. + * takes for + * semantic enrichment to finish processing before the request fails. * * @param semanticMaxWaitInMilliseconds the semanticMaxWaitInMilliseconds value to set. * @return the SearchRequest object itself. */ + @Generated public SearchRequest setSemanticMaxWaitInMilliseconds(Integer semanticMaxWaitInMilliseconds) { this.semanticMaxWaitInMilliseconds = semanticMaxWaitInMilliseconds; return this; @@ -820,114 +933,100 @@ public SearchRequest setSemanticMaxWaitInMilliseconds(Integer semanticMaxWaitInM /** * Get the semanticQuery property: 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. + * 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. * * @return the semanticQuery value. */ + @Generated public String getSemanticQuery() { return this.semanticQuery; } /** * Set the semanticQuery property: 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. + * 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. * * @param semanticQuery the semanticQuery value to set. * @return the SearchRequest object itself. */ + @Generated public SearchRequest setSemanticQuery(String semanticQuery) { this.semanticQuery = semanticQuery; return this; } /** - * Get the answers property: 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-<number of answers>` 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-<confidence 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-<number of maximum character length>', such as 'extractive|maxcharlength-600'. + * Get the answers property: A value that specifies whether answers should be returned as part of the search + * response. * * @return the answers value. */ - public String getAnswers() { + @Generated + public QueryAnswerType getAnswers() { return this.answers; } /** - * Set the answers property: 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-<number of answers>` 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-<confidence 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-<number of maximum character length>', such as 'extractive|maxcharlength-600'. + * Set the answers property: A value that specifies whether answers should be returned as part of the search + * response. * * @param answers the answers value to set. * @return the SearchRequest object itself. */ - public SearchRequest setAnswers(String answers) { + @Generated + public SearchRequest setAnswers(QueryAnswerType answers) { this.answers = answers; return this; } /** - * Get the captions property: 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-<true/false>` 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-<number of maximum character length>', such as 'extractive|maxcharlength-600'. + * Get the captions property: A value that specifies whether captions should be returned as part of the + * search response. * * @return the captions value. */ - public String getCaptions() { + @Generated + public QueryCaptionType getCaptions() { return this.captions; } /** - * Set the captions property: 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-<true/false>` 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-<number of maximum character length>', such as 'extractive|maxcharlength-600'. + * Set the captions property: A value that specifies whether captions should be returned as part of the + * search response. * * @param captions the captions value to set. * @return the SearchRequest object itself. */ - public SearchRequest setCaptions(String captions) { + @Generated + public SearchRequest setCaptions(QueryCaptionType captions) { this.captions = captions; return this; } /** - * Get the queryRewrites property: 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) rewrites to - * help increase the recall of the request. The requested count can be configured by appending the pipe character - * `|` followed by the `count-<number of rewrites>` option, such as `generative|count-3`. Defaults to `None`. + * Get the queryRewrites property: A value that specifies whether query rewrites should be generated to augment + * the search query. * * @return the queryRewrites value. */ - public String getQueryRewrites() { + @Generated + public QueryRewritesType getQueryRewrites() { return this.queryRewrites; } /** - * Set the queryRewrites property: 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) rewrites to - * help increase the recall of the request. The requested count can be configured by appending the pipe character - * `|` followed by the `count-<number of rewrites>` option, such as `generative|count-3`. Defaults to `None`. + * Set the queryRewrites property: A value that specifies whether query rewrites should be generated to augment + * the search query. * * @param queryRewrites the queryRewrites value to set. * @return the SearchRequest object itself. */ - public SearchRequest setQueryRewrites(String queryRewrites) { + @Generated + public SearchRequest setQueryRewrites(QueryRewritesType queryRewrites) { this.queryRewrites = queryRewrites; return this; } @@ -937,6 +1036,7 @@ public SearchRequest setQueryRewrites(String queryRewrites) { * * @return the semanticFields value. */ + @Generated public String getSemanticFields() { return this.semanticFields; } @@ -947,6 +1047,7 @@ public String getSemanticFields() { * @param semanticFields the semanticFields value to set. * @return the SearchRequest object itself. */ + @Generated public SearchRequest setSemanticFields(String semanticFields) { this.semanticFields = semanticFields; return this; @@ -957,6 +1058,7 @@ public SearchRequest setSemanticFields(String semanticFields) { * * @return the vectorQueries value. */ + @Generated public List getVectorQueries() { return this.vectorQueries; } @@ -967,6 +1069,7 @@ public List getVectorQueries() { * @param vectorQueries the vectorQueries value to set. * @return the SearchRequest object itself. */ + @Generated public SearchRequest setVectorQueries(List vectorQueries) { this.vectorQueries = vectorQueries; return this; @@ -974,21 +1077,25 @@ public SearchRequest setVectorQueries(List vectorQueries) { /** * Get the vectorFilterMode property: Determines whether or not filters are applied before or after the vector - * search is performed. Default is 'preFilter' for new indexes. + * search + * is performed. Default is 'preFilter' for new indexes. * * @return the vectorFilterMode value. */ + @Generated public VectorFilterMode getVectorFilterMode() { return this.vectorFilterMode; } /** * Set the vectorFilterMode property: Determines whether or not filters are applied before or after the vector - * search is performed. Default is 'preFilter' for new indexes. + * search + * is performed. Default is 'preFilter' for new indexes. * * @param vectorFilterMode the vectorFilterMode value to set. * @return the SearchRequest object itself. */ + @Generated public SearchRequest setVectorFilterMode(VectorFilterMode vectorFilterMode) { this.vectorFilterMode = vectorFilterMode; return this; @@ -999,6 +1106,7 @@ public SearchRequest setVectorFilterMode(VectorFilterMode vectorFilterMode) { * * @return the hybridSearch value. */ + @Generated public HybridSearch getHybridSearch() { return this.hybridSearch; } @@ -1009,6 +1117,7 @@ public HybridSearch getHybridSearch() { * @param hybridSearch the hybridSearch value to set. * @return the SearchRequest object itself. */ + @Generated public SearchRequest setHybridSearch(HybridSearch hybridSearch) { this.hybridSearch = hybridSearch; return this; @@ -1017,6 +1126,7 @@ public SearchRequest setHybridSearch(HybridSearch hybridSearch) { /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); @@ -1049,9 +1159,9 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { this.semanticErrorHandling == null ? null : this.semanticErrorHandling.toString()); jsonWriter.writeNumberField("semanticMaxWaitInMilliseconds", this.semanticMaxWaitInMilliseconds); jsonWriter.writeStringField("semanticQuery", this.semanticQuery); - jsonWriter.writeStringField("answers", this.answers); - jsonWriter.writeStringField("captions", this.captions); - jsonWriter.writeStringField("queryRewrites", this.queryRewrites); + jsonWriter.writeStringField("answers", this.answers == null ? null : this.answers.toString()); + jsonWriter.writeStringField("captions", this.captions == null ? null : this.captions.toString()); + jsonWriter.writeStringField("queryRewrites", this.queryRewrites == null ? null : this.queryRewrites.toString()); jsonWriter.writeStringField("semanticFields", this.semanticFields); jsonWriter.writeArrayField("vectorQueries", this.vectorQueries, (writer, element) -> writer.writeJson(element)); jsonWriter.writeStringField("vectorFilterMode", @@ -1068,6 +1178,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { * pointing to JSON null. * @throws IOException If an error occurs while reading the SearchRequest. */ + @Generated public static SearchRequest fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { SearchRequest deserializedSearchRequest = new SearchRequest(); @@ -1130,11 +1241,11 @@ public static SearchRequest fromJson(JsonReader jsonReader) throws IOException { } else if ("semanticQuery".equals(fieldName)) { deserializedSearchRequest.semanticQuery = reader.getString(); } else if ("answers".equals(fieldName)) { - deserializedSearchRequest.answers = reader.getString(); + deserializedSearchRequest.answers = QueryAnswerType.fromString(reader.getString()); } else if ("captions".equals(fieldName)) { - deserializedSearchRequest.captions = reader.getString(); + deserializedSearchRequest.captions = QueryCaptionType.fromString(reader.getString()); } else if ("queryRewrites".equals(fieldName)) { - deserializedSearchRequest.queryRewrites = reader.getString(); + deserializedSearchRequest.queryRewrites = QueryRewritesType.fromString(reader.getString()); } else if ("semanticFields".equals(fieldName)) { deserializedSearchRequest.semanticFields = reader.getString(); } else if ("vectorQueries".equals(fieldName)) { diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SearchResourceEncryptionKey.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SearchResourceEncryptionKey.java new file mode 100644 index 000000000000..1e22b7618c16 --- /dev/null +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SearchResourceEncryptionKey.java @@ -0,0 +1,229 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.search.documents.models; + +import com.azure.core.annotation.Fluent; +import com.azure.core.annotation.Generated; +import com.azure.json.JsonReader; +import com.azure.json.JsonSerializable; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import java.io.IOException; + +/** + * 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. + */ +@Fluent +public final class SearchResourceEncryptionKey implements JsonSerializable { + /* + * The name of your Azure Key Vault key to be used to encrypt your data at rest. + */ + @Generated + private final String keyName; + + /* + * The version of your Azure Key Vault key to be used to encrypt your data at rest. + */ + @Generated + private String keyVersion; + + /* + * 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`. + */ + @Generated + private final String vaultUri; + + /* + * Optional Azure Active Directory credentials used for accessing your Azure Key + * Vault. Not required if using managed identity instead. + */ + @Generated + private AzureActiveDirectoryApplicationCredentials accessCredentials; + + /* + * 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. + */ + @Generated + private SearchIndexerDataIdentity identity; + + /** + * Creates an instance of SearchResourceEncryptionKey class. + * + * @param keyName the keyName value to set. + * @param vaultUri the vaultUri value to set. + */ + @Generated + public SearchResourceEncryptionKey(String keyName, String vaultUri) { + this.keyName = keyName; + this.vaultUri = vaultUri; + } + + /** + * Get the keyName property: The name of your Azure Key Vault key to be used to encrypt your data at rest. + * + * @return the keyName value. + */ + @Generated + public String getKeyName() { + return this.keyName; + } + + /** + * Get the keyVersion property: The version of your Azure Key Vault key to be used to encrypt your data at rest. + * + * @return the keyVersion value. + */ + @Generated + public String getKeyVersion() { + return this.keyVersion; + } + + /** + * Set the keyVersion property: The version of your Azure Key Vault key to be used to encrypt your data at rest. + * + * @param keyVersion the keyVersion value to set. + * @return the SearchResourceEncryptionKey object itself. + */ + @Generated + public SearchResourceEncryptionKey setKeyVersion(String keyVersion) { + this.keyVersion = keyVersion; + return this; + } + + /** + * Get the vaultUri property: 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`. + * + * @return the vaultUri value. + */ + @Generated + public String getVaultUri() { + return this.vaultUri; + } + + /** + * Get the accessCredentials property: Optional Azure Active Directory credentials used for accessing your Azure Key + * Vault. Not required if using managed identity instead. + * + * @return the accessCredentials value. + */ + @Generated + public AzureActiveDirectoryApplicationCredentials getAccessCredentials() { + return this.accessCredentials; + } + + /** + * Set the accessCredentials property: Optional Azure Active Directory credentials used for accessing your Azure Key + * Vault. Not required if using managed identity instead. + * + * @param accessCredentials the accessCredentials value to set. + * @return the SearchResourceEncryptionKey object itself. + */ + @Generated + public SearchResourceEncryptionKey + setAccessCredentials(AzureActiveDirectoryApplicationCredentials accessCredentials) { + this.accessCredentials = accessCredentials; + return this; + } + + /** + * Get the identity property: 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. + * + * @return the identity value. + */ + @Generated + public SearchIndexerDataIdentity getIdentity() { + return this.identity; + } + + /** + * Set the identity property: 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. + * + * @param identity the identity value to set. + * @return the SearchResourceEncryptionKey object itself. + */ + @Generated + public SearchResourceEncryptionKey setIdentity(SearchIndexerDataIdentity identity) { + this.identity = identity; + return this; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("keyVaultKeyName", this.keyName); + jsonWriter.writeStringField("keyVaultUri", this.vaultUri); + jsonWriter.writeStringField("keyVaultKeyVersion", this.keyVersion); + jsonWriter.writeJsonField("accessCredentials", this.accessCredentials); + jsonWriter.writeJsonField("identity", this.identity); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of SearchResourceEncryptionKey from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of SearchResourceEncryptionKey if the JsonReader was pointing to an instance of it, or null + * if it was pointing to JSON null. + * @throws IllegalStateException If the deserialized JSON object was missing any required properties. + * @throws IOException If an error occurs while reading the SearchResourceEncryptionKey. + */ + @Generated + public static SearchResourceEncryptionKey fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + String keyName = null; + String vaultUri = null; + String keyVersion = null; + AzureActiveDirectoryApplicationCredentials accessCredentials = null; + SearchIndexerDataIdentity identity = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("keyVaultKeyName".equals(fieldName)) { + keyName = reader.getString(); + } else if ("keyVaultUri".equals(fieldName)) { + vaultUri = reader.getString(); + } else if ("keyVaultKeyVersion".equals(fieldName)) { + keyVersion = reader.getString(); + } else if ("accessCredentials".equals(fieldName)) { + accessCredentials = AzureActiveDirectoryApplicationCredentials.fromJson(reader); + } else if ("identity".equals(fieldName)) { + identity = SearchIndexerDataIdentity.fromJson(reader); + } else { + reader.skipChildren(); + } + } + SearchResourceEncryptionKey deserializedSearchResourceEncryptionKey + = new SearchResourceEncryptionKey(keyName, vaultUri); + deserializedSearchResourceEncryptionKey.keyVersion = keyVersion; + deserializedSearchResourceEncryptionKey.accessCredentials = accessCredentials; + deserializedSearchResourceEncryptionKey.identity = identity; + + return deserializedSearchResourceEncryptionKey; + }); + } +} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SearchResult.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SearchResult.java index 61dd60953475..b33f8a6476f7 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SearchResult.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SearchResult.java @@ -1,191 +1,223 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.search.documents.models; -import com.azure.core.annotation.Fluent; -import com.azure.core.util.serializer.JsonSerializer; -import com.azure.search.documents.SearchDocument; -import com.azure.search.documents.implementation.converters.SearchResultHelper; - +import com.azure.core.annotation.Generated; +import com.azure.core.annotation.Immutable; +import com.azure.core.util.BinaryData; +import com.azure.json.JsonReader; +import com.azure.json.JsonSerializable; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import java.io.IOException; +import java.util.LinkedHashMap; import java.util.List; import java.util.Map; -import static com.azure.core.util.serializer.TypeReference.createInstance; - /** * Contains a document found by a search query, plus associated metadata. */ -@Fluent -public final class SearchResult { - +@Immutable +public final class SearchResult implements JsonSerializable { /* - * The relevance score of the document compared to other documents returned - * by the query. + * The relevance score of the document compared to other documents returned by the + * query. */ + @Generated private final double score; /* - * The semantic search results based on the search request. + * 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'. */ - private SemanticSearchResult semanticSearch; + @Generated + private Double rerankerScore; /* - * 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. + * 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. */ + @Generated private Map> highlights; /* - * Contains debugging information that can be used to further explore your search results. + * 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'. */ - private DocumentDebugInfo documentDebugInfo; + @Generated + private List captions; /* - * Contains a document found by a search query, plus associated metadata. + * Contains debugging information that can be used to further explore your search + * results. */ - private Map additionalProperties; + @Generated + private List documentDebugInfo; /* - * The json serializer. + * Contains a document found by a search query, plus associated metadata. */ - private JsonSerializer jsonSerializer; - - static { - SearchResultHelper.setAccessor(new SearchResultHelper.SearchResultAccessor() { - @Override - public void setAdditionalProperties(SearchResult searchResult, SearchDocument additionalProperties) { - searchResult.setAdditionalProperties(additionalProperties); - } - - @Override - public void setHighlights(SearchResult searchResult, Map> highlights) { - searchResult.setHighlights(highlights); - } - - @Override - public void setJsonSerializer(SearchResult searchResult, JsonSerializer jsonSerializer) { - searchResult.setJsonSerializer(jsonSerializer); - } - - @Override - public void setSemanticSearchResults(SearchResult searchResult, Double rerankerScore, - List captions) { - searchResult.setSemanticSearchResult(rerankerScore, captions); - } - - @Override - public void setDocumentDebugInfo(SearchResult searchResult, DocumentDebugInfo documentDebugInfo) { - searchResult.setDocumentDebugInfo(documentDebugInfo); - } - }); - } + @Generated + private Map additionalProperties; /** - * Constructor of {@link SearchResult}. - * - * @param score The relevance score of the document compared to other documents returned by the query. + * Creates an instance of SearchResult class. + * + * @param score the score value to set. */ - public SearchResult(double score) { + @Generated + private SearchResult(double score) { this.score = score; } /** - * Get the score property: The relevance score of the document compared to other documents returned by the query. - * + * Get the score property: The relevance score of the document compared to other documents returned by the + * query. + * * @return the score value. */ + @Generated public double getScore() { return this.score; } /** - * Get the highlights property: 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. - * + * Get the rerankerScore property: 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'. + * + * @return the rerankerScore value. + */ + @Generated + public Double getRerankerScore() { + return this.rerankerScore; + } + + /** + * Get the highlights property: 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. + * * @return the highlights value. */ + @Generated public Map> getHighlights() { return this.highlights; } /** - * Get the semanticSearchResult property: The semantic search results based on the search request. - *

- * If semantic search wasn't requested this will return a {@link SemanticSearchResult} with no values. - * - * @return the semanticSearchResult value. - */ - public SemanticSearchResult getSemanticSearch() { - return this.semanticSearch; + * Get the captions property: 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'. + * + * @return the captions value. + */ + @Generated + public List getCaptions() { + return this.captions; } /** - * Get the documentDebugInfo property: Contains debugging information that can be used to further explore your search results. + * Get the documentDebugInfo property: Contains debugging information that can be used to further explore your + * search + * results. + * * @return the documentDebugInfo value. */ - public DocumentDebugInfo getDocumentDebugInfo() { + @Generated + public List getDocumentDebugInfo() { return this.documentDebugInfo; } /** - * Get the additionalProperties property: Unmatched properties from the message are deserialized this collection. - * - * @param modelClass The model class converts to. - * @param Convert document to the generic type. + * Get the additionalProperties property: Contains a document found by a search query, plus associated metadata. + * * @return the additionalProperties value. - * @throws RuntimeException if there is IO error occurs. - */ - public T getDocument(Class modelClass) { - return jsonSerializer.deserializeFromBytes(jsonSerializer.serializeToBytes(additionalProperties), - createInstance(modelClass)); - } - - /** - * The private setter to set the additionalProperties property via {@code SearchResultHelper.SearchResultAccessor}. - * - * @param additionalProperties The Unmatched properties from the message are deserialized this collection. - */ - private void setAdditionalProperties(SearchDocument additionalProperties) { - this.additionalProperties = additionalProperties; - } - - /** - * The private setter to set the highlights property via {@code SearchResultHelper.SearchResultAccessor}. - * - * @param highlights The Text fragments from the document that indicate the matching search terms. */ - private void setHighlights(Map> highlights) { - this.highlights = highlights; + @Generated + public Map getAdditionalProperties() { + return this.additionalProperties; } /** - * The private setter to set the jsonSerializer property via {@code SearchResultHelper.SearchResultAccessor}. - * - * @param jsonSerializer The json serializer. - */ - private void setJsonSerializer(JsonSerializer jsonSerializer) { - this.jsonSerializer = jsonSerializer; - } - - /** - * The private setter to set the documentDebugInfo property via {@code SearchResultHelper.SearchResultAccessor}. - * - * @param documentDebugInfo The document debug info. - */ - private void setDocumentDebugInfo(DocumentDebugInfo documentDebugInfo) { - this.documentDebugInfo = documentDebugInfo; + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeDoubleField("@search.score", this.score); + jsonWriter.writeNumberField("@search.rerankerScore", this.rerankerScore); + jsonWriter.writeMapField("@search.highlights", this.highlights, + (writer, element) -> writer.writeArray(element, (writer1, element1) -> writer1.writeString(element1))); + jsonWriter.writeArrayField("@search.captions", this.captions, (writer, element) -> writer.writeJson(element)); + if (additionalProperties != null) { + for (Map.Entry additionalProperty : additionalProperties.entrySet()) { + jsonWriter.writeFieldName(additionalProperty.getKey()); + if (additionalProperty.getValue() == null) { + jsonWriter.writeNull(); + } else { + additionalProperty.getValue().writeTo(jsonWriter); + } + } + } + return jsonWriter.writeEndObject(); } /** - * The private setter to set the semanticSearchResult property via - * {@code SearchResultHelper.setSemanticSearchResult}. - * - * @param rerankerScore The reranker score. - * @param captions The captions. - */ - private void setSemanticSearchResult(Double rerankerScore, List captions) { - this.semanticSearch = new SemanticSearchResult(rerankerScore, captions); + * Reads an instance of SearchResult from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of SearchResult if the JsonReader was pointing to an instance of it, or null if it was + * pointing to JSON null. + * @throws IllegalStateException If the deserialized JSON object was missing any required properties. + * @throws IOException If an error occurs while reading the SearchResult. + */ + @Generated + public static SearchResult fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + double score = 0.0; + Double rerankerScore = null; + Map> highlights = null; + List captions = null; + List documentDebugInfo = null; + Map additionalProperties = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("@search.score".equals(fieldName)) { + score = reader.getDouble(); + } else if ("@search.rerankerScore".equals(fieldName)) { + rerankerScore = reader.getNullable(JsonReader::getDouble); + } else if ("@search.highlights".equals(fieldName)) { + highlights = reader.readMap(reader1 -> reader1.readArray(reader2 -> reader2.getString())); + } else if ("@search.captions".equals(fieldName)) { + captions = reader.readArray(reader1 -> QueryCaptionResult.fromJson(reader1)); + } else if ("@search.documentDebugInfo".equals(fieldName)) { + documentDebugInfo = reader.readArray(reader1 -> DocumentDebugInfo.fromJson(reader1)); + } else { + if (additionalProperties == null) { + additionalProperties = new LinkedHashMap<>(); + } + + additionalProperties.put(fieldName, + reader.getNullable(nonNullReader -> BinaryData.fromObject(nonNullReader.readUntyped()))); + } + } + SearchResult deserializedSearchResult = new SearchResult(score); + deserializedSearchResult.rerankerScore = rerankerScore; + deserializedSearchResult.highlights = highlights; + deserializedSearchResult.captions = captions; + deserializedSearchResult.documentDebugInfo = documentDebugInfo; + deserializedSearchResult.additionalProperties = additionalProperties; + + return deserializedSearchResult; + }); } } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SearchScoreThreshold.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SearchScoreThreshold.java index c03a29c86df0..d8d8bc228bd9 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SearchScoreThreshold.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SearchScoreThreshold.java @@ -1,10 +1,10 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) TypeSpec Code Generator. + package com.azure.search.documents.models; +import com.azure.core.annotation.Generated; import com.azure.core.annotation.Immutable; import com.azure.json.JsonReader; import com.azure.json.JsonToken; @@ -12,53 +12,56 @@ import java.io.IOException; /** - * 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. + * 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. */ @Immutable public final class SearchScoreThreshold extends VectorThreshold { - /* - * The kind of threshold used to filter vector queries + * Type of threshold. */ + @Generated private VectorThresholdKind kind = VectorThresholdKind.SEARCH_SCORE; /* - * 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. + * 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. */ + @Generated private final double value; /** * Creates an instance of SearchScoreThreshold class. - * + * * @param value the value value to set. */ + @Generated public SearchScoreThreshold(double value) { this.value = value; } /** - * Get the kind property: The kind of threshold used to filter vector queries. - * + * Get the kind property: Type of threshold. + * * @return the kind value. */ + @Generated @Override public VectorThresholdKind getKind() { return this.kind; } /** - * /** - * Get the value property: 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`. - * - * @return the value. - * / + * Get the value property: 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. + * + * @return the value value. */ + @Generated public double getValue() { return this.value; } @@ -66,6 +69,7 @@ public double getValue() { /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); @@ -76,36 +80,34 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of SearchScoreThreshold from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of SearchScoreThreshold if the JsonReader was pointing to an instance of it, or null if it * was pointing to JSON null. * @throws IllegalStateException If the deserialized JSON object was missing any required properties. * @throws IOException If an error occurs while reading the SearchScoreThreshold. */ + @Generated public static SearchScoreThreshold fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { - boolean valueFound = false; double value = 0.0; VectorThresholdKind kind = VectorThresholdKind.SEARCH_SCORE; while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); + if ("value".equals(fieldName)) { value = reader.getDouble(); - valueFound = true; } else if ("kind".equals(fieldName)) { kind = VectorThresholdKind.fromString(reader.getString()); } else { reader.skipChildren(); } } - if (valueFound) { - SearchScoreThreshold deserializedSearchScoreThreshold = new SearchScoreThreshold(value); - deserializedSearchScoreThreshold.kind = kind; - return deserializedSearchScoreThreshold; - } - throw new IllegalStateException("Missing required property: value"); + SearchScoreThreshold deserializedSearchScoreThreshold = new SearchScoreThreshold(value); + deserializedSearchScoreThreshold.kind = kind; + + return deserializedSearchScoreThreshold; }); } } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/SearchServiceCounters.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SearchServiceCounters.java similarity index 66% rename from sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/SearchServiceCounters.java rename to sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SearchServiceCounters.java index 739ecf061ea8..78346857380e 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/SearchServiceCounters.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SearchServiceCounters.java @@ -1,89 +1,103 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) TypeSpec Code Generator. -package com.azure.search.documents.indexes.models; +package com.azure.search.documents.models; -import com.azure.core.annotation.Fluent; +import com.azure.core.annotation.Generated; +import com.azure.core.annotation.Immutable; import com.azure.json.JsonReader; import com.azure.json.JsonSerializable; import com.azure.json.JsonToken; import com.azure.json.JsonWriter; import java.io.IOException; -import java.util.ArrayList; -import java.util.List; /** * Represents service-level resource counters and quotas. */ -@Fluent +@Immutable public final class SearchServiceCounters implements JsonSerializable { /* * Total number of aliases. */ - private ResourceCounter aliasCounter; + @Generated + private final ResourceCounter aliasCounter; /* * Total number of documents across all indexes in the service. */ + @Generated private final ResourceCounter documentCounter; /* * Total number of indexes. */ + @Generated private final ResourceCounter indexCounter; /* * Total number of indexers. */ + @Generated private final ResourceCounter indexerCounter; /* * Total number of data sources. */ + @Generated private final ResourceCounter dataSourceCounter; /* * Total size of used storage in bytes. */ + @Generated private final ResourceCounter storageSizeCounter; /* * Total number of synonym maps. */ + @Generated private final ResourceCounter synonymMapCounter; /* * Total number of skillsets. */ - private ResourceCounter skillsetCounter; + @Generated + private final ResourceCounter skillsetCounter; /* * Total memory consumption of all vector indexes within the service, in bytes. */ - private ResourceCounter vectorIndexSizeCounter; + @Generated + private final ResourceCounter vectorIndexSizeCounter; /** * Creates an instance of SearchServiceCounters class. * + * @param aliasCounter the aliasCounter value to set. * @param documentCounter the documentCounter value to set. * @param indexCounter the indexCounter value to set. * @param indexerCounter the indexerCounter value to set. * @param dataSourceCounter the dataSourceCounter value to set. * @param storageSizeCounter the storageSizeCounter value to set. * @param synonymMapCounter the synonymMapCounter value to set. + * @param skillsetCounter the skillsetCounter value to set. + * @param vectorIndexSizeCounter the vectorIndexSizeCounter value to set. */ - public SearchServiceCounters(ResourceCounter documentCounter, ResourceCounter indexCounter, - ResourceCounter indexerCounter, ResourceCounter dataSourceCounter, ResourceCounter storageSizeCounter, - ResourceCounter synonymMapCounter) { + @Generated + private SearchServiceCounters(ResourceCounter aliasCounter, ResourceCounter documentCounter, + ResourceCounter indexCounter, ResourceCounter indexerCounter, ResourceCounter dataSourceCounter, + ResourceCounter storageSizeCounter, ResourceCounter synonymMapCounter, ResourceCounter skillsetCounter, + ResourceCounter vectorIndexSizeCounter) { + this.aliasCounter = aliasCounter; this.documentCounter = documentCounter; this.indexCounter = indexCounter; this.indexerCounter = indexerCounter; this.dataSourceCounter = dataSourceCounter; this.storageSizeCounter = storageSizeCounter; this.synonymMapCounter = synonymMapCounter; + this.skillsetCounter = skillsetCounter; + this.vectorIndexSizeCounter = vectorIndexSizeCounter; } /** @@ -91,26 +105,17 @@ public SearchServiceCounters(ResourceCounter documentCounter, ResourceCounter in * * @return the aliasCounter value. */ + @Generated public ResourceCounter getAliasCounter() { return this.aliasCounter; } - /** - * Set the aliasCounter property: Total number of aliases. - * - * @param aliasCounter the aliasCounter value to set. - * @return the SearchServiceCounters object itself. - */ - public SearchServiceCounters setAliasCounter(ResourceCounter aliasCounter) { - this.aliasCounter = aliasCounter; - return this; - } - /** * Get the documentCounter property: Total number of documents across all indexes in the service. * * @return the documentCounter value. */ + @Generated public ResourceCounter getDocumentCounter() { return this.documentCounter; } @@ -120,6 +125,7 @@ public ResourceCounter getDocumentCounter() { * * @return the indexCounter value. */ + @Generated public ResourceCounter getIndexCounter() { return this.indexCounter; } @@ -129,6 +135,7 @@ public ResourceCounter getIndexCounter() { * * @return the indexerCounter value. */ + @Generated public ResourceCounter getIndexerCounter() { return this.indexerCounter; } @@ -138,6 +145,7 @@ public ResourceCounter getIndexerCounter() { * * @return the dataSourceCounter value. */ + @Generated public ResourceCounter getDataSourceCounter() { return this.dataSourceCounter; } @@ -147,6 +155,7 @@ public ResourceCounter getDataSourceCounter() { * * @return the storageSizeCounter value. */ + @Generated public ResourceCounter getStorageSizeCounter() { return this.storageSizeCounter; } @@ -156,6 +165,7 @@ public ResourceCounter getStorageSizeCounter() { * * @return the synonymMapCounter value. */ + @Generated public ResourceCounter getSynonymMapCounter() { return this.synonymMapCounter; } @@ -165,56 +175,36 @@ public ResourceCounter getSynonymMapCounter() { * * @return the skillsetCounter value. */ + @Generated public ResourceCounter getSkillsetCounter() { return this.skillsetCounter; } - /** - * Set the skillsetCounter property: Total number of skillsets. - * - * @param skillsetCounter the skillsetCounter value to set. - * @return the SearchServiceCounters object itself. - */ - public SearchServiceCounters setSkillsetCounter(ResourceCounter skillsetCounter) { - this.skillsetCounter = skillsetCounter; - return this; - } - /** * Get the vectorIndexSizeCounter property: Total memory consumption of all vector indexes within the service, in * bytes. * * @return the vectorIndexSizeCounter value. */ + @Generated public ResourceCounter getVectorIndexSizeCounter() { return this.vectorIndexSizeCounter; } - /** - * Set the vectorIndexSizeCounter property: Total memory consumption of all vector indexes within the service, in - * bytes. - * - * @param vectorIndexSizeCounter the vectorIndexSizeCounter value to set. - * @return the SearchServiceCounters object itself. - */ - public SearchServiceCounters setVectorIndexSizeCounter(ResourceCounter vectorIndexSizeCounter) { - this.vectorIndexSizeCounter = vectorIndexSizeCounter; - return this; - } - /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); + jsonWriter.writeJsonField("aliasesCount", this.aliasCounter); jsonWriter.writeJsonField("documentCount", this.documentCounter); jsonWriter.writeJsonField("indexesCount", this.indexCounter); jsonWriter.writeJsonField("indexersCount", this.indexerCounter); jsonWriter.writeJsonField("dataSourcesCount", this.dataSourceCounter); jsonWriter.writeJsonField("storageSize", this.storageSizeCounter); jsonWriter.writeJsonField("synonymMaps", this.synonymMapCounter); - jsonWriter.writeJsonField("aliasesCount", this.aliasCounter); jsonWriter.writeJsonField("skillsetCount", this.skillsetCounter); jsonWriter.writeJsonField("vectorIndexSize", this.vectorIndexSizeCounter); return jsonWriter.writeEndObject(); @@ -229,47 +219,36 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { * @throws IllegalStateException If the deserialized JSON object was missing any required properties. * @throws IOException If an error occurs while reading the SearchServiceCounters. */ + @Generated public static SearchServiceCounters fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { - boolean documentCounterFound = false; + ResourceCounter aliasCounter = null; ResourceCounter documentCounter = null; - boolean indexCounterFound = false; ResourceCounter indexCounter = null; - boolean indexerCounterFound = false; ResourceCounter indexerCounter = null; - boolean dataSourceCounterFound = false; ResourceCounter dataSourceCounter = null; - boolean storageSizeCounterFound = false; ResourceCounter storageSizeCounter = null; - boolean synonymMapCounterFound = false; ResourceCounter synonymMapCounter = null; - ResourceCounter aliasCounter = null; ResourceCounter skillsetCounter = null; ResourceCounter vectorIndexSizeCounter = null; while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); - if ("documentCount".equals(fieldName)) { + if ("aliasesCount".equals(fieldName)) { + aliasCounter = ResourceCounter.fromJson(reader); + } else if ("documentCount".equals(fieldName)) { documentCounter = ResourceCounter.fromJson(reader); - documentCounterFound = true; } else if ("indexesCount".equals(fieldName)) { indexCounter = ResourceCounter.fromJson(reader); - indexCounterFound = true; } else if ("indexersCount".equals(fieldName)) { indexerCounter = ResourceCounter.fromJson(reader); - indexerCounterFound = true; } else if ("dataSourcesCount".equals(fieldName)) { dataSourceCounter = ResourceCounter.fromJson(reader); - dataSourceCounterFound = true; } else if ("storageSize".equals(fieldName)) { storageSizeCounter = ResourceCounter.fromJson(reader); - storageSizeCounterFound = true; } else if ("synonymMaps".equals(fieldName)) { synonymMapCounter = ResourceCounter.fromJson(reader); - synonymMapCounterFound = true; - } else if ("aliasesCount".equals(fieldName)) { - aliasCounter = ResourceCounter.fromJson(reader); } else if ("skillsetCount".equals(fieldName)) { skillsetCounter = ResourceCounter.fromJson(reader); } else if ("vectorIndexSize".equals(fieldName)) { @@ -278,42 +257,8 @@ public static SearchServiceCounters fromJson(JsonReader jsonReader) throws IOExc reader.skipChildren(); } } - if (documentCounterFound - && indexCounterFound - && indexerCounterFound - && dataSourceCounterFound - && storageSizeCounterFound - && synonymMapCounterFound) { - SearchServiceCounters deserializedSearchServiceCounters = new SearchServiceCounters(documentCounter, - indexCounter, indexerCounter, dataSourceCounter, storageSizeCounter, synonymMapCounter); - deserializedSearchServiceCounters.aliasCounter = aliasCounter; - deserializedSearchServiceCounters.skillsetCounter = skillsetCounter; - deserializedSearchServiceCounters.vectorIndexSizeCounter = vectorIndexSizeCounter; - - return deserializedSearchServiceCounters; - } - List missingProperties = new ArrayList<>(); - if (!documentCounterFound) { - missingProperties.add("documentCount"); - } - if (!indexCounterFound) { - missingProperties.add("indexesCount"); - } - if (!indexerCounterFound) { - missingProperties.add("indexersCount"); - } - if (!dataSourceCounterFound) { - missingProperties.add("dataSourcesCount"); - } - if (!storageSizeCounterFound) { - missingProperties.add("storageSize"); - } - if (!synonymMapCounterFound) { - missingProperties.add("synonymMaps"); - } - - throw new IllegalStateException( - "Missing required property/properties: " + String.join(", ", missingProperties)); + return new SearchServiceCounters(aliasCounter, documentCounter, indexCounter, indexerCounter, + dataSourceCounter, storageSizeCounter, synonymMapCounter, skillsetCounter, vectorIndexSizeCounter); }); } } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/SearchServiceLimits.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SearchServiceLimits.java similarity index 63% rename from sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/SearchServiceLimits.java rename to sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SearchServiceLimits.java index b0476964a21c..115b8d9e24ca 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/SearchServiceLimits.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SearchServiceLimits.java @@ -1,12 +1,11 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) TypeSpec Code Generator. -package com.azure.search.documents.indexes.models; +package com.azure.search.documents.models; -import com.azure.core.annotation.Fluent; +import com.azure.core.annotation.Generated; +import com.azure.core.annotation.Immutable; import com.azure.json.JsonReader; import com.azure.json.JsonSerializable; import com.azure.json.JsonToken; @@ -16,38 +15,45 @@ /** * Represents various service level limits. */ -@Fluent +@Immutable public final class SearchServiceLimits implements JsonSerializable { /* * The maximum allowed fields per index. */ + @Generated private Integer maxFieldsPerIndex; /* - * 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. + * 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. */ + @Generated private Integer maxFieldNestingDepthPerIndex; /* - * The maximum number of fields of type Collection(Edm.ComplexType) allowed in an index. + * The maximum number of fields of type Collection(Edm.ComplexType) allowed in an + * index. */ + @Generated private Integer maxComplexCollectionFieldsPerIndex; /* * The maximum number of objects in complex collections allowed per document. */ + @Generated private Integer maxComplexObjectsInCollectionsPerDocument; /* * The maximum amount of storage in bytes allowed per index. */ + @Generated private Long maxStoragePerIndexInBytes; /** * Creates an instance of SearchServiceLimits class. */ - public SearchServiceLimits() { + @Generated + private SearchServiceLimits() { } /** @@ -55,111 +61,60 @@ public SearchServiceLimits() { * * @return the maxFieldsPerIndex value. */ + @Generated public Integer getMaxFieldsPerIndex() { return this.maxFieldsPerIndex; } - /** - * Set the maxFieldsPerIndex property: The maximum allowed fields per index. - * - * @param maxFieldsPerIndex the maxFieldsPerIndex value to set. - * @return the SearchServiceLimits object itself. - */ - public SearchServiceLimits setMaxFieldsPerIndex(Integer maxFieldsPerIndex) { - this.maxFieldsPerIndex = maxFieldsPerIndex; - return this; - } - /** * Get the maxFieldNestingDepthPerIndex property: 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. + * including the + * top-level complex field. For example, a/b/c has a nesting depth of 3. * * @return the maxFieldNestingDepthPerIndex value. */ + @Generated public Integer getMaxFieldNestingDepthPerIndex() { return this.maxFieldNestingDepthPerIndex; } - /** - * Set the maxFieldNestingDepthPerIndex property: 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. - * - * @param maxFieldNestingDepthPerIndex the maxFieldNestingDepthPerIndex value to set. - * @return the SearchServiceLimits object itself. - */ - public SearchServiceLimits setMaxFieldNestingDepthPerIndex(Integer maxFieldNestingDepthPerIndex) { - this.maxFieldNestingDepthPerIndex = maxFieldNestingDepthPerIndex; - return this; - } - /** * Get the maxComplexCollectionFieldsPerIndex property: The maximum number of fields of type - * Collection(Edm.ComplexType) allowed in an index. + * Collection(Edm.ComplexType) allowed in an + * index. * * @return the maxComplexCollectionFieldsPerIndex value. */ + @Generated public Integer getMaxComplexCollectionFieldsPerIndex() { return this.maxComplexCollectionFieldsPerIndex; } - /** - * Set the maxComplexCollectionFieldsPerIndex property: The maximum number of fields of type - * Collection(Edm.ComplexType) allowed in an index. - * - * @param maxComplexCollectionFieldsPerIndex the maxComplexCollectionFieldsPerIndex value to set. - * @return the SearchServiceLimits object itself. - */ - public SearchServiceLimits setMaxComplexCollectionFieldsPerIndex(Integer maxComplexCollectionFieldsPerIndex) { - this.maxComplexCollectionFieldsPerIndex = maxComplexCollectionFieldsPerIndex; - return this; - } - /** * Get the maxComplexObjectsInCollectionsPerDocument property: The maximum number of objects in complex collections * allowed per document. * * @return the maxComplexObjectsInCollectionsPerDocument value. */ + @Generated public Integer getMaxComplexObjectsInCollectionsPerDocument() { return this.maxComplexObjectsInCollectionsPerDocument; } - /** - * Set the maxComplexObjectsInCollectionsPerDocument property: The maximum number of objects in complex collections - * allowed per document. - * - * @param maxComplexObjectsInCollectionsPerDocument the maxComplexObjectsInCollectionsPerDocument value to set. - * @return the SearchServiceLimits object itself. - */ - public SearchServiceLimits - setMaxComplexObjectsInCollectionsPerDocument(Integer maxComplexObjectsInCollectionsPerDocument) { - this.maxComplexObjectsInCollectionsPerDocument = maxComplexObjectsInCollectionsPerDocument; - return this; - } - /** * Get the maxStoragePerIndexInBytes property: The maximum amount of storage in bytes allowed per index. * * @return the maxStoragePerIndexInBytes value. */ + @Generated public Long getMaxStoragePerIndexInBytes() { return this.maxStoragePerIndexInBytes; } - /** - * Set the maxStoragePerIndexInBytes property: The maximum amount of storage in bytes allowed per index. - * - * @param maxStoragePerIndexInBytes the maxStoragePerIndexInBytes value to set. - * @return the SearchServiceLimits object itself. - */ - public SearchServiceLimits setMaxStoragePerIndexInBytes(Long maxStoragePerIndexInBytes) { - this.maxStoragePerIndexInBytes = maxStoragePerIndexInBytes; - return this; - } - /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); @@ -180,6 +135,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { * pointing to JSON null. * @throws IOException If an error occurs while reading the SearchServiceLimits. */ + @Generated public static SearchServiceLimits fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { SearchServiceLimits deserializedSearchServiceLimits = new SearchServiceLimits(); diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/SearchServiceStatistics.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SearchServiceStatistics.java similarity index 72% rename from sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/SearchServiceStatistics.java rename to sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SearchServiceStatistics.java index 763621ce1333..43534a0ea1e4 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/SearchServiceStatistics.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SearchServiceStatistics.java @@ -1,33 +1,33 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) TypeSpec Code Generator. -package com.azure.search.documents.indexes.models; +package com.azure.search.documents.models; +import com.azure.core.annotation.Generated; import com.azure.core.annotation.Immutable; import com.azure.json.JsonReader; import com.azure.json.JsonSerializable; import com.azure.json.JsonToken; import com.azure.json.JsonWriter; import java.io.IOException; -import java.util.ArrayList; -import java.util.List; /** - * Response from a get service statistics request. If successful, it includes service level counters and limits. + * Response from a get service statistics request. If successful, it includes + * service level counters and limits. */ @Immutable public final class SearchServiceStatistics implements JsonSerializable { /* * Service level resource counters. */ + @Generated private final SearchServiceCounters counters; /* * Service level general limits. */ + @Generated private final SearchServiceLimits limits; /** @@ -36,7 +36,8 @@ public final class SearchServiceStatistics implements JsonSerializable { - boolean countersFound = false; SearchServiceCounters counters = null; - boolean limitsFound = false; SearchServiceLimits limits = null; while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); @@ -91,27 +94,13 @@ public static SearchServiceStatistics fromJson(JsonReader jsonReader) throws IOE if ("counters".equals(fieldName)) { counters = SearchServiceCounters.fromJson(reader); - countersFound = true; } else if ("limits".equals(fieldName)) { limits = SearchServiceLimits.fromJson(reader); - limitsFound = true; } else { reader.skipChildren(); } } - if (countersFound && limitsFound) { - return new SearchServiceStatistics(counters, limits); - } - List missingProperties = new ArrayList<>(); - if (!countersFound) { - missingProperties.add("counters"); - } - if (!limitsFound) { - missingProperties.add("limits"); - } - - throw new IllegalStateException( - "Missing required property/properties: " + String.join(", ", missingProperties)); + return new SearchServiceStatistics(counters, limits); }); } } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/SearchSuggester.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SearchSuggester.java similarity index 69% rename from sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/SearchSuggester.java rename to sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SearchSuggester.java index c5472d31caf6..1cf69d3f7017 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/SearchSuggester.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SearchSuggester.java @@ -1,66 +1,70 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. -package com.azure.search.documents.indexes.models; +// Code generated by Microsoft (R) TypeSpec Code Generator. -import com.azure.core.annotation.Fluent; +package com.azure.search.documents.models; + +import com.azure.core.annotation.Generated; +import com.azure.core.annotation.Immutable; import com.azure.json.JsonReader; import com.azure.json.JsonSerializable; import com.azure.json.JsonToken; import com.azure.json.JsonWriter; import java.io.IOException; -import java.util.ArrayList; import java.util.List; /** * Defines how the Suggest API should apply to a group of fields in the index. */ -@Fluent +@Immutable public final class SearchSuggester implements JsonSerializable { - /* * The name of the suggester. */ + @Generated private final String name; /* * A value indicating the capabilities of the suggester. */ - private String searchMode = "analyzingInfixMatching"; + @Generated + private final String searchMode = "analyzingInfixMatching"; /* - * The list of field names to which the suggester applies. Each field must be searchable. + * The list of field names to which the suggester applies. Each field must be + * searchable. */ + @Generated private final List sourceFields; /** * Creates an instance of SearchSuggester class. - * + * * @param name the name value to set. * @param sourceFields the sourceFields value to set. */ + @Generated public SearchSuggester(String name, List sourceFields) { - this.searchMode = "analyzingInfixMatching"; - this.sourceFields = sourceFields; this.name = name; + this.sourceFields = sourceFields; } /** * Get the name property: The name of the suggester. - * + * * @return the name value. */ + @Generated public String getName() { return this.name; } /** * Get the searchMode property: A value indicating the capabilities of the suggester. - * + * * @return the searchMode value. */ + @Generated public String getSearchMode() { return this.searchMode; } @@ -68,9 +72,10 @@ public String getSearchMode() { /** * Get the sourceFields property: The list of field names to which the suggester applies. Each field must be * searchable. - * + * * @return the sourceFields value. */ + @Generated public List getSourceFields() { return this.sourceFields; } @@ -78,60 +83,43 @@ public List getSourceFields() { /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); jsonWriter.writeStringField("name", this.name); - jsonWriter.writeArrayField("sourceFields", this.sourceFields, (writer, element) -> writer.writeString(element)); jsonWriter.writeStringField("searchMode", this.searchMode); + jsonWriter.writeArrayField("sourceFields", this.sourceFields, (writer, element) -> writer.writeString(element)); return jsonWriter.writeEndObject(); } /** * Reads an instance of SearchSuggester from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of SearchSuggester if the JsonReader was pointing to an instance of it, or null if it was * pointing to JSON null. * @throws IllegalStateException If the deserialized JSON object was missing any required properties. * @throws IOException If an error occurs while reading the SearchSuggester. */ + @Generated public static SearchSuggester fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { - boolean nameFound = false; String name = null; - boolean sourceFieldsFound = false; List sourceFields = null; - String searchMode = null; while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); + if ("name".equals(fieldName)) { name = reader.getString(); - nameFound = true; } else if ("sourceFields".equals(fieldName)) { sourceFields = reader.readArray(reader1 -> reader1.getString()); - sourceFieldsFound = true; - } else if ("searchMode".equals(fieldName)) { - searchMode = reader.getString(); } else { reader.skipChildren(); } } - if (nameFound && sourceFieldsFound) { - SearchSuggester deserializedSearchSuggester = new SearchSuggester(name, sourceFields); - deserializedSearchSuggester.searchMode = searchMode; - return deserializedSearchSuggester; - } - List missingProperties = new ArrayList<>(); - if (!nameFound) { - missingProperties.add("name"); - } - if (!sourceFieldsFound) { - missingProperties.add("sourceFields"); - } - throw new IllegalStateException( - "Missing required property/properties: " + String.join(", ", missingProperties)); + return new SearchSuggester(name, sourceFields); }); } } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/SemanticConfiguration.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SemanticConfiguration.java similarity index 60% rename from sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/SemanticConfiguration.java rename to sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SemanticConfiguration.java index 120969a29820..a56ef352be78 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/SemanticConfiguration.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SemanticConfiguration.java @@ -1,43 +1,51 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) TypeSpec Code Generator. -package com.azure.search.documents.indexes.models; +package com.azure.search.documents.models; -import com.azure.core.annotation.Immutable; +import com.azure.core.annotation.Fluent; +import com.azure.core.annotation.Generated; import com.azure.json.JsonReader; import com.azure.json.JsonSerializable; import com.azure.json.JsonToken; import com.azure.json.JsonWriter; import java.io.IOException; -import java.util.ArrayList; -import java.util.List; /** - * Defines a specific configuration to be used in the context of semantic capabilities. + * Defines a specific configuration to be used in the context of semantic + * capabilities. */ -@Immutable +@Fluent public final class SemanticConfiguration implements JsonSerializable { /* * The name of the semantic configuration. */ + @Generated private final String name; /* - * 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. + * 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. */ + @Generated private final SemanticPrioritizedFields prioritizedFields; + /* + * Determines how which semantic or query rewrite models to use during model flighting/upgrades. + */ + @Generated + private Boolean flightingOptIn; + /** * Creates an instance of SemanticConfiguration class. * * @param name the name value to set. * @param prioritizedFields the prioritizedFields value to set. */ + @Generated public SemanticConfiguration(String name, SemanticPrioritizedFields prioritizedFields) { this.name = name; this.prioritizedFields = prioritizedFields; @@ -48,29 +56,58 @@ public SemanticConfiguration(String name, SemanticPrioritizedFields prioritizedF * * @return the name value. */ + @Generated public String getName() { return this.name; } /** * Get the prioritizedFields property: 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. + * ranking, captions, highlights, and answers. At least one of the three sub + * properties (titleField, prioritizedKeywordsFields and prioritizedContentFields) + * need to be set. * * @return the prioritizedFields value. */ + @Generated public SemanticPrioritizedFields getPrioritizedFields() { return this.prioritizedFields; } + /** + * Get the flightingOptIn property: Determines how which semantic or query rewrite models to use during model + * flighting/upgrades. + * + * @return the flightingOptIn value. + */ + @Generated + public Boolean isFlightingOptIn() { + return this.flightingOptIn; + } + + /** + * Set the flightingOptIn property: Determines how which semantic or query rewrite models to use during model + * flighting/upgrades. + * + * @param flightingOptIn the flightingOptIn value to set. + * @return the SemanticConfiguration object itself. + */ + @Generated + public SemanticConfiguration setFlightingOptIn(Boolean flightingOptIn) { + this.flightingOptIn = flightingOptIn; + return this; + } + /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); jsonWriter.writeStringField("name", this.name); jsonWriter.writeJsonField("prioritizedFields", this.prioritizedFields); + jsonWriter.writeBooleanField("flightingOptIn", this.flightingOptIn); return jsonWriter.writeEndObject(); } @@ -83,39 +120,31 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { * @throws IllegalStateException If the deserialized JSON object was missing any required properties. * @throws IOException If an error occurs while reading the SemanticConfiguration. */ + @Generated public static SemanticConfiguration fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { - boolean nameFound = false; String name = null; - boolean prioritizedFieldsFound = false; SemanticPrioritizedFields prioritizedFields = null; + Boolean flightingOptIn = null; while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); if ("name".equals(fieldName)) { name = reader.getString(); - nameFound = true; } else if ("prioritizedFields".equals(fieldName)) { prioritizedFields = SemanticPrioritizedFields.fromJson(reader); - prioritizedFieldsFound = true; + } else if ("flightingOptIn".equals(fieldName)) { + flightingOptIn = reader.getNullable(JsonReader::getBoolean); } else { reader.skipChildren(); } } - if (nameFound && prioritizedFieldsFound) { - return new SemanticConfiguration(name, prioritizedFields); - } - List missingProperties = new ArrayList<>(); - if (!nameFound) { - missingProperties.add("name"); - } - if (!prioritizedFieldsFound) { - missingProperties.add("prioritizedFields"); - } + SemanticConfiguration deserializedSemanticConfiguration + = new SemanticConfiguration(name, prioritizedFields); + deserializedSemanticConfiguration.flightingOptIn = flightingOptIn; - throw new IllegalStateException( - "Missing required property/properties: " + String.join(", ", missingProperties)); + return deserializedSemanticConfiguration; }); } } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SemanticDebugInfo.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SemanticDebugInfo.java index a3e1006bc326..dda6d57642b0 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SemanticDebugInfo.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SemanticDebugInfo.java @@ -1,11 +1,10 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.search.documents.models; +import com.azure.core.annotation.Generated; import com.azure.core.annotation.Immutable; import com.azure.json.JsonReader; import com.azure.json.JsonSerializable; @@ -15,62 +14,73 @@ import java.util.List; /** - * The SemanticDebugInfo model. + * Contains debugging information specific to semantic ranking requests. */ @Immutable public final class SemanticDebugInfo implements JsonSerializable { /* - * The title field that was sent to the semantic enrichment process, as well as how it was used + * The title field that was sent to the semantic enrichment process, as well as + * how it was used */ + @Generated private QueryResultDocumentSemanticField titleField; /* - * The content fields that were sent to the semantic enrichment process, as well as how they were used + * The content fields that were sent to the semantic enrichment process, as well + * as how they were used */ + @Generated private List contentFields; /* - * The keyword fields that were sent to the semantic enrichment process, as well as how they were used + * The keyword fields that were sent to the semantic enrichment process, as well + * as how they were used */ + @Generated private List keywordFields; /* * The raw concatenated strings that were sent to the semantic enrichment process. */ + @Generated private QueryResultDocumentRerankerInput rerankerInput; /** * Creates an instance of SemanticDebugInfo class. */ - public SemanticDebugInfo() { + @Generated + private SemanticDebugInfo() { } /** - * Get the titleField property: The title field that was sent to the semantic enrichment process, as well as how it - * was used. + * Get the titleField property: The title field that was sent to the semantic enrichment process, as well as + * how it was used. * * @return the titleField value. */ + @Generated public QueryResultDocumentSemanticField getTitleField() { return this.titleField; } /** - * Get the contentFields property: The content fields that were sent to the semantic enrichment process, as well as - * how they were used. + * Get the contentFields property: The content fields that were sent to the semantic enrichment process, as well + * as how they were used. * * @return the contentFields value. */ + @Generated public List getContentFields() { return this.contentFields; } /** - * Get the keywordFields property: The keyword fields that were sent to the semantic enrichment process, as well as - * how they were used. + * Get the keywordFields property: The keyword fields that were sent to the semantic enrichment process, as well + * as how they were used. * * @return the keywordFields value. */ + @Generated public List getKeywordFields() { return this.keywordFields; } @@ -80,6 +90,7 @@ public List getKeywordFields() { * * @return the rerankerInput value. */ + @Generated public QueryResultDocumentRerankerInput getRerankerInput() { return this.rerankerInput; } @@ -87,6 +98,7 @@ public QueryResultDocumentRerankerInput getRerankerInput() { /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); @@ -101,6 +113,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { * pointing to JSON null. * @throws IOException If an error occurs while reading the SemanticDebugInfo. */ + @Generated public static SemanticDebugInfo fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { SemanticDebugInfo deserializedSemanticDebugInfo = new SemanticDebugInfo(); diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SemanticErrorMode.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SemanticErrorMode.java index 2e748874c94a..3c2838e2a9cb 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SemanticErrorMode.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SemanticErrorMode.java @@ -1,28 +1,31 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.search.documents.models; +import com.azure.core.annotation.Generated; import com.azure.core.util.ExpandableStringEnum; import java.util.Collection; /** - * Allows the user to choose whether a semantic call should fail completely, or to return partial results. + * Allows the user to choose whether a semantic call should fail completely, or to + * return partial results. */ public final class SemanticErrorMode extends ExpandableStringEnum { /** - * If the semantic processing fails, partial results still return. The definition of partial results depends on what - * semantic step failed and what was the reason for failure. + * If the semantic processing fails, partial results still return. The definition + * of partial results depends on what semantic step failed and what was the reason + * for failure. */ + @Generated public static final SemanticErrorMode PARTIAL = fromString("partial"); /** - * If there is an exception during the semantic processing step, the query will fail and return the appropriate HTTP - * code depending on the error. + * If there is an exception during the semantic processing step, the query will + * fail and return the appropriate HTTP code depending on the error. */ + @Generated public static final SemanticErrorMode FAIL = fromString("fail"); /** @@ -30,6 +33,7 @@ public final class SemanticErrorMode extends ExpandableStringEnum values() { return values(SemanticErrorMode.class); } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SemanticErrorReason.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SemanticErrorReason.java index a544340ef302..9edc2f2b8989 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SemanticErrorReason.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SemanticErrorReason.java @@ -1,11 +1,10 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.search.documents.models; +import com.azure.core.annotation.Generated; import com.azure.core.util.ExpandableStringEnum; import java.util.Collection; @@ -14,19 +13,22 @@ */ public final class SemanticErrorReason extends ExpandableStringEnum { /** - * If `semanticMaxWaitInMilliseconds` was set and the semantic processing duration exceeded that value. Only the - * base results were returned. + * If `semanticMaxWaitInMilliseconds` was set and the semantic processing duration + * exceeded that value. Only the base results were returned. */ + @Generated public static final SemanticErrorReason MAX_WAIT_EXCEEDED = fromString("maxWaitExceeded"); /** * The request was throttled. Only the base results were returned. */ + @Generated public static final SemanticErrorReason CAPACITY_OVERLOADED = fromString("capacityOverloaded"); /** * At least one step of the semantic process failed. */ + @Generated public static final SemanticErrorReason TRANSIENT = fromString("transient"); /** @@ -34,6 +36,7 @@ public final class SemanticErrorReason extends ExpandableStringEnum values() { return values(SemanticErrorReason.class); } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/SemanticField.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SemanticField.java similarity index 79% rename from sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/SemanticField.java rename to sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SemanticField.java index c174d8aa528b..a7419b2d2ffd 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/SemanticField.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SemanticField.java @@ -1,11 +1,10 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) TypeSpec Code Generator. -package com.azure.search.documents.indexes.models; +package com.azure.search.documents.models; +import com.azure.core.annotation.Generated; import com.azure.core.annotation.Immutable; import com.azure.json.JsonReader; import com.azure.json.JsonSerializable; @@ -19,8 +18,9 @@ @Immutable public final class SemanticField implements JsonSerializable { /* - * The fieldName property. + * File name */ + @Generated private final String fieldName; /** @@ -28,15 +28,17 @@ public final class SemanticField implements JsonSerializable { * * @param fieldName the fieldName value to set. */ + @Generated public SemanticField(String fieldName) { this.fieldName = fieldName; } /** - * Get the fieldName property: The fieldName property. + * Get the fieldName property: File name. * * @return the fieldName value. */ + @Generated public String getFieldName() { return this.fieldName; } @@ -44,6 +46,7 @@ public String getFieldName() { /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); @@ -60,9 +63,9 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { * @throws IllegalStateException If the deserialized JSON object was missing any required properties. * @throws IOException If an error occurs while reading the SemanticField. */ + @Generated public static SemanticField fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { - boolean fieldNameFound = false; String fieldName = null; while (reader.nextToken() != JsonToken.END_OBJECT) { String jsonFieldName = reader.getFieldName(); @@ -70,15 +73,11 @@ public static SemanticField fromJson(JsonReader jsonReader) throws IOException { if ("fieldName".equals(jsonFieldName)) { fieldName = reader.getString(); - fieldNameFound = true; } else { reader.skipChildren(); } } - if (fieldNameFound) { - return new SemanticField(fieldName); - } - throw new IllegalStateException("Missing required property: fieldName"); + return new SemanticField(fieldName); }); } } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SemanticFieldState.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SemanticFieldState.java index f382b4b908b1..fe92a464cc65 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SemanticFieldState.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SemanticFieldState.java @@ -1,11 +1,10 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.search.documents.models; +import com.azure.core.annotation.Generated; import com.azure.core.util.ExpandableStringEnum; import java.util.Collection; @@ -16,16 +15,19 @@ public final class SemanticFieldState extends ExpandableStringEnum values() { return values(SemanticFieldState.class); } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/SemanticPrioritizedFields.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SemanticPrioritizedFields.java similarity index 61% rename from sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/SemanticPrioritizedFields.java rename to sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SemanticPrioritizedFields.java index 58f9c75c9d82..40b48c54f5e7 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/SemanticPrioritizedFields.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SemanticPrioritizedFields.java @@ -1,94 +1,107 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. -package com.azure.search.documents.indexes.models; +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.search.documents.models; import com.azure.core.annotation.Fluent; +import com.azure.core.annotation.Generated; import com.azure.json.JsonReader; import com.azure.json.JsonSerializable; import com.azure.json.JsonToken; import com.azure.json.JsonWriter; import java.io.IOException; -import java.util.Arrays; import java.util.List; /** - * Describes the title, content, and keywords fields to be used for semantic ranking, captions, highlights, and answers. + * Describes the title, content, and keywords fields to be used for semantic + * ranking, captions, highlights, and answers. */ @Fluent public final class SemanticPrioritizedFields implements JsonSerializable { - /* - * 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. + * 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. */ + @Generated private SemanticField titleField; /* - * 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. + * 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. */ + @Generated private List contentFields; /* - * 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. + * 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. */ + @Generated private List keywordsFields; /** * Creates an instance of SemanticPrioritizedFields class. */ + @Generated public SemanticPrioritizedFields() { } /** - * Get the titleField property: 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. - * + * Get the titleField property: 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. + * * @return the titleField value. */ + @Generated public SemanticField getTitleField() { return this.titleField; } /** - * Set the titleField property: 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. - * + * Set the titleField property: 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. + * * @param titleField the titleField value to set. * @return the SemanticPrioritizedFields object itself. */ + @Generated public SemanticPrioritizedFields setTitleField(SemanticField titleField) { this.titleField = titleField; return this; } /** - * Get the contentFields property: 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. - * + * Get the contentFields property: 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. + * * @return the contentFields value. */ + @Generated public List getContentFields() { return this.contentFields; } /** - * Set the contentFields property: 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. - * + * Set the contentFields property: 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. + * * @param contentFields the contentFields value to set. * @return the SemanticPrioritizedFields object itself. */ + @Generated public SemanticPrioritizedFields setContentFields(List contentFields) { this.contentFields = contentFields; return this; @@ -96,25 +109,29 @@ public SemanticPrioritizedFields setContentFields(List contentFie /** * Get the keywordsFields property: 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 + * 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. - * + * * @return the keywordsFields value. */ + @Generated public List getKeywordsFields() { return this.keywordsFields; } /** * Set the keywordsFields property: 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 + * 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. - * + * * @param keywordsFields the keywordsFields value to set. * @return the SemanticPrioritizedFields object itself. */ + @Generated public SemanticPrioritizedFields setKeywordsFields(List keywordsFields) { this.keywordsFields = keywordsFields; return this; @@ -123,6 +140,7 @@ public SemanticPrioritizedFields setKeywordsFields(List keywordsF /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); @@ -136,18 +154,20 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of SemanticPrioritizedFields from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of SemanticPrioritizedFields if the JsonReader was pointing to an instance of it, or null if * it was pointing to JSON null. * @throws IOException If an error occurs while reading the SemanticPrioritizedFields. */ + @Generated public static SemanticPrioritizedFields fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { SemanticPrioritizedFields deserializedSemanticPrioritizedFields = new SemanticPrioritizedFields(); while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); + if ("titleField".equals(fieldName)) { deserializedSemanticPrioritizedFields.titleField = SemanticField.fromJson(reader); } else if ("prioritizedContentFields".equals(fieldName)) { @@ -160,35 +180,8 @@ public static SemanticPrioritizedFields fromJson(JsonReader jsonReader) throws I reader.skipChildren(); } } + return deserializedSemanticPrioritizedFields; }); } - - /** - * Set the contentFields property: 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. - * - * @param contentFields the contentFields value to set. - * @return the SemanticPrioritizedFields object itself. - */ - public SemanticPrioritizedFields setContentFields(SemanticField... contentFields) { - this.contentFields = (contentFields == null) ? null : Arrays.asList(contentFields); - return this; - } - - /** - * Set the keywordsFields property: 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. - * - * @param keywordsFields the keywordsFields value to set. - * @return the SemanticPrioritizedFields object itself. - */ - public SemanticPrioritizedFields setKeywordsFields(SemanticField... keywordsFields) { - this.keywordsFields = (keywordsFields == null) ? null : Arrays.asList(keywordsFields); - return this; - } } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SemanticQueryRewritesResultType.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SemanticQueryRewritesResultType.java index d7323109b2f3..cf3546ca8ad7 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SemanticQueryRewritesResultType.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SemanticQueryRewritesResultType.java @@ -1,11 +1,10 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.search.documents.models; +import com.azure.core.annotation.Generated; import com.azure.core.util.ExpandableStringEnum; import java.util.Collection; @@ -14,9 +13,10 @@ */ public final class SemanticQueryRewritesResultType extends ExpandableStringEnum { /** - * Query rewrites were not successfully generated for this request. Only the original query was used to retrieve the - * results. + * Query rewrites were not successfully generated for this request. Only the + * original query was used to retrieve the results. */ + @Generated public static final SemanticQueryRewritesResultType ORIGINAL_QUERY_ONLY = fromString("originalQueryOnly"); /** @@ -24,6 +24,7 @@ public final class SemanticQueryRewritesResultType extends ExpandableStringEnum< * * @deprecated Use the {@link #fromString(String)} factory method. */ + @Generated @Deprecated public SemanticQueryRewritesResultType() { } @@ -34,6 +35,7 @@ public SemanticQueryRewritesResultType() { * @param name a name to look for. * @return the corresponding SemanticQueryRewritesResultType. */ + @Generated public static SemanticQueryRewritesResultType fromString(String name) { return fromString(name, SemanticQueryRewritesResultType.class); } @@ -43,6 +45,7 @@ public static SemanticQueryRewritesResultType fromString(String name) { * * @return known SemanticQueryRewritesResultType values. */ + @Generated public static Collection values() { return values(SemanticQueryRewritesResultType.class); } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/SemanticSearch.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SemanticSearch.java similarity index 88% rename from sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/SemanticSearch.java rename to sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SemanticSearch.java index 63adb8b6bb2e..a3dca5046638 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/SemanticSearch.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SemanticSearch.java @@ -1,12 +1,11 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) TypeSpec Code Generator. -package com.azure.search.documents.indexes.models; +package com.azure.search.documents.models; import com.azure.core.annotation.Fluent; +import com.azure.core.annotation.Generated; import com.azure.json.JsonReader; import com.azure.json.JsonSerializable; import com.azure.json.JsonToken; @@ -20,39 +19,46 @@ @Fluent public final class SemanticSearch implements JsonSerializable { /* - * 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. + * 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. */ + @Generated private String defaultConfigurationName; /* * The semantic configurations for the index. */ + @Generated private List configurations; /** * Creates an instance of SemanticSearch class. */ + @Generated public SemanticSearch() { } /** * Get the defaultConfigurationName property: 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. + * index, + * making it optional to pass it on as a query parameter every time. * * @return the defaultConfigurationName value. */ + @Generated public String getDefaultConfigurationName() { return this.defaultConfigurationName; } /** * Set the defaultConfigurationName property: 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. + * index, + * making it optional to pass it on as a query parameter every time. * * @param defaultConfigurationName the defaultConfigurationName value to set. * @return the SemanticSearch object itself. */ + @Generated public SemanticSearch setDefaultConfigurationName(String defaultConfigurationName) { this.defaultConfigurationName = defaultConfigurationName; return this; @@ -63,6 +69,7 @@ public SemanticSearch setDefaultConfigurationName(String defaultConfigurationNam * * @return the configurations value. */ + @Generated public List getConfigurations() { return this.configurations; } @@ -73,6 +80,7 @@ public List getConfigurations() { * @param configurations the configurations value to set. * @return the SemanticSearch object itself. */ + @Generated public SemanticSearch setConfigurations(List configurations) { this.configurations = configurations; return this; @@ -81,6 +89,7 @@ public SemanticSearch setConfigurations(List configuratio /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); @@ -98,6 +107,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { * pointing to JSON null. * @throws IOException If an error occurs while reading the SemanticSearch. */ + @Generated public static SemanticSearch fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { SemanticSearch deserializedSemanticSearch = new SemanticSearch(); diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SemanticSearchOptions.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SemanticSearchOptions.java deleted file mode 100644 index 108daaf48e09..000000000000 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SemanticSearchOptions.java +++ /dev/null @@ -1,248 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -package com.azure.search.documents.models; - -import java.time.Duration; - -/** - * Parameters for performing vector searches. - */ -public final class SemanticSearchOptions { - /* - * The name of the semantic configuration that lists which fields should be - * used for semantic ranking, captions, highlights, and answers - */ - private String semanticConfigurationName; - - /* - * Allows the user to choose whether a semantic call should fail completely, or to return partial results. - */ - private SemanticErrorMode errorMode; - - /* - * 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. - */ - private Duration maxWaitDuration; - - /* - * 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-<number of - * answers>' 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-<confidence 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-<number of maximum character length>', - * such as 'extractive|maxcharlength-600'. - */ - private QueryAnswer queryAnswer; - - /* - * 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-<true/false>' 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-<number of maximum character length>', such as 'extractive|maxcharlength-600'. - */ - private QueryCaption queryCaption; - - /* - * 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. - */ - private String semanticQuery; - - /* - * 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-<number of rewrites>` option, such as `generative|count-3`. - * Defaults to `None`. This parameter is only valid if the query type is `semantic`. - */ - private QueryRewrites queryRewrites; - - /** - * Creates a new instance of {@link SemanticSearchOptions}. - */ - public SemanticSearchOptions() { - } - - /** - * Get the semanticConfigurationName property: The name of the semantic configuration that lists which fields should - * be used for semantic ranking, captions, highlights, and answers. - * - * @return the semanticConfigurationName value. - */ - public String getSemanticConfigurationName() { - return this.semanticConfigurationName; - } - - /** - * Set the semanticConfigurationName property: The name of the semantic configuration that lists which fields should - * be used for semantic ranking, captions, highlights, and answers. - * - * @param semanticConfigurationName the semanticConfigurationName value to set. - * @return the SemanticSearchOptions object itself. - */ - public SemanticSearchOptions setSemanticConfigurationName(String semanticConfigurationName) { - this.semanticConfigurationName = semanticConfigurationName; - return this; - } - - /** - * Get the semanticErrorHandling property: Allows the user to choose whether a semantic call should fail completely, - * or to return partial results. - * - * @return the semanticErrorHandling value. - */ - public SemanticErrorMode getErrorMode() { - return this.errorMode; - } - - /** - * Set the semanticErrorHandling property: Allows the user to choose whether a semantic call should fail completely, - * or to return partial results. - * - * @param errorMode the semanticErrorHandling value to set. - * @return the SemanticSearchOptions object itself. - */ - public SemanticSearchOptions setErrorMode(SemanticErrorMode errorMode) { - this.errorMode = errorMode; - return this; - } - - /** - * Get the semanticMaxWaitInMilliseconds property: 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. - * - * @return the semanticMaxWaitDuration value. - */ - public Duration getMaxWaitDuration() { - return this.maxWaitDuration; - } - - /** - * Set the semanticMaxWaitDuration property: 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. - * - * @param maxWaitDuration the semanticMaxWaitInMilliseconds value to set. - * @return the SemanticSearchOptions object itself. - */ - public SemanticSearchOptions setMaxWaitDuration(Duration maxWaitDuration) { - this.maxWaitDuration = maxWaitDuration; - return this; - } - - /** - * Get the answers property: 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-<number of answers>' 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-<confidence threshold>' option - * after the answers parameter value, such as 'extractive|threshold-0.9'. Default threshold is 0.7. - * - * @return the answers value. - */ - public QueryAnswer getQueryAnswer() { - return this.queryAnswer; - } - - /** - * Set the answers property: 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-<number of answers>' 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-<confidence threshold>' option - * after the answers parameter value, such as 'extractive|threshold-0.9'. Default threshold is 0.7. - * - * @param queryAnswer the answers value to set. - * @return the SemanticSearchOptions object itself. - */ - public SemanticSearchOptions setQueryAnswer(QueryAnswer queryAnswer) { - this.queryAnswer = queryAnswer; - return this; - } - - /** - * Get the query caption property: 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-<true/false>' option, such as 'extractive|highlight-true'. Defaults to 'None'. - * - * @return the query caption value. - */ - public QueryCaption getQueryCaption() { - return this.queryCaption; - } - - /** - * Set the query caption property: 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-<true/false>' option, such as 'extractive|highlight-true'. Defaults to 'None'. - * - * @param queryCaption the query caption value to set. - * @return the SemanticSearchOptions object itself. - */ - public SemanticSearchOptions setQueryCaption(QueryCaption queryCaption) { - this.queryCaption = queryCaption; - return this; - } - - /** - * Get the semanticQuery property: 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. - * - * @return the semanticQuery value. - */ - public String getSemanticQuery() { - return this.semanticQuery; - } - - /** - * Set the semanticQuery property: 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. - * - * @param semanticQuery the semanticQuery value to set. - * @return the SemanticSearchOptions object itself. - */ - public SemanticSearchOptions setSemanticQuery(String semanticQuery) { - this.semanticQuery = semanticQuery; - return this; - } - - /** - * Get the queryRewrites property: 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-<number of rewrites>` option, such - * as `generative|count-3`. Defaults to `None`. This parameter is only valid if the query type is `semantic`. - * - * @return the queryRewrites value. - */ - public QueryRewrites getQueryRewrites() { - return this.queryRewrites; - } - - /** - * Set the queryRewrites property: 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-<number of rewrites>` option, such - * as `generative|count-3`. Defaults to `None`. This parameter is only valid if the query type is `semantic`. - * - * @param queryRewrites the queryRewrites value to set. - * @return the SemanticSearchOptions object itself. - */ - public SemanticSearchOptions setQueryRewrites(QueryRewrites queryRewrites) { - this.queryRewrites = queryRewrites; - return this; - } -} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SemanticSearchResult.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SemanticSearchResult.java deleted file mode 100644 index ff4a5179a3e3..000000000000 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SemanticSearchResult.java +++ /dev/null @@ -1,49 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -package com.azure.search.documents.models; - -import java.util.List; - -/** - * The document-level results for a {@link QueryType#SEMANTIC semantic} search. - */ -public final class SemanticSearchResult { - /* - * 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. - */ - private final Double rerankerScore; - - /* - * Captions are the most representative passages from the document relatively to the search query. They are often - * used as document summary. - */ - private final List queryCaptions; - - SemanticSearchResult(Double rerankerScore, List queryCaptions) { - this.rerankerScore = rerankerScore; - this.queryCaptions = queryCaptions; - } - - /** - * Get the rerankerScore property: 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'. - * - * @return the rerankerScore value. - */ - public Double getRerankerScore() { - return this.rerankerScore; - } - - /** - * Get the queryCaptions property: 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'. - * - * @return the captions value. - */ - public List getQueryCaptions() { - return this.queryCaptions; - } -} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SemanticSearchResults.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SemanticSearchResults.java deleted file mode 100644 index 8295e56aaff0..000000000000 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SemanticSearchResults.java +++ /dev/null @@ -1,69 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -package com.azure.search.documents.models; - -import com.azure.search.documents.implementation.util.SearchPagedResponseAccessHelper; -import com.azure.search.documents.implementation.util.SemanticSearchResultsAccessHelper; -import com.azure.search.documents.util.SearchPagedResponse; - -import java.util.List; - -/** - * The page-level results for a {@link QueryType#SEMANTIC semantic} search. - */ -public final class SemanticSearchResults { - private final List queryAnswers; - private final SemanticErrorReason errorReason; - private final SemanticSearchResultsType resultsType; - private final SemanticQueryRewritesResultType semanticQueryRewritesResultType; - - static { - SemanticSearchResultsAccessHelper.setAccessor(SemanticSearchResults::new); - } - - private SemanticSearchResults(SearchPagedResponse pagedResponse) { - this.queryAnswers = SearchPagedResponseAccessHelper.getQueryAnswers(pagedResponse); - this.errorReason = SearchPagedResponseAccessHelper.getSemanticErrorReason(pagedResponse); - this.resultsType = SearchPagedResponseAccessHelper.getSemanticSearchResultsType(pagedResponse); - this.semanticQueryRewritesResultType - = SearchPagedResponseAccessHelper.getSemanticQueryRewritesResultType(pagedResponse); - } - - /** - * The answer results based on the search request. - *

- * If {@code answers} wasn't supplied in the request this will be null. - * - * @return The answer results if {@code answers} were supplied in the request, otherwise null. - */ - public List getQueryAnswers() { - return this.queryAnswers; - } - - /** - * The reason for a partial result returned by Azure AI Search. - * - * @return The reason for a partial result returned by Azure AI Search. - */ - public SemanticErrorReason getErrorReason() { - return this.errorReason; - } - - /** - * The type of the partial result returned by Azure AI Search. - * - * @return The type of the partial result returned by Azure AI Search. - */ - public SemanticSearchResultsType getResultsType() { - return this.resultsType; - } - - /** - * Type of query rewrite that was used for this request. - * - * @return The type of query rewrite that was used for this request. - */ - public SemanticQueryRewritesResultType getSemanticQueryRewritesResultType() { - return this.semanticQueryRewritesResultType; - } -} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SemanticSearchResultsType.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SemanticSearchResultsType.java index c934a927056d..6c6a6fb2e49e 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SemanticSearchResultsType.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SemanticSearchResultsType.java @@ -1,11 +1,10 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.search.documents.models; +import com.azure.core.annotation.Generated; import com.azure.core.util.ExpandableStringEnum; import java.util.Collection; @@ -16,12 +15,15 @@ public final class SemanticSearchResultsType extends ExpandableStringEnum values() { return values(SemanticSearchResultsType.class); } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/implementation/models/SentimentSkillV1.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SentimentSkill.java similarity index 63% rename from sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/implementation/models/SentimentSkillV1.java rename to sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SentimentSkill.java index b2582aadef98..099c9c4f5b46 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/implementation/models/SentimentSkillV1.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SentimentSkill.java @@ -1,53 +1,51 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) TypeSpec Code Generator. -package com.azure.search.documents.indexes.implementation.models; +package com.azure.search.documents.models; import com.azure.core.annotation.Fluent; +import com.azure.core.annotation.Generated; import com.azure.json.JsonReader; import com.azure.json.JsonToken; import com.azure.json.JsonWriter; -import com.azure.search.documents.indexes.models.InputFieldMappingEntry; -import com.azure.search.documents.indexes.models.OutputFieldMappingEntry; -import com.azure.search.documents.indexes.models.SearchIndexerSkill; -import com.azure.search.documents.indexes.models.SentimentSkillLanguage; import java.io.IOException; -import java.util.ArrayList; import java.util.List; /** * This skill is deprecated. Use the V3.SentimentSkill instead. */ @Fluent -public final class SentimentSkillV1 extends SearchIndexerSkill { +public final class SentimentSkill extends SearchIndexerSkill { /* - * A URI fragment specifying the type of skill. + * The discriminator for derived types. */ + @Generated private String odataType = "#Microsoft.Skills.Text.SentimentSkill"; /* * A value indicating which language code to use. Default is `en`. */ + @Generated private SentimentSkillLanguage defaultLanguageCode; /** - * Creates an instance of SentimentSkillV1 class. + * Creates an instance of SentimentSkill class. * * @param inputs the inputs value to set. * @param outputs the outputs value to set. */ - public SentimentSkillV1(List inputs, List outputs) { + @Generated + public SentimentSkill(List inputs, List outputs) { super(inputs, outputs); } /** - * Get the odataType property: A URI fragment specifying the type of skill. + * Get the odataType property: The discriminator for derived types. * * @return the odataType value. */ + @Generated @Override public String getOdataType() { return this.odataType; @@ -58,6 +56,7 @@ public String getOdataType() { * * @return the defaultLanguageCode value. */ + @Generated public SentimentSkillLanguage getDefaultLanguageCode() { return this.defaultLanguageCode; } @@ -66,9 +65,10 @@ public SentimentSkillLanguage getDefaultLanguageCode() { * Set the defaultLanguageCode property: A value indicating which language code to use. Default is `en`. * * @param defaultLanguageCode the defaultLanguageCode value to set. - * @return the SentimentSkillV1 object itself. + * @return the SentimentSkill object itself. */ - public SentimentSkillV1 setDefaultLanguageCode(SentimentSkillLanguage defaultLanguageCode) { + @Generated + public SentimentSkill setDefaultLanguageCode(SentimentSkillLanguage defaultLanguageCode) { this.defaultLanguageCode = defaultLanguageCode; return this; } @@ -76,8 +76,9 @@ public SentimentSkillV1 setDefaultLanguageCode(SentimentSkillLanguage defaultLan /** * {@inheritDoc} */ + @Generated @Override - public SentimentSkillV1 setName(String name) { + public SentimentSkill setName(String name) { super.setName(name); return this; } @@ -85,8 +86,9 @@ public SentimentSkillV1 setName(String name) { /** * {@inheritDoc} */ + @Generated @Override - public SentimentSkillV1 setDescription(String description) { + public SentimentSkill setDescription(String description) { super.setDescription(description); return this; } @@ -94,8 +96,9 @@ public SentimentSkillV1 setDescription(String description) { /** * {@inheritDoc} */ + @Generated @Override - public SentimentSkillV1 setContext(String context) { + public SentimentSkill setContext(String context) { super.setContext(context); return this; } @@ -103,6 +106,7 @@ public SentimentSkillV1 setContext(String context) { /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); @@ -118,19 +122,18 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { } /** - * Reads an instance of SentimentSkillV1 from the JsonReader. + * Reads an instance of SentimentSkill from the JsonReader. * * @param jsonReader The JsonReader being read. - * @return An instance of SentimentSkillV1 if the JsonReader was pointing to an instance of it, or null if it was + * @return An instance of SentimentSkill if the JsonReader was pointing to an instance of it, or null if it was * pointing to JSON null. * @throws IllegalStateException If the deserialized JSON object was missing any required properties. - * @throws IOException If an error occurs while reading the SentimentSkillV1. + * @throws IOException If an error occurs while reading the SentimentSkill. */ - public static SentimentSkillV1 fromJson(JsonReader jsonReader) throws IOException { + @Generated + public static SentimentSkill fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { - boolean inputsFound = false; List inputs = null; - boolean outputsFound = false; List outputs = null; String name = null; String description = null; @@ -143,10 +146,8 @@ public static SentimentSkillV1 fromJson(JsonReader jsonReader) throws IOExceptio if ("inputs".equals(fieldName)) { inputs = reader.readArray(reader1 -> InputFieldMappingEntry.fromJson(reader1)); - inputsFound = true; } else if ("outputs".equals(fieldName)) { outputs = reader.readArray(reader1 -> OutputFieldMappingEntry.fromJson(reader1)); - outputsFound = true; } else if ("name".equals(fieldName)) { name = reader.getString(); } else if ("description".equals(fieldName)) { @@ -161,26 +162,14 @@ public static SentimentSkillV1 fromJson(JsonReader jsonReader) throws IOExceptio reader.skipChildren(); } } - if (inputsFound && outputsFound) { - SentimentSkillV1 deserializedSentimentSkillV1 = new SentimentSkillV1(inputs, outputs); - deserializedSentimentSkillV1.setName(name); - deserializedSentimentSkillV1.setDescription(description); - deserializedSentimentSkillV1.setContext(context); - deserializedSentimentSkillV1.odataType = odataType; - deserializedSentimentSkillV1.defaultLanguageCode = defaultLanguageCode; - - return deserializedSentimentSkillV1; - } - List missingProperties = new ArrayList<>(); - if (!inputsFound) { - missingProperties.add("inputs"); - } - if (!outputsFound) { - missingProperties.add("outputs"); - } - - throw new IllegalStateException( - "Missing required property/properties: " + String.join(", ", missingProperties)); + SentimentSkill deserializedSentimentSkill = new SentimentSkill(inputs, outputs); + deserializedSentimentSkill.setName(name); + deserializedSentimentSkill.setDescription(description); + deserializedSentimentSkill.setContext(context); + deserializedSentimentSkill.odataType = odataType; + deserializedSentimentSkill.defaultLanguageCode = defaultLanguageCode; + + return deserializedSentimentSkill; }); } } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/SentimentSkillLanguage.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SentimentSkillLanguage.java similarity index 86% rename from sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/SentimentSkillLanguage.java rename to sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SentimentSkillLanguage.java index 01e665cda6a8..ffa19feb06f4 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/SentimentSkillLanguage.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SentimentSkillLanguage.java @@ -1,11 +1,10 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) TypeSpec Code Generator. -package com.azure.search.documents.indexes.models; +package com.azure.search.documents.models; +import com.azure.core.annotation.Generated; import com.azure.core.util.ExpandableStringEnum; import java.util.Collection; @@ -16,76 +15,91 @@ public final class SentimentSkillLanguage extends ExpandableStringEnum values() { return values(SentimentSkillLanguage.class); } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/implementation/models/SentimentSkillV3.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SentimentSkillV3.java similarity index 70% rename from sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/implementation/models/SentimentSkillV3.java rename to sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SentimentSkillV3.java index ed244a5c5ddb..9c902439cbc4 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/implementation/models/SentimentSkillV3.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SentimentSkillV3.java @@ -1,49 +1,51 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) TypeSpec Code Generator. -package com.azure.search.documents.indexes.implementation.models; +package com.azure.search.documents.models; import com.azure.core.annotation.Fluent; +import com.azure.core.annotation.Generated; import com.azure.json.JsonReader; import com.azure.json.JsonToken; import com.azure.json.JsonWriter; -import com.azure.search.documents.indexes.models.InputFieldMappingEntry; -import com.azure.search.documents.indexes.models.OutputFieldMappingEntry; -import com.azure.search.documents.indexes.models.SearchIndexerSkill; import java.io.IOException; -import java.util.ArrayList; import java.util.List; /** - * 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 + * 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. */ @Fluent public final class SentimentSkillV3 extends SearchIndexerSkill { /* - * A URI fragment specifying the type of skill. + * The discriminator for derived types. */ + @Generated private String odataType = "#Microsoft.Skills.Text.V3.SentimentSkill"; /* * A value indicating which language code to use. Default is `en`. */ + @Generated private String defaultLanguageCode; /* - * 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. + * 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. */ + @Generated private Boolean includeOpinionMining; /* - * 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. + * 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. */ + @Generated private String modelVersion; /** @@ -52,15 +54,17 @@ public final class SentimentSkillV3 extends SearchIndexerSkill { * @param inputs the inputs value to set. * @param outputs the outputs value to set. */ + @Generated public SentimentSkillV3(List inputs, List outputs) { super(inputs, outputs); } /** - * Get the odataType property: A URI fragment specifying the type of skill. + * Get the odataType property: The discriminator for derived types. * * @return the odataType value. */ + @Generated @Override public String getOdataType() { return this.odataType; @@ -71,6 +75,7 @@ public String getOdataType() { * * @return the defaultLanguageCode value. */ + @Generated public String getDefaultLanguageCode() { return this.defaultLanguageCode; } @@ -81,6 +86,7 @@ public String getDefaultLanguageCode() { * @param defaultLanguageCode the defaultLanguageCode value to set. * @return the SentimentSkillV3 object itself. */ + @Generated public SentimentSkillV3 setDefaultLanguageCode(String defaultLanguageCode) { this.defaultLanguageCode = defaultLanguageCode; return this; @@ -88,47 +94,53 @@ public SentimentSkillV3 setDefaultLanguageCode(String defaultLanguageCode) { /** * Get the includeOpinionMining property: 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. + * Analytics + * for opinion mining, namely targets (nouns or verbs) and their associated + * assessment (adjective) in the text. Default is false. * * @return the includeOpinionMining value. */ + @Generated public Boolean isIncludeOpinionMining() { return this.includeOpinionMining; } /** * Set the includeOpinionMining property: 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. + * Analytics + * for opinion mining, namely targets (nouns or verbs) and their associated + * assessment (adjective) in the text. Default is false. * * @param includeOpinionMining the includeOpinionMining value to set. * @return the SentimentSkillV3 object itself. */ + @Generated public SentimentSkillV3 setIncludeOpinionMining(Boolean includeOpinionMining) { this.includeOpinionMining = includeOpinionMining; return this; } /** - * Get the modelVersion property: 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. + * Get the modelVersion property: 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. * * @return the modelVersion value. */ + @Generated public String getModelVersion() { return this.modelVersion; } /** - * Set the modelVersion property: 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. + * Set the modelVersion property: 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. * * @param modelVersion the modelVersion value to set. * @return the SentimentSkillV3 object itself. */ + @Generated public SentimentSkillV3 setModelVersion(String modelVersion) { this.modelVersion = modelVersion; return this; @@ -137,6 +149,7 @@ public SentimentSkillV3 setModelVersion(String modelVersion) { /** * {@inheritDoc} */ + @Generated @Override public SentimentSkillV3 setName(String name) { super.setName(name); @@ -146,6 +159,7 @@ public SentimentSkillV3 setName(String name) { /** * {@inheritDoc} */ + @Generated @Override public SentimentSkillV3 setDescription(String description) { super.setDescription(description); @@ -155,6 +169,7 @@ public SentimentSkillV3 setDescription(String description) { /** * {@inheritDoc} */ + @Generated @Override public SentimentSkillV3 setContext(String context) { super.setContext(context); @@ -164,6 +179,7 @@ public SentimentSkillV3 setContext(String context) { /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); @@ -188,11 +204,10 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { * @throws IllegalStateException If the deserialized JSON object was missing any required properties. * @throws IOException If an error occurs while reading the SentimentSkillV3. */ + @Generated public static SentimentSkillV3 fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { - boolean inputsFound = false; List inputs = null; - boolean outputsFound = false; List outputs = null; String name = null; String description = null; @@ -207,10 +222,8 @@ public static SentimentSkillV3 fromJson(JsonReader jsonReader) throws IOExceptio if ("inputs".equals(fieldName)) { inputs = reader.readArray(reader1 -> InputFieldMappingEntry.fromJson(reader1)); - inputsFound = true; } else if ("outputs".equals(fieldName)) { outputs = reader.readArray(reader1 -> OutputFieldMappingEntry.fromJson(reader1)); - outputsFound = true; } else if ("name".equals(fieldName)) { name = reader.getString(); } else if ("description".equals(fieldName)) { @@ -229,28 +242,16 @@ public static SentimentSkillV3 fromJson(JsonReader jsonReader) throws IOExceptio reader.skipChildren(); } } - if (inputsFound && outputsFound) { - SentimentSkillV3 deserializedSentimentSkillV3 = new SentimentSkillV3(inputs, outputs); - deserializedSentimentSkillV3.setName(name); - deserializedSentimentSkillV3.setDescription(description); - deserializedSentimentSkillV3.setContext(context); - deserializedSentimentSkillV3.odataType = odataType; - deserializedSentimentSkillV3.defaultLanguageCode = defaultLanguageCode; - deserializedSentimentSkillV3.includeOpinionMining = includeOpinionMining; - deserializedSentimentSkillV3.modelVersion = modelVersion; + SentimentSkillV3 deserializedSentimentSkillV3 = new SentimentSkillV3(inputs, outputs); + deserializedSentimentSkillV3.setName(name); + deserializedSentimentSkillV3.setDescription(description); + deserializedSentimentSkillV3.setContext(context); + deserializedSentimentSkillV3.odataType = odataType; + deserializedSentimentSkillV3.defaultLanguageCode = defaultLanguageCode; + deserializedSentimentSkillV3.includeOpinionMining = includeOpinionMining; + deserializedSentimentSkillV3.modelVersion = modelVersion; - return deserializedSentimentSkillV3; - } - List missingProperties = new ArrayList<>(); - if (!inputsFound) { - missingProperties.add("inputs"); - } - if (!outputsFound) { - missingProperties.add("outputs"); - } - - throw new IllegalStateException( - "Missing required property/properties: " + String.join(", ", missingProperties)); + return deserializedSentimentSkillV3; }); } } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/ShaperSkill.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/ShaperSkill.java similarity index 73% rename from sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/ShaperSkill.java rename to sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/ShaperSkill.java index a083f8cf4bce..a6034a6eca8d 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/ShaperSkill.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/ShaperSkill.java @@ -1,28 +1,27 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) TypeSpec Code Generator. -package com.azure.search.documents.indexes.models; +package com.azure.search.documents.models; import com.azure.core.annotation.Fluent; +import com.azure.core.annotation.Generated; import com.azure.json.JsonReader; import com.azure.json.JsonToken; import com.azure.json.JsonWriter; import java.io.IOException; -import java.util.ArrayList; import java.util.List; /** - * A skill for reshaping the outputs. It creates a complex type to support composite fields (also known as multipart - * fields). + * A skill for reshaping the outputs. It creates a complex type to support + * composite fields (also known as multipart fields). */ @Fluent public final class ShaperSkill extends SearchIndexerSkill { /* - * A URI fragment specifying the type of skill. + * The discriminator for derived types. */ + @Generated private String odataType = "#Microsoft.Skills.Util.ShaperSkill"; /** @@ -31,15 +30,17 @@ public final class ShaperSkill extends SearchIndexerSkill { * @param inputs the inputs value to set. * @param outputs the outputs value to set. */ + @Generated public ShaperSkill(List inputs, List outputs) { super(inputs, outputs); } /** - * Get the odataType property: A URI fragment specifying the type of skill. + * Get the odataType property: The discriminator for derived types. * * @return the odataType value. */ + @Generated @Override public String getOdataType() { return this.odataType; @@ -48,6 +49,7 @@ public String getOdataType() { /** * {@inheritDoc} */ + @Generated @Override public ShaperSkill setName(String name) { super.setName(name); @@ -57,6 +59,7 @@ public ShaperSkill setName(String name) { /** * {@inheritDoc} */ + @Generated @Override public ShaperSkill setDescription(String description) { super.setDescription(description); @@ -66,6 +69,7 @@ public ShaperSkill setDescription(String description) { /** * {@inheritDoc} */ + @Generated @Override public ShaperSkill setContext(String context) { super.setContext(context); @@ -75,6 +79,7 @@ public ShaperSkill setContext(String context) { /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); @@ -96,11 +101,10 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { * @throws IllegalStateException If the deserialized JSON object was missing any required properties. * @throws IOException If an error occurs while reading the ShaperSkill. */ + @Generated public static ShaperSkill fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { - boolean inputsFound = false; List inputs = null; - boolean outputsFound = false; List outputs = null; String name = null; String description = null; @@ -112,10 +116,8 @@ public static ShaperSkill fromJson(JsonReader jsonReader) throws IOException { if ("inputs".equals(fieldName)) { inputs = reader.readArray(reader1 -> InputFieldMappingEntry.fromJson(reader1)); - inputsFound = true; } else if ("outputs".equals(fieldName)) { outputs = reader.readArray(reader1 -> OutputFieldMappingEntry.fromJson(reader1)); - outputsFound = true; } else if ("name".equals(fieldName)) { name = reader.getString(); } else if ("description".equals(fieldName)) { @@ -128,25 +130,13 @@ public static ShaperSkill fromJson(JsonReader jsonReader) throws IOException { reader.skipChildren(); } } - if (inputsFound && outputsFound) { - ShaperSkill deserializedShaperSkill = new ShaperSkill(inputs, outputs); - deserializedShaperSkill.setName(name); - deserializedShaperSkill.setDescription(description); - deserializedShaperSkill.setContext(context); - deserializedShaperSkill.odataType = odataType; + ShaperSkill deserializedShaperSkill = new ShaperSkill(inputs, outputs); + deserializedShaperSkill.setName(name); + deserializedShaperSkill.setDescription(description); + deserializedShaperSkill.setContext(context); + deserializedShaperSkill.odataType = odataType; - return deserializedShaperSkill; - } - List missingProperties = new ArrayList<>(); - if (!inputsFound) { - missingProperties.add("inputs"); - } - if (!outputsFound) { - missingProperties.add("outputs"); - } - - throw new IllegalStateException( - "Missing required property/properties: " + String.join(", ", missingProperties)); + return deserializedShaperSkill; }); } } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/ShingleTokenFilter.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/ShingleTokenFilter.java similarity index 78% rename from sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/ShingleTokenFilter.java rename to sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/ShingleTokenFilter.java index 04d8fd94e0ff..6235bc790310 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/ShingleTokenFilter.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/ShingleTokenFilter.java @@ -1,73 +1,86 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. -package com.azure.search.documents.indexes.models; +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.search.documents.models; import com.azure.core.annotation.Fluent; +import com.azure.core.annotation.Generated; import com.azure.json.JsonReader; import com.azure.json.JsonToken; import com.azure.json.JsonWriter; import java.io.IOException; /** - * Creates combinations of tokens as a single token. This token filter is implemented using Apache Lucene. + * Creates combinations of tokens as a single token. This token filter is + * implemented using Apache Lucene. */ @Fluent public final class ShingleTokenFilter extends TokenFilter { - /* - * A URI fragment specifying the type of token filter. + * The discriminator for derived types. */ + @Generated private String odataType = "#Microsoft.Azure.Search.ShingleTokenFilter"; /* * The maximum shingle size. Default and minimum value is 2. */ + @Generated private Integer maxShingleSize; /* - * The minimum shingle size. Default and minimum value is 2. Must be less than the value of maxShingleSize. + * The minimum shingle size. Default and minimum value is 2. Must be less than the + * value of maxShingleSize. */ + @Generated private Integer minShingleSize; /* - * A value indicating whether the output stream will contain the input tokens (unigrams) as well as shingles. - * Default is true. + * A value indicating whether the output stream will contain the input tokens + * (unigrams) as well as shingles. Default is true. */ + @Generated private Boolean outputUnigrams; /* - * 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. + * 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. */ + @Generated private Boolean outputUnigramsIfNoShingles; /* - * The string to use when joining adjacent tokens to form a shingle. Default is a single space (" "). + * The string to use when joining adjacent tokens to form a shingle. Default is a + * single space (" "). */ + @Generated private String tokenSeparator; /* - * The string to insert for each position at which there is no token. Default is an underscore ("_"). + * The string to insert for each position at which there is no token. Default is + * an underscore ("_"). */ + @Generated private String filterToken; /** * Creates an instance of ShingleTokenFilter class. - * + * * @param name the name value to set. */ + @Generated public ShingleTokenFilter(String name) { super(name); } /** - * Get the odataType property: A URI fragment specifying the type of token filter. - * + * Get the odataType property: The discriminator for derived types. + * * @return the odataType value. */ + @Generated @Override public String getOdataType() { return this.odataType; @@ -75,19 +88,21 @@ public String getOdataType() { /** * Get the maxShingleSize property: The maximum shingle size. Default and minimum value is 2. - * + * * @return the maxShingleSize value. */ + @Generated public Integer getMaxShingleSize() { return this.maxShingleSize; } /** * Set the maxShingleSize property: The maximum shingle size. Default and minimum value is 2. - * + * * @param maxShingleSize the maxShingleSize value to set. * @return the ShingleTokenFilter object itself. */ + @Generated public ShingleTokenFilter setMaxShingleSize(Integer maxShingleSize) { this.maxShingleSize = maxShingleSize; return this; @@ -96,9 +111,10 @@ public ShingleTokenFilter setMaxShingleSize(Integer maxShingleSize) { /** * Get the minShingleSize property: The minimum shingle size. Default and minimum value is 2. Must be less than the * value of maxShingleSize. - * + * * @return the minShingleSize value. */ + @Generated public Integer getMinShingleSize() { return this.minShingleSize; } @@ -106,10 +122,11 @@ public Integer getMinShingleSize() { /** * Set the minShingleSize property: The minimum shingle size. Default and minimum value is 2. Must be less than the * value of maxShingleSize. - * + * * @param minShingleSize the minShingleSize value to set. * @return the ShingleTokenFilter object itself. */ + @Generated public ShingleTokenFilter setMinShingleSize(Integer minShingleSize) { this.minShingleSize = minShingleSize; return this; @@ -118,20 +135,22 @@ public ShingleTokenFilter setMinShingleSize(Integer minShingleSize) { /** * Get the outputUnigrams property: A value indicating whether the output stream will contain the input tokens * (unigrams) as well as shingles. Default is true. - * + * * @return the outputUnigrams value. */ - public Boolean areOutputUnigrams() { + @Generated + public Boolean isOutputUnigrams() { return this.outputUnigrams; } /** * Set the outputUnigrams property: A value indicating whether the output stream will contain the input tokens * (unigrams) as well as shingles. Default is true. - * + * * @param outputUnigrams the outputUnigrams value to set. * @return the ShingleTokenFilter object itself. */ + @Generated public ShingleTokenFilter setOutputUnigrams(Boolean outputUnigrams) { this.outputUnigrams = outputUnigrams; return this; @@ -139,21 +158,27 @@ public ShingleTokenFilter setOutputUnigrams(Boolean outputUnigrams) { /** * Get the outputUnigramsIfNoShingles property: 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. - * + * no shingles + * are available. This property takes precedence when outputUnigrams is set to + * false. Default is false. + * * @return the outputUnigramsIfNoShingles value. */ - public Boolean areOutputUnigramsIfNoShingles() { + @Generated + public Boolean isOutputUnigramsIfNoShingles() { return this.outputUnigramsIfNoShingles; } /** * Set the outputUnigramsIfNoShingles property: 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. - * + * no shingles + * are available. This property takes precedence when outputUnigrams is set to + * false. Default is false. + * * @param outputUnigramsIfNoShingles the outputUnigramsIfNoShingles value to set. * @return the ShingleTokenFilter object itself. */ + @Generated public ShingleTokenFilter setOutputUnigramsIfNoShingles(Boolean outputUnigramsIfNoShingles) { this.outputUnigramsIfNoShingles = outputUnigramsIfNoShingles; return this; @@ -162,9 +187,10 @@ public ShingleTokenFilter setOutputUnigramsIfNoShingles(Boolean outputUnigramsIf /** * Get the tokenSeparator property: The string to use when joining adjacent tokens to form a shingle. Default is a * single space (" "). - * + * * @return the tokenSeparator value. */ + @Generated public String getTokenSeparator() { return this.tokenSeparator; } @@ -172,32 +198,35 @@ public String getTokenSeparator() { /** * Set the tokenSeparator property: The string to use when joining adjacent tokens to form a shingle. Default is a * single space (" "). - * + * * @param tokenSeparator the tokenSeparator value to set. * @return the ShingleTokenFilter object itself. */ + @Generated public ShingleTokenFilter setTokenSeparator(String tokenSeparator) { this.tokenSeparator = tokenSeparator; return this; } /** - * Get the filterToken property: The string to insert for each position at which there is no token. Default is an - * underscore ("_"). - * + * Get the filterToken property: The string to insert for each position at which there is no token. Default is + * an underscore ("_"). + * * @return the filterToken value. */ + @Generated public String getFilterToken() { return this.filterToken; } /** - * Set the filterToken property: The string to insert for each position at which there is no token. Default is an - * underscore ("_"). - * + * Set the filterToken property: The string to insert for each position at which there is no token. Default is + * an underscore ("_"). + * * @param filterToken the filterToken value to set. * @return the ShingleTokenFilter object itself. */ + @Generated public ShingleTokenFilter setFilterToken(String filterToken) { this.filterToken = filterToken; return this; @@ -206,6 +235,7 @@ public ShingleTokenFilter setFilterToken(String filterToken) { /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); @@ -222,16 +252,16 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of ShingleTokenFilter from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of ShingleTokenFilter if the JsonReader was pointing to an instance of it, or null if it was * pointing to JSON null. * @throws IllegalStateException If the deserialized JSON object was missing any required properties. * @throws IOException If an error occurs while reading the ShingleTokenFilter. */ + @Generated public static ShingleTokenFilter fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { - boolean nameFound = false; String name = null; String odataType = "#Microsoft.Azure.Search.ShingleTokenFilter"; Integer maxShingleSize = null; @@ -243,9 +273,9 @@ public static ShingleTokenFilter fromJson(JsonReader jsonReader) throws IOExcept while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); + if ("name".equals(fieldName)) { name = reader.getString(); - nameFound = true; } else if ("@odata.type".equals(fieldName)) { odataType = reader.getString(); } else if ("maxShingleSize".equals(fieldName)) { @@ -264,18 +294,16 @@ public static ShingleTokenFilter fromJson(JsonReader jsonReader) throws IOExcept reader.skipChildren(); } } - if (nameFound) { - ShingleTokenFilter deserializedShingleTokenFilter = new ShingleTokenFilter(name); - deserializedShingleTokenFilter.odataType = odataType; - deserializedShingleTokenFilter.maxShingleSize = maxShingleSize; - deserializedShingleTokenFilter.minShingleSize = minShingleSize; - deserializedShingleTokenFilter.outputUnigrams = outputUnigrams; - deserializedShingleTokenFilter.outputUnigramsIfNoShingles = outputUnigramsIfNoShingles; - deserializedShingleTokenFilter.tokenSeparator = tokenSeparator; - deserializedShingleTokenFilter.filterToken = filterToken; - return deserializedShingleTokenFilter; - } - throw new IllegalStateException("Missing required property: name"); + ShingleTokenFilter deserializedShingleTokenFilter = new ShingleTokenFilter(name); + deserializedShingleTokenFilter.odataType = odataType; + deserializedShingleTokenFilter.maxShingleSize = maxShingleSize; + deserializedShingleTokenFilter.minShingleSize = minShingleSize; + deserializedShingleTokenFilter.outputUnigrams = outputUnigrams; + deserializedShingleTokenFilter.outputUnigramsIfNoShingles = outputUnigramsIfNoShingles; + deserializedShingleTokenFilter.tokenSeparator = tokenSeparator; + deserializedShingleTokenFilter.filterToken = filterToken; + + return deserializedShingleTokenFilter; }); } } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/SimilarityAlgorithm.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SimilarityAlgorithm.java similarity index 86% rename from sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/SimilarityAlgorithm.java rename to sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SimilarityAlgorithm.java index 1b938fe483fd..c988ff6623d6 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/SimilarityAlgorithm.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SimilarityAlgorithm.java @@ -1,11 +1,10 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) TypeSpec Code Generator. -package com.azure.search.documents.indexes.models; +package com.azure.search.documents.models; +import com.azure.core.annotation.Generated; import com.azure.core.annotation.Immutable; import com.azure.json.JsonReader; import com.azure.json.JsonSerializable; @@ -14,28 +13,32 @@ import java.io.IOException; /** - * 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. + * 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. */ @Immutable public class SimilarityAlgorithm implements JsonSerializable { /* - * The @odata.type property. + * The discriminator for derived types. */ + @Generated private String odataType = "SimilarityAlgorithm"; /** * Creates an instance of SimilarityAlgorithm class. */ + @Generated public SimilarityAlgorithm() { } /** - * Get the odataType property: The @odata.type property. + * Get the odataType property: The discriminator for derived types. * * @return the odataType value. */ + @Generated public String getOdataType() { return this.odataType; } @@ -43,6 +46,7 @@ public String getOdataType() { /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); @@ -58,6 +62,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { * pointing to JSON null. * @throws IOException If an error occurs while reading the SimilarityAlgorithm. */ + @Generated public static SimilarityAlgorithm fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { String discriminatorValue = null; @@ -85,6 +90,7 @@ public static SimilarityAlgorithm fromJson(JsonReader jsonReader) throws IOExcep }); } + @Generated static SimilarityAlgorithm fromJsonKnownDiscriminator(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { SimilarityAlgorithm deserializedSimilarityAlgorithm = new SimilarityAlgorithm(); diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SingleVectorFieldResult.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SingleVectorFieldResult.java index c1838844dbbe..be52ee5e485b 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SingleVectorFieldResult.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SingleVectorFieldResult.java @@ -1,11 +1,10 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.search.documents.models; +import com.azure.core.annotation.Generated; import com.azure.core.annotation.Immutable; import com.azure.json.JsonReader; import com.azure.json.JsonSerializable; @@ -14,27 +13,31 @@ import java.io.IOException; /** - * A single vector field result. Both @search.score and vector similarity values are returned. Vector similarity is - * related to @search.score by an equation. + * A single vector field result. Both @search.score and vector similarity values + * are returned. Vector similarity is related to @search.score by an equation. */ @Immutable public final class SingleVectorFieldResult implements JsonSerializable { /* - * 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. + * 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. */ + @Generated private Double searchScore; /* - * 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. + * 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. */ + @Generated private Double vectorSimilarity; /** * Creates an instance of SingleVectorFieldResult class. */ - public SingleVectorFieldResult() { + @Generated + private SingleVectorFieldResult() { } /** @@ -43,17 +46,19 @@ public SingleVectorFieldResult() { * * @return the searchScore value. */ + @Generated public Double getSearchScore() { return this.searchScore; } /** * Get the vectorSimilarity property: 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. + * definition of similarity metric, not the 'distance' version. For example, + * cosine similarity instead of cosine distance. * * @return the vectorSimilarity value. */ + @Generated public Double getVectorSimilarity() { return this.vectorSimilarity; } @@ -61,6 +66,7 @@ public Double getVectorSimilarity() { /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); @@ -75,6 +81,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { * was pointing to JSON null. * @throws IOException If an error occurs while reading the SingleVectorFieldResult. */ + @Generated public static SingleVectorFieldResult fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { SingleVectorFieldResult deserializedSingleVectorFieldResult = new SingleVectorFieldResult(); diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/implementation/models/SkillNames.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SkillNames.java similarity index 90% rename from sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/implementation/models/SkillNames.java rename to sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SkillNames.java index 4a5bd4b8a70d..620be6e5f808 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/implementation/models/SkillNames.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SkillNames.java @@ -1,12 +1,11 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) TypeSpec Code Generator. -package com.azure.search.documents.indexes.implementation.models; +package com.azure.search.documents.models; import com.azure.core.annotation.Fluent; +import com.azure.core.annotation.Generated; import com.azure.json.JsonReader; import com.azure.json.JsonSerializable; import com.azure.json.JsonToken; @@ -15,18 +14,20 @@ import java.util.List; /** - * The SkillNames model. + * The type of the skill names. */ @Fluent public final class SkillNames implements JsonSerializable { /* * the names of skills to be reset. */ + @Generated private List skillNames; /** * Creates an instance of SkillNames class. */ + @Generated public SkillNames() { } @@ -35,6 +36,7 @@ public SkillNames() { * * @return the skillNames value. */ + @Generated public List getSkillNames() { return this.skillNames; } @@ -45,6 +47,7 @@ public List getSkillNames() { * @param skillNames the skillNames value to set. * @return the SkillNames object itself. */ + @Generated public SkillNames setSkillNames(List skillNames) { this.skillNames = skillNames; return this; @@ -53,6 +56,7 @@ public SkillNames setSkillNames(List skillNames) { /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); @@ -68,6 +72,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { * to JSON null. * @throws IOException If an error occurs while reading the SkillNames. */ + @Generated public static SkillNames fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { SkillNames deserializedSkillNames = new SkillNames(); diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/SnowballTokenFilter.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SnowballTokenFilter.java similarity index 70% rename from sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/SnowballTokenFilter.java rename to sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SnowballTokenFilter.java index 07cfcc46b2bb..0dec9f5e90e5 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/SnowballTokenFilter.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SnowballTokenFilter.java @@ -1,32 +1,32 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) TypeSpec Code Generator. -package com.azure.search.documents.indexes.models; +package com.azure.search.documents.models; +import com.azure.core.annotation.Generated; import com.azure.core.annotation.Immutable; import com.azure.json.JsonReader; import com.azure.json.JsonToken; import com.azure.json.JsonWriter; import java.io.IOException; -import java.util.ArrayList; -import java.util.List; /** - * A filter that stems words using a Snowball-generated stemmer. This token filter is implemented using Apache Lucene. + * A filter that stems words using a Snowball-generated stemmer. This token filter + * is implemented using Apache Lucene. */ @Immutable public final class SnowballTokenFilter extends TokenFilter { /* - * A URI fragment specifying the type of token filter. + * The discriminator for derived types. */ + @Generated private String odataType = "#Microsoft.Azure.Search.SnowballTokenFilter"; /* * The language to use. */ + @Generated private final SnowballTokenFilterLanguage language; /** @@ -35,16 +35,18 @@ public final class SnowballTokenFilter extends TokenFilter { * @param name the name value to set. * @param language the language value to set. */ + @Generated public SnowballTokenFilter(String name, SnowballTokenFilterLanguage language) { super(name); this.language = language; } /** - * Get the odataType property: A URI fragment specifying the type of token filter. + * Get the odataType property: The discriminator for derived types. * * @return the odataType value. */ + @Generated @Override public String getOdataType() { return this.odataType; @@ -55,6 +57,7 @@ public String getOdataType() { * * @return the language value. */ + @Generated public SnowballTokenFilterLanguage getLanguage() { return this.language; } @@ -62,6 +65,7 @@ public SnowballTokenFilterLanguage getLanguage() { /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); @@ -80,11 +84,10 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { * @throws IllegalStateException If the deserialized JSON object was missing any required properties. * @throws IOException If an error occurs while reading the SnowballTokenFilter. */ + @Generated public static SnowballTokenFilter fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { - boolean nameFound = false; String name = null; - boolean languageFound = false; SnowballTokenFilterLanguage language = null; String odataType = "#Microsoft.Azure.Search.SnowballTokenFilter"; while (reader.nextToken() != JsonToken.END_OBJECT) { @@ -93,32 +96,18 @@ public static SnowballTokenFilter fromJson(JsonReader jsonReader) throws IOExcep if ("name".equals(fieldName)) { name = reader.getString(); - nameFound = true; } else if ("language".equals(fieldName)) { language = SnowballTokenFilterLanguage.fromString(reader.getString()); - languageFound = true; } else if ("@odata.type".equals(fieldName)) { odataType = reader.getString(); } else { reader.skipChildren(); } } - if (nameFound && languageFound) { - SnowballTokenFilter deserializedSnowballTokenFilter = new SnowballTokenFilter(name, language); - deserializedSnowballTokenFilter.odataType = odataType; + SnowballTokenFilter deserializedSnowballTokenFilter = new SnowballTokenFilter(name, language); + deserializedSnowballTokenFilter.odataType = odataType; - return deserializedSnowballTokenFilter; - } - List missingProperties = new ArrayList<>(); - if (!nameFound) { - missingProperties.add("name"); - } - if (!languageFound) { - missingProperties.add("language"); - } - - throw new IllegalStateException( - "Missing required property/properties: " + String.join(", ", missingProperties)); + return deserializedSnowballTokenFilter; }); } } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SnowballTokenFilterLanguage.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SnowballTokenFilterLanguage.java new file mode 100644 index 000000000000..5753728fdcaf --- /dev/null +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SnowballTokenFilterLanguage.java @@ -0,0 +1,181 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.search.documents.models; + +import com.azure.core.annotation.Generated; +import com.azure.core.util.ExpandableStringEnum; +import java.util.Collection; + +/** + * The language to use for a Snowball token filter. + */ +public final class SnowballTokenFilterLanguage extends ExpandableStringEnum { + /** + * Selects the Lucene Snowball stemming tokenizer for Armenian. + */ + @Generated + public static final SnowballTokenFilterLanguage ARMENIAN = fromString("armenian"); + + /** + * Selects the Lucene Snowball stemming tokenizer for Basque. + */ + @Generated + public static final SnowballTokenFilterLanguage BASQUE = fromString("basque"); + + /** + * Selects the Lucene Snowball stemming tokenizer for Catalan. + */ + @Generated + public static final SnowballTokenFilterLanguage CATALAN = fromString("catalan"); + + /** + * Selects the Lucene Snowball stemming tokenizer for Danish. + */ + @Generated + public static final SnowballTokenFilterLanguage DANISH = fromString("danish"); + + /** + * Selects the Lucene Snowball stemming tokenizer for Dutch. + */ + @Generated + public static final SnowballTokenFilterLanguage DUTCH = fromString("dutch"); + + /** + * Selects the Lucene Snowball stemming tokenizer for English. + */ + @Generated + public static final SnowballTokenFilterLanguage ENGLISH = fromString("english"); + + /** + * Selects the Lucene Snowball stemming tokenizer for Finnish. + */ + @Generated + public static final SnowballTokenFilterLanguage FINNISH = fromString("finnish"); + + /** + * Selects the Lucene Snowball stemming tokenizer for French. + */ + @Generated + public static final SnowballTokenFilterLanguage FRENCH = fromString("french"); + + /** + * Selects the Lucene Snowball stemming tokenizer for German. + */ + @Generated + public static final SnowballTokenFilterLanguage GERMAN = fromString("german"); + + /** + * Selects the Lucene Snowball stemming tokenizer that uses the German variant + * algorithm. + */ + @Generated + public static final SnowballTokenFilterLanguage GERMAN2 = fromString("german2"); + + /** + * Selects the Lucene Snowball stemming tokenizer for Hungarian. + */ + @Generated + public static final SnowballTokenFilterLanguage HUNGARIAN = fromString("hungarian"); + + /** + * Selects the Lucene Snowball stemming tokenizer for Italian. + */ + @Generated + public static final SnowballTokenFilterLanguage ITALIAN = fromString("italian"); + + /** + * Selects the Lucene Snowball stemming tokenizer for Dutch that uses the + * Kraaij-Pohlmann stemming algorithm. + */ + @Generated + public static final SnowballTokenFilterLanguage KP = fromString("kp"); + + /** + * Selects the Lucene Snowball stemming tokenizer for English that uses the Lovins + * stemming algorithm. + */ + @Generated + public static final SnowballTokenFilterLanguage LOVINS = fromString("lovins"); + + /** + * Selects the Lucene Snowball stemming tokenizer for Norwegian. + */ + @Generated + public static final SnowballTokenFilterLanguage NORWEGIAN = fromString("norwegian"); + + /** + * Selects the Lucene Snowball stemming tokenizer for English that uses the Porter + * stemming algorithm. + */ + @Generated + public static final SnowballTokenFilterLanguage PORTER = fromString("porter"); + + /** + * Selects the Lucene Snowball stemming tokenizer for Portuguese. + */ + @Generated + public static final SnowballTokenFilterLanguage PORTUGUESE = fromString("portuguese"); + + /** + * Selects the Lucene Snowball stemming tokenizer for Romanian. + */ + @Generated + public static final SnowballTokenFilterLanguage ROMANIAN = fromString("romanian"); + + /** + * Selects the Lucene Snowball stemming tokenizer for Russian. + */ + @Generated + public static final SnowballTokenFilterLanguage RUSSIAN = fromString("russian"); + + /** + * Selects the Lucene Snowball stemming tokenizer for Spanish. + */ + @Generated + public static final SnowballTokenFilterLanguage SPANISH = fromString("spanish"); + + /** + * Selects the Lucene Snowball stemming tokenizer for Swedish. + */ + @Generated + public static final SnowballTokenFilterLanguage SWEDISH = fromString("swedish"); + + /** + * Selects the Lucene Snowball stemming tokenizer for Turkish. + */ + @Generated + public static final SnowballTokenFilterLanguage TURKISH = fromString("turkish"); + + /** + * Creates a new instance of SnowballTokenFilterLanguage value. + * + * @deprecated Use the {@link #fromString(String)} factory method. + */ + @Generated + @Deprecated + public SnowballTokenFilterLanguage() { + } + + /** + * Creates or finds a SnowballTokenFilterLanguage from its string representation. + * + * @param name a name to look for. + * @return the corresponding SnowballTokenFilterLanguage. + */ + @Generated + public static SnowballTokenFilterLanguage fromString(String name) { + return fromString(name, SnowballTokenFilterLanguage.class); + } + + /** + * Gets known SnowballTokenFilterLanguage values. + * + * @return known SnowballTokenFilterLanguage values. + */ + @Generated + public static Collection values() { + return values(SnowballTokenFilterLanguage.class); + } +} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/SoftDeleteColumnDeletionDetectionPolicy.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SoftDeleteColumnDeletionDetectionPolicy.java similarity index 89% rename from sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/SoftDeleteColumnDeletionDetectionPolicy.java rename to sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SoftDeleteColumnDeletionDetectionPolicy.java index 18cde2832c20..9b9df1475c6a 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/SoftDeleteColumnDeletionDetectionPolicy.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SoftDeleteColumnDeletionDetectionPolicy.java @@ -1,49 +1,54 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) TypeSpec Code Generator. -package com.azure.search.documents.indexes.models; +package com.azure.search.documents.models; import com.azure.core.annotation.Fluent; +import com.azure.core.annotation.Generated; import com.azure.json.JsonReader; import com.azure.json.JsonToken; import com.azure.json.JsonWriter; import java.io.IOException; /** - * 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. + * 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. */ @Fluent public final class SoftDeleteColumnDeletionDetectionPolicy extends DataDeletionDetectionPolicy { /* - * A URI fragment specifying the type of data deletion detection policy. + * The discriminator for derived types. */ + @Generated private String odataType = "#Microsoft.Azure.Search.SoftDeleteColumnDeletionDetectionPolicy"; /* * The name of the column to use for soft-deletion detection. */ + @Generated private String softDeleteColumnName; /* * The marker value that identifies an item as deleted. */ + @Generated private String softDeleteMarkerValue; /** * Creates an instance of SoftDeleteColumnDeletionDetectionPolicy class. */ + @Generated public SoftDeleteColumnDeletionDetectionPolicy() { } /** - * Get the odataType property: A URI fragment specifying the type of data deletion detection policy. + * Get the odataType property: The discriminator for derived types. * * @return the odataType value. */ + @Generated @Override public String getOdataType() { return this.odataType; @@ -54,6 +59,7 @@ public String getOdataType() { * * @return the softDeleteColumnName value. */ + @Generated public String getSoftDeleteColumnName() { return this.softDeleteColumnName; } @@ -64,6 +70,7 @@ public String getSoftDeleteColumnName() { * @param softDeleteColumnName the softDeleteColumnName value to set. * @return the SoftDeleteColumnDeletionDetectionPolicy object itself. */ + @Generated public SoftDeleteColumnDeletionDetectionPolicy setSoftDeleteColumnName(String softDeleteColumnName) { this.softDeleteColumnName = softDeleteColumnName; return this; @@ -74,6 +81,7 @@ public SoftDeleteColumnDeletionDetectionPolicy setSoftDeleteColumnName(String so * * @return the softDeleteMarkerValue value. */ + @Generated public String getSoftDeleteMarkerValue() { return this.softDeleteMarkerValue; } @@ -84,6 +92,7 @@ public String getSoftDeleteMarkerValue() { * @param softDeleteMarkerValue the softDeleteMarkerValue value to set. * @return the SoftDeleteColumnDeletionDetectionPolicy object itself. */ + @Generated public SoftDeleteColumnDeletionDetectionPolicy setSoftDeleteMarkerValue(String softDeleteMarkerValue) { this.softDeleteMarkerValue = softDeleteMarkerValue; return this; @@ -92,6 +101,7 @@ public SoftDeleteColumnDeletionDetectionPolicy setSoftDeleteMarkerValue(String s /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); @@ -109,6 +119,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { * it, or null if it was pointing to JSON null. * @throws IOException If an error occurs while reading the SoftDeleteColumnDeletionDetectionPolicy. */ + @Generated public static SoftDeleteColumnDeletionDetectionPolicy fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { SoftDeleteColumnDeletionDetectionPolicy deserializedSoftDeleteColumnDeletionDetectionPolicy diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/SplitSkill.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SplitSkill.java similarity index 74% rename from sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/SplitSkill.java rename to sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SplitSkill.java index 77f4b3192ab3..bd8b37a2795c 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/SplitSkill.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SplitSkill.java @@ -1,17 +1,15 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) TypeSpec Code Generator. -package com.azure.search.documents.indexes.models; +package com.azure.search.documents.models; import com.azure.core.annotation.Fluent; +import com.azure.core.annotation.Generated; import com.azure.json.JsonReader; import com.azure.json.JsonToken; import com.azure.json.JsonWriter; import java.io.IOException; -import java.util.ArrayList; import java.util.List; /** @@ -20,50 +18,60 @@ @Fluent public final class SplitSkill extends SearchIndexerSkill { /* - * A URI fragment specifying the type of skill. + * The discriminator for derived types. */ + @Generated private String odataType = "#Microsoft.Skills.Text.SplitSkill"; /* * A value indicating which language code to use. Default is `en`. */ + @Generated private SplitSkillLanguage defaultLanguageCode; /* * A value indicating which split mode to perform. */ + @Generated private TextSplitMode textSplitMode; /* * The desired maximum page length. Default is 10000. */ + @Generated private Integer maximumPageLength; /* - * 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. + * 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. */ + @Generated private Integer pageOverlapLength; /* - * 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. + * 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. */ + @Generated private Integer maximumPagesToTake; /* - * 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. + * 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. */ + @Generated private SplitSkillUnit unit; /* - * 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. + * 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. */ + @Generated private AzureOpenAITokenizerParameters azureOpenAITokenizerParameters; /** @@ -72,15 +80,17 @@ public final class SplitSkill extends SearchIndexerSkill { * @param inputs the inputs value to set. * @param outputs the outputs value to set. */ + @Generated public SplitSkill(List inputs, List outputs) { super(inputs, outputs); } /** - * Get the odataType property: A URI fragment specifying the type of skill. + * Get the odataType property: The discriminator for derived types. * * @return the odataType value. */ + @Generated @Override public String getOdataType() { return this.odataType; @@ -91,6 +101,7 @@ public String getOdataType() { * * @return the defaultLanguageCode value. */ + @Generated public SplitSkillLanguage getDefaultLanguageCode() { return this.defaultLanguageCode; } @@ -101,6 +112,7 @@ public SplitSkillLanguage getDefaultLanguageCode() { * @param defaultLanguageCode the defaultLanguageCode value to set. * @return the SplitSkill object itself. */ + @Generated public SplitSkill setDefaultLanguageCode(SplitSkillLanguage defaultLanguageCode) { this.defaultLanguageCode = defaultLanguageCode; return this; @@ -111,6 +123,7 @@ public SplitSkill setDefaultLanguageCode(SplitSkillLanguage defaultLanguageCode) * * @return the textSplitMode value. */ + @Generated public TextSplitMode getTextSplitMode() { return this.textSplitMode; } @@ -121,6 +134,7 @@ public TextSplitMode getTextSplitMode() { * @param textSplitMode the textSplitMode value to set. * @return the SplitSkill object itself. */ + @Generated public SplitSkill setTextSplitMode(TextSplitMode textSplitMode) { this.textSplitMode = textSplitMode; return this; @@ -131,6 +145,7 @@ public SplitSkill setTextSplitMode(TextSplitMode textSplitMode) { * * @return the maximumPageLength value. */ + @Generated public Integer getMaximumPageLength() { return this.maximumPageLength; } @@ -141,6 +156,7 @@ public Integer getMaximumPageLength() { * @param maximumPageLength the maximumPageLength value to set. * @return the SplitSkill object itself. */ + @Generated public SplitSkill setMaximumPageLength(Integer maximumPageLength) { this.maximumPageLength = maximumPageLength; return this; @@ -148,21 +164,25 @@ public SplitSkill setMaximumPageLength(Integer maximumPageLength) { /** * Get the pageOverlapLength property: 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. + * chunk + * will start with this number of characters/tokens from the end of the nth chunk. * * @return the pageOverlapLength value. */ + @Generated public Integer getPageOverlapLength() { return this.pageOverlapLength; } /** * Set the pageOverlapLength property: 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. + * chunk + * will start with this number of characters/tokens from the end of the nth chunk. * * @param pageOverlapLength the pageOverlapLength value to set. * @return the SplitSkill object itself. */ + @Generated public SplitSkill setPageOverlapLength(Integer pageOverlapLength) { this.pageOverlapLength = pageOverlapLength; return this; @@ -170,47 +190,55 @@ public SplitSkill setPageOverlapLength(Integer pageOverlapLength) { /** * Get the maximumPagesToTake property: 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. + * 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. * * @return the maximumPagesToTake value. */ + @Generated public Integer getMaximumPagesToTake() { return this.maximumPagesToTake; } /** * Set the maximumPagesToTake property: 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. + * 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. * * @param maximumPagesToTake the maximumPagesToTake value to set. * @return the SplitSkill object itself. */ + @Generated public SplitSkill setMaximumPagesToTake(Integer maximumPagesToTake) { this.maximumPagesToTake = maximumPagesToTake; return this; } /** - * Get the unit property: 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. + * Get the unit property: 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. * * @return the unit value. */ + @Generated public SplitSkillUnit getUnit() { return this.unit; } /** - * Set the unit property: 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. + * Set the unit property: 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. * * @param unit the unit value to set. * @return the SplitSkill object itself. */ + @Generated public SplitSkill setUnit(SplitSkillUnit unit) { this.unit = unit; return this; @@ -218,23 +246,27 @@ public SplitSkill setUnit(SplitSkillUnit unit) { /** * Get the azureOpenAITokenizerParameters property: 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. + * specified, the + * splitSkill will use these parameters when performing the tokenization. The + * parameters are a valid 'encoderModelName' and an optional 'allowedSpecialTokens' property. * * @return the azureOpenAITokenizerParameters value. */ + @Generated public AzureOpenAITokenizerParameters getAzureOpenAITokenizerParameters() { return this.azureOpenAITokenizerParameters; } /** * Set the azureOpenAITokenizerParameters property: 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. + * specified, the + * splitSkill will use these parameters when performing the tokenization. The + * parameters are a valid 'encoderModelName' and an optional 'allowedSpecialTokens' property. * * @param azureOpenAITokenizerParameters the azureOpenAITokenizerParameters value to set. * @return the SplitSkill object itself. */ + @Generated public SplitSkill setAzureOpenAITokenizerParameters(AzureOpenAITokenizerParameters azureOpenAITokenizerParameters) { this.azureOpenAITokenizerParameters = azureOpenAITokenizerParameters; return this; @@ -243,6 +275,7 @@ public SplitSkill setAzureOpenAITokenizerParameters(AzureOpenAITokenizerParamete /** * {@inheritDoc} */ + @Generated @Override public SplitSkill setName(String name) { super.setName(name); @@ -252,6 +285,7 @@ public SplitSkill setName(String name) { /** * {@inheritDoc} */ + @Generated @Override public SplitSkill setDescription(String description) { super.setDescription(description); @@ -261,6 +295,7 @@ public SplitSkill setDescription(String description) { /** * {@inheritDoc} */ + @Generated @Override public SplitSkill setContext(String context) { super.setContext(context); @@ -270,6 +305,7 @@ public SplitSkill setContext(String context) { /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); @@ -299,11 +335,10 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { * @throws IllegalStateException If the deserialized JSON object was missing any required properties. * @throws IOException If an error occurs while reading the SplitSkill. */ + @Generated public static SplitSkill fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { - boolean inputsFound = false; List inputs = null; - boolean outputsFound = false; List outputs = null; String name = null; String description = null; @@ -322,10 +357,8 @@ public static SplitSkill fromJson(JsonReader jsonReader) throws IOException { if ("inputs".equals(fieldName)) { inputs = reader.readArray(reader1 -> InputFieldMappingEntry.fromJson(reader1)); - inputsFound = true; } else if ("outputs".equals(fieldName)) { outputs = reader.readArray(reader1 -> OutputFieldMappingEntry.fromJson(reader1)); - outputsFound = true; } else if ("name".equals(fieldName)) { name = reader.getString(); } else if ("description".equals(fieldName)) { @@ -352,32 +385,20 @@ public static SplitSkill fromJson(JsonReader jsonReader) throws IOException { reader.skipChildren(); } } - if (inputsFound && outputsFound) { - SplitSkill deserializedSplitSkill = new SplitSkill(inputs, outputs); - deserializedSplitSkill.setName(name); - deserializedSplitSkill.setDescription(description); - deserializedSplitSkill.setContext(context); - deserializedSplitSkill.odataType = odataType; - deserializedSplitSkill.defaultLanguageCode = defaultLanguageCode; - deserializedSplitSkill.textSplitMode = textSplitMode; - deserializedSplitSkill.maximumPageLength = maximumPageLength; - deserializedSplitSkill.pageOverlapLength = pageOverlapLength; - deserializedSplitSkill.maximumPagesToTake = maximumPagesToTake; - deserializedSplitSkill.unit = unit; - deserializedSplitSkill.azureOpenAITokenizerParameters = azureOpenAITokenizerParameters; - - return deserializedSplitSkill; - } - List missingProperties = new ArrayList<>(); - if (!inputsFound) { - missingProperties.add("inputs"); - } - if (!outputsFound) { - missingProperties.add("outputs"); - } - - throw new IllegalStateException( - "Missing required property/properties: " + String.join(", ", missingProperties)); + SplitSkill deserializedSplitSkill = new SplitSkill(inputs, outputs); + deserializedSplitSkill.setName(name); + deserializedSplitSkill.setDescription(description); + deserializedSplitSkill.setContext(context); + deserializedSplitSkill.odataType = odataType; + deserializedSplitSkill.defaultLanguageCode = defaultLanguageCode; + deserializedSplitSkill.textSplitMode = textSplitMode; + deserializedSplitSkill.maximumPageLength = maximumPageLength; + deserializedSplitSkill.pageOverlapLength = pageOverlapLength; + deserializedSplitSkill.maximumPagesToTake = maximumPagesToTake; + deserializedSplitSkill.unit = unit; + deserializedSplitSkill.azureOpenAITokenizerParameters = azureOpenAITokenizerParameters; + + return deserializedSplitSkill; }); } } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/SplitSkillEncoderModelName.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SplitSkillEncoderModelName.java similarity index 66% rename from sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/SplitSkillEncoderModelName.java rename to sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SplitSkillEncoderModelName.java index 52edd1078d44..96f72a952a0a 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/SplitSkillEncoderModelName.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SplitSkillEncoderModelName.java @@ -1,10 +1,10 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. -package com.azure.search.documents.indexes.models; +// Code generated by Microsoft (R) TypeSpec Code Generator. +package com.azure.search.documents.models; + +import com.azure.core.annotation.Generated; import com.azure.core.util.ExpandableStringEnum; import java.util.Collection; @@ -12,52 +12,59 @@ * A value indicating which tokenizer to use. */ public final class SplitSkillEncoderModelName extends ExpandableStringEnum { - /** - * Refers to a base model trained with a 50,000 token vocabulary, often used in general natural language processing - * tasks. + * Refers to a base model trained with a 50,000 token vocabulary, often used in + * general natural language processing tasks. */ - public static final SplitSkillEncoderModelName R_50K_BASE = fromString("r50k_base"); + @Generated + public static final SplitSkillEncoderModelName R50K_BASE = fromString("r50k_base"); /** * A base model with a 50,000 token vocabulary, optimized for prompt-based tasks. */ - public static final SplitSkillEncoderModelName P_50K_BASE = fromString("p50k_base"); + @Generated + public static final SplitSkillEncoderModelName P50K_BASE = fromString("p50k_base"); /** - * Similar to p50k_base but fine-tuned for editing or rephrasing tasks with a 50,000 token vocabulary. + * Similar to p50k_base but fine-tuned for editing or rephrasing tasks with a + * 50,000 token vocabulary. */ - public static final SplitSkillEncoderModelName P_50K_EDIT = fromString("p50k_edit"); + @Generated + public static final SplitSkillEncoderModelName P50K_EDIT = fromString("p50k_edit"); /** * A base model with a 100,000 token vocabulary. */ - public static final SplitSkillEncoderModelName CL_100K_BASE = fromString("cl100k_base"); + @Generated + public static final SplitSkillEncoderModelName CL100K_BASE = fromString("cl100k_base"); /** * Creates a new instance of SplitSkillEncoderModelName value. - * + * * @deprecated Use the {@link #fromString(String)} factory method. */ + @Generated @Deprecated public SplitSkillEncoderModelName() { } /** * Creates or finds a SplitSkillEncoderModelName from its string representation. - * + * * @param name a name to look for. * @return the corresponding SplitSkillEncoderModelName. */ + @Generated public static SplitSkillEncoderModelName fromString(String name) { return fromString(name, SplitSkillEncoderModelName.class); } /** * Gets known SplitSkillEncoderModelName values. - * + * * @return known SplitSkillEncoderModelName values. */ + @Generated public static Collection values() { return values(SplitSkillEncoderModelName.class); } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/SplitSkillLanguage.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SplitSkillLanguage.java similarity index 86% rename from sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/SplitSkillLanguage.java rename to sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SplitSkillLanguage.java index bd2c889faf0b..f255d323cd7f 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/SplitSkillLanguage.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SplitSkillLanguage.java @@ -1,11 +1,10 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) TypeSpec Code Generator. -package com.azure.search.documents.indexes.models; +package com.azure.search.documents.models; +import com.azure.core.annotation.Generated; import com.azure.core.util.ExpandableStringEnum; import java.util.Collection; @@ -16,166 +15,199 @@ public final class SplitSkillLanguage extends ExpandableStringEnum values() { return values(SplitSkillLanguage.class); } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/SplitSkillUnit.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SplitSkillUnit.java similarity index 84% rename from sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/SplitSkillUnit.java rename to sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SplitSkillUnit.java index 921df515b83e..cb28b361aef7 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/SplitSkillUnit.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SplitSkillUnit.java @@ -1,11 +1,10 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) TypeSpec Code Generator. -package com.azure.search.documents.indexes.models; +package com.azure.search.documents.models; +import com.azure.core.annotation.Generated; import com.azure.core.util.ExpandableStringEnum; import java.util.Collection; @@ -16,11 +15,14 @@ public final class SplitSkillUnit extends ExpandableStringEnum { /** * The length will be measured by character. */ + @Generated public static final SplitSkillUnit CHARACTERS = fromString("characters"); /** - * The length will be measured by an AzureOpenAI tokenizer from the tiktoken library. + * The length will be measured by an AzureOpenAI tokenizer from the tiktoken + * library. */ + @Generated public static final SplitSkillUnit AZURE_OPEN_AITOKENS = fromString("azureOpenAITokens"); /** @@ -28,6 +30,7 @@ public final class SplitSkillUnit extends ExpandableStringEnum { * * @deprecated Use the {@link #fromString(String)} factory method. */ + @Generated @Deprecated public SplitSkillUnit() { } @@ -38,6 +41,7 @@ public SplitSkillUnit() { * @param name a name to look for. * @return the corresponding SplitSkillUnit. */ + @Generated public static SplitSkillUnit fromString(String name) { return fromString(name, SplitSkillUnit.class); } @@ -47,6 +51,7 @@ public static SplitSkillUnit fromString(String name) { * * @return known SplitSkillUnit values. */ + @Generated public static Collection values() { return values(SplitSkillUnit.class); } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/SqlIntegratedChangeTrackingPolicy.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SqlIntegratedChangeTrackingPolicy.java similarity index 83% rename from sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/SqlIntegratedChangeTrackingPolicy.java rename to sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SqlIntegratedChangeTrackingPolicy.java index 9cfcbde00118..209abdf63470 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/SqlIntegratedChangeTrackingPolicy.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SqlIntegratedChangeTrackingPolicy.java @@ -1,11 +1,10 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) TypeSpec Code Generator. -package com.azure.search.documents.indexes.models; +package com.azure.search.documents.models; +import com.azure.core.annotation.Generated; import com.azure.core.annotation.Immutable; import com.azure.json.JsonReader; import com.azure.json.JsonToken; @@ -13,27 +12,30 @@ import java.io.IOException; /** - * Defines a data change detection policy that captures changes using the Integrated Change Tracking feature of Azure - * SQL Database. + * Defines a data change detection policy that captures changes using the + * Integrated Change Tracking feature of Azure SQL Database. */ @Immutable public final class SqlIntegratedChangeTrackingPolicy extends DataChangeDetectionPolicy { /* - * A URI fragment specifying the type of data change detection policy. + * The discriminator for derived types. */ + @Generated private String odataType = "#Microsoft.Azure.Search.SqlIntegratedChangeTrackingPolicy"; /** * Creates an instance of SqlIntegratedChangeTrackingPolicy class. */ + @Generated public SqlIntegratedChangeTrackingPolicy() { } /** - * Get the odataType property: A URI fragment specifying the type of data change detection policy. + * Get the odataType property: The discriminator for derived types. * * @return the odataType value. */ + @Generated @Override public String getOdataType() { return this.odataType; @@ -42,6 +44,7 @@ public String getOdataType() { /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); @@ -57,6 +60,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { * null if it was pointing to JSON null. * @throws IOException If an error occurs while reading the SqlIntegratedChangeTrackingPolicy. */ + @Generated public static SqlIntegratedChangeTrackingPolicy fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { SqlIntegratedChangeTrackingPolicy deserializedSqlIntegratedChangeTrackingPolicy diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/StemmerOverrideTokenFilter.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/StemmerOverrideTokenFilter.java similarity index 66% rename from sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/StemmerOverrideTokenFilter.java rename to sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/StemmerOverrideTokenFilter.java index b3bc46406c56..0084f68ac8a7 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/StemmerOverrideTokenFilter.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/StemmerOverrideTokenFilter.java @@ -1,34 +1,37 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) TypeSpec Code Generator. -package com.azure.search.documents.indexes.models; +package com.azure.search.documents.models; +import com.azure.core.annotation.Generated; import com.azure.core.annotation.Immutable; import com.azure.json.JsonReader; import com.azure.json.JsonToken; import com.azure.json.JsonWriter; import java.io.IOException; -import java.util.ArrayList; import java.util.List; /** - * 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. + * 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. */ @Immutable public final class StemmerOverrideTokenFilter extends TokenFilter { /* - * A URI fragment specifying the type of token filter. + * The discriminator for derived types. */ + @Generated private String odataType = "#Microsoft.Azure.Search.StemmerOverrideTokenFilter"; /* - * A list of stemming rules in the following format: "word => stem", for example: "ran => run". + * A list of stemming rules in the following format: "word => stem", for example: + * "ran => run". */ + @Generated private final List rules; /** @@ -37,27 +40,30 @@ public final class StemmerOverrideTokenFilter extends TokenFilter { * @param name the name value to set. * @param rules the rules value to set. */ + @Generated public StemmerOverrideTokenFilter(String name, List rules) { super(name); this.rules = rules; } /** - * Get the odataType property: A URI fragment specifying the type of token filter. + * Get the odataType property: The discriminator for derived types. * * @return the odataType value. */ + @Generated @Override public String getOdataType() { return this.odataType; } /** - * Get the rules property: A list of stemming rules in the following format: "word => stem", for example: "ran - * => run". + * Get the rules property: A list of stemming rules in the following format: "word => stem", for example: + * "ran => run". * * @return the rules value. */ + @Generated public List getRules() { return this.rules; } @@ -65,6 +71,7 @@ public List getRules() { /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); @@ -83,11 +90,10 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { * @throws IllegalStateException If the deserialized JSON object was missing any required properties. * @throws IOException If an error occurs while reading the StemmerOverrideTokenFilter. */ + @Generated public static StemmerOverrideTokenFilter fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { - boolean nameFound = false; String name = null; - boolean rulesFound = false; List rules = null; String odataType = "#Microsoft.Azure.Search.StemmerOverrideTokenFilter"; while (reader.nextToken() != JsonToken.END_OBJECT) { @@ -96,33 +102,19 @@ public static StemmerOverrideTokenFilter fromJson(JsonReader jsonReader) throws if ("name".equals(fieldName)) { name = reader.getString(); - nameFound = true; } else if ("rules".equals(fieldName)) { rules = reader.readArray(reader1 -> reader1.getString()); - rulesFound = true; } else if ("@odata.type".equals(fieldName)) { odataType = reader.getString(); } else { reader.skipChildren(); } } - if (nameFound && rulesFound) { - StemmerOverrideTokenFilter deserializedStemmerOverrideTokenFilter - = new StemmerOverrideTokenFilter(name, rules); - deserializedStemmerOverrideTokenFilter.odataType = odataType; + StemmerOverrideTokenFilter deserializedStemmerOverrideTokenFilter + = new StemmerOverrideTokenFilter(name, rules); + deserializedStemmerOverrideTokenFilter.odataType = odataType; - return deserializedStemmerOverrideTokenFilter; - } - List missingProperties = new ArrayList<>(); - if (!nameFound) { - missingProperties.add("name"); - } - if (!rulesFound) { - missingProperties.add("rules"); - } - - throw new IllegalStateException( - "Missing required property/properties: " + String.join(", ", missingProperties)); + return deserializedStemmerOverrideTokenFilter; }); } } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/StemmerTokenFilter.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/StemmerTokenFilter.java similarity index 71% rename from sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/StemmerTokenFilter.java rename to sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/StemmerTokenFilter.java index 21495bb224ef..a4820cbf6efe 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/StemmerTokenFilter.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/StemmerTokenFilter.java @@ -1,32 +1,32 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) TypeSpec Code Generator. -package com.azure.search.documents.indexes.models; +package com.azure.search.documents.models; +import com.azure.core.annotation.Generated; import com.azure.core.annotation.Immutable; import com.azure.json.JsonReader; import com.azure.json.JsonToken; import com.azure.json.JsonWriter; import java.io.IOException; -import java.util.ArrayList; -import java.util.List; /** - * Language specific stemming filter. This token filter is implemented using Apache Lucene. + * Language specific stemming filter. This token filter is implemented using + * Apache Lucene. */ @Immutable public final class StemmerTokenFilter extends TokenFilter { /* - * A URI fragment specifying the type of token filter. + * The discriminator for derived types. */ + @Generated private String odataType = "#Microsoft.Azure.Search.StemmerTokenFilter"; /* * The language to use. */ + @Generated private final StemmerTokenFilterLanguage language; /** @@ -35,16 +35,18 @@ public final class StemmerTokenFilter extends TokenFilter { * @param name the name value to set. * @param language the language value to set. */ + @Generated public StemmerTokenFilter(String name, StemmerTokenFilterLanguage language) { super(name); this.language = language; } /** - * Get the odataType property: A URI fragment specifying the type of token filter. + * Get the odataType property: The discriminator for derived types. * * @return the odataType value. */ + @Generated @Override public String getOdataType() { return this.odataType; @@ -55,6 +57,7 @@ public String getOdataType() { * * @return the language value. */ + @Generated public StemmerTokenFilterLanguage getLanguage() { return this.language; } @@ -62,6 +65,7 @@ public StemmerTokenFilterLanguage getLanguage() { /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); @@ -80,11 +84,10 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { * @throws IllegalStateException If the deserialized JSON object was missing any required properties. * @throws IOException If an error occurs while reading the StemmerTokenFilter. */ + @Generated public static StemmerTokenFilter fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { - boolean nameFound = false; String name = null; - boolean languageFound = false; StemmerTokenFilterLanguage language = null; String odataType = "#Microsoft.Azure.Search.StemmerTokenFilter"; while (reader.nextToken() != JsonToken.END_OBJECT) { @@ -93,32 +96,18 @@ public static StemmerTokenFilter fromJson(JsonReader jsonReader) throws IOExcept if ("name".equals(fieldName)) { name = reader.getString(); - nameFound = true; } else if ("language".equals(fieldName)) { language = StemmerTokenFilterLanguage.fromString(reader.getString()); - languageFound = true; } else if ("@odata.type".equals(fieldName)) { odataType = reader.getString(); } else { reader.skipChildren(); } } - if (nameFound && languageFound) { - StemmerTokenFilter deserializedStemmerTokenFilter = new StemmerTokenFilter(name, language); - deserializedStemmerTokenFilter.odataType = odataType; + StemmerTokenFilter deserializedStemmerTokenFilter = new StemmerTokenFilter(name, language); + deserializedStemmerTokenFilter.odataType = odataType; - return deserializedStemmerTokenFilter; - } - List missingProperties = new ArrayList<>(); - if (!nameFound) { - missingProperties.add("name"); - } - if (!languageFound) { - missingProperties.add("language"); - } - - throw new IllegalStateException( - "Missing required property/properties: " + String.join(", ", missingProperties)); + return deserializedStemmerTokenFilter; }); } } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/StemmerTokenFilterLanguage.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/StemmerTokenFilterLanguage.java new file mode 100644 index 000000000000..8f57020825b9 --- /dev/null +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/StemmerTokenFilterLanguage.java @@ -0,0 +1,378 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.search.documents.models; + +import com.azure.core.annotation.Generated; +import com.azure.core.util.ExpandableStringEnum; +import java.util.Collection; + +/** + * The language to use for a stemmer token filter. + */ +public final class StemmerTokenFilterLanguage extends ExpandableStringEnum { + /** + * Selects the Lucene stemming tokenizer for Arabic. + */ + @Generated + public static final StemmerTokenFilterLanguage ARABIC = fromString("arabic"); + + /** + * Selects the Lucene stemming tokenizer for Armenian. + */ + @Generated + public static final StemmerTokenFilterLanguage ARMENIAN = fromString("armenian"); + + /** + * Selects the Lucene stemming tokenizer for Basque. + */ + @Generated + public static final StemmerTokenFilterLanguage BASQUE = fromString("basque"); + + /** + * Selects the Lucene stemming tokenizer for Portuguese (Brazil). + */ + @Generated + public static final StemmerTokenFilterLanguage BRAZILIAN = fromString("brazilian"); + + /** + * Selects the Lucene stemming tokenizer for Bulgarian. + */ + @Generated + public static final StemmerTokenFilterLanguage BULGARIAN = fromString("bulgarian"); + + /** + * Selects the Lucene stemming tokenizer for Catalan. + */ + @Generated + public static final StemmerTokenFilterLanguage CATALAN = fromString("catalan"); + + /** + * Selects the Lucene stemming tokenizer for Czech. + */ + @Generated + public static final StemmerTokenFilterLanguage CZECH = fromString("czech"); + + /** + * Selects the Lucene stemming tokenizer for Danish. + */ + @Generated + public static final StemmerTokenFilterLanguage DANISH = fromString("danish"); + + /** + * Selects the Lucene stemming tokenizer for Dutch. + */ + @Generated + public static final StemmerTokenFilterLanguage DUTCH = fromString("dutch"); + + /** + * Selects the Lucene stemming tokenizer for Dutch that uses the Kraaij-Pohlmann + * stemming algorithm. + */ + @Generated + public static final StemmerTokenFilterLanguage DUTCH_KP = fromString("dutchKp"); + + /** + * Selects the Lucene stemming tokenizer for English. + */ + @Generated + public static final StemmerTokenFilterLanguage ENGLISH = fromString("english"); + + /** + * Selects the Lucene stemming tokenizer for English that does light stemming. + */ + @Generated + public static final StemmerTokenFilterLanguage LIGHT_ENGLISH = fromString("lightEnglish"); + + /** + * Selects the Lucene stemming tokenizer for English that does minimal stemming. + */ + @Generated + public static final StemmerTokenFilterLanguage MINIMAL_ENGLISH = fromString("minimalEnglish"); + + /** + * Selects the Lucene stemming tokenizer for English that removes trailing + * possessives from words. + */ + @Generated + public static final StemmerTokenFilterLanguage POSSESSIVE_ENGLISH = fromString("possessiveEnglish"); + + /** + * Selects the Lucene stemming tokenizer for English that uses the Porter2 + * stemming algorithm. + */ + @Generated + public static final StemmerTokenFilterLanguage PORTER2 = fromString("porter2"); + + /** + * Selects the Lucene stemming tokenizer for English that uses the Lovins stemming + * algorithm. + */ + @Generated + public static final StemmerTokenFilterLanguage LOVINS = fromString("lovins"); + + /** + * Selects the Lucene stemming tokenizer for Finnish. + */ + @Generated + public static final StemmerTokenFilterLanguage FINNISH = fromString("finnish"); + + /** + * Selects the Lucene stemming tokenizer for Finnish that does light stemming. + */ + @Generated + public static final StemmerTokenFilterLanguage LIGHT_FINNISH = fromString("lightFinnish"); + + /** + * Selects the Lucene stemming tokenizer for French. + */ + @Generated + public static final StemmerTokenFilterLanguage FRENCH = fromString("french"); + + /** + * Selects the Lucene stemming tokenizer for French that does light stemming. + */ + @Generated + public static final StemmerTokenFilterLanguage LIGHT_FRENCH = fromString("lightFrench"); + + /** + * Selects the Lucene stemming tokenizer for French that does minimal stemming. + */ + @Generated + public static final StemmerTokenFilterLanguage MINIMAL_FRENCH = fromString("minimalFrench"); + + /** + * Selects the Lucene stemming tokenizer for Galician. + */ + @Generated + public static final StemmerTokenFilterLanguage GALICIAN = fromString("galician"); + + /** + * Selects the Lucene stemming tokenizer for Galician that does minimal stemming. + */ + @Generated + public static final StemmerTokenFilterLanguage MINIMAL_GALICIAN = fromString("minimalGalician"); + + /** + * Selects the Lucene stemming tokenizer for German. + */ + @Generated + public static final StemmerTokenFilterLanguage GERMAN = fromString("german"); + + /** + * Selects the Lucene stemming tokenizer that uses the German variant algorithm. + */ + @Generated + public static final StemmerTokenFilterLanguage GERMAN2 = fromString("german2"); + + /** + * Selects the Lucene stemming tokenizer for German that does light stemming. + */ + @Generated + public static final StemmerTokenFilterLanguage LIGHT_GERMAN = fromString("lightGerman"); + + /** + * Selects the Lucene stemming tokenizer for German that does minimal stemming. + */ + @Generated + public static final StemmerTokenFilterLanguage MINIMAL_GERMAN = fromString("minimalGerman"); + + /** + * Selects the Lucene stemming tokenizer for Greek. + */ + @Generated + public static final StemmerTokenFilterLanguage GREEK = fromString("greek"); + + /** + * Selects the Lucene stemming tokenizer for Hindi. + */ + @Generated + public static final StemmerTokenFilterLanguage HINDI = fromString("hindi"); + + /** + * Selects the Lucene stemming tokenizer for Hungarian. + */ + @Generated + public static final StemmerTokenFilterLanguage HUNGARIAN = fromString("hungarian"); + + /** + * Selects the Lucene stemming tokenizer for Hungarian that does light stemming. + */ + @Generated + public static final StemmerTokenFilterLanguage LIGHT_HUNGARIAN = fromString("lightHungarian"); + + /** + * Selects the Lucene stemming tokenizer for Indonesian. + */ + @Generated + public static final StemmerTokenFilterLanguage INDONESIAN = fromString("indonesian"); + + /** + * Selects the Lucene stemming tokenizer for Irish. + */ + @Generated + public static final StemmerTokenFilterLanguage IRISH = fromString("irish"); + + /** + * Selects the Lucene stemming tokenizer for Italian. + */ + @Generated + public static final StemmerTokenFilterLanguage ITALIAN = fromString("italian"); + + /** + * Selects the Lucene stemming tokenizer for Italian that does light stemming. + */ + @Generated + public static final StemmerTokenFilterLanguage LIGHT_ITALIAN = fromString("lightItalian"); + + /** + * Selects the Lucene stemming tokenizer for Sorani. + */ + @Generated + public static final StemmerTokenFilterLanguage SORANI = fromString("sorani"); + + /** + * Selects the Lucene stemming tokenizer for Latvian. + */ + @Generated + public static final StemmerTokenFilterLanguage LATVIAN = fromString("latvian"); + + /** + * Selects the Lucene stemming tokenizer for Norwegian (Bokmål). + */ + @Generated + public static final StemmerTokenFilterLanguage NORWEGIAN = fromString("norwegian"); + + /** + * Selects the Lucene stemming tokenizer for Norwegian (Bokmål) that does light + * stemming. + */ + @Generated + public static final StemmerTokenFilterLanguage LIGHT_NORWEGIAN = fromString("lightNorwegian"); + + /** + * Selects the Lucene stemming tokenizer for Norwegian (Bokmål) that does minimal + * stemming. + */ + @Generated + public static final StemmerTokenFilterLanguage MINIMAL_NORWEGIAN = fromString("minimalNorwegian"); + + /** + * Selects the Lucene stemming tokenizer for Norwegian (Nynorsk) that does light + * stemming. + */ + @Generated + public static final StemmerTokenFilterLanguage LIGHT_NYNORSK = fromString("lightNynorsk"); + + /** + * Selects the Lucene stemming tokenizer for Norwegian (Nynorsk) that does minimal + * stemming. + */ + @Generated + public static final StemmerTokenFilterLanguage MINIMAL_NYNORSK = fromString("minimalNynorsk"); + + /** + * Selects the Lucene stemming tokenizer for Portuguese. + */ + @Generated + public static final StemmerTokenFilterLanguage PORTUGUESE = fromString("portuguese"); + + /** + * Selects the Lucene stemming tokenizer for Portuguese that does light stemming. + */ + @Generated + public static final StemmerTokenFilterLanguage LIGHT_PORTUGUESE = fromString("lightPortuguese"); + + /** + * Selects the Lucene stemming tokenizer for Portuguese that does minimal stemming. + */ + @Generated + public static final StemmerTokenFilterLanguage MINIMAL_PORTUGUESE = fromString("minimalPortuguese"); + + /** + * Selects the Lucene stemming tokenizer for Portuguese that uses the RSLP + * stemming algorithm. + */ + @Generated + public static final StemmerTokenFilterLanguage PORTUGUESE_RSLP = fromString("portugueseRslp"); + + /** + * Selects the Lucene stemming tokenizer for Romanian. + */ + @Generated + public static final StemmerTokenFilterLanguage ROMANIAN = fromString("romanian"); + + /** + * Selects the Lucene stemming tokenizer for Russian. + */ + @Generated + public static final StemmerTokenFilterLanguage RUSSIAN = fromString("russian"); + + /** + * Selects the Lucene stemming tokenizer for Russian that does light stemming. + */ + @Generated + public static final StemmerTokenFilterLanguage LIGHT_RUSSIAN = fromString("lightRussian"); + + /** + * Selects the Lucene stemming tokenizer for Spanish. + */ + @Generated + public static final StemmerTokenFilterLanguage SPANISH = fromString("spanish"); + + /** + * Selects the Lucene stemming tokenizer for Spanish that does light stemming. + */ + @Generated + public static final StemmerTokenFilterLanguage LIGHT_SPANISH = fromString("lightSpanish"); + + /** + * Selects the Lucene stemming tokenizer for Swedish. + */ + @Generated + public static final StemmerTokenFilterLanguage SWEDISH = fromString("swedish"); + + /** + * Selects the Lucene stemming tokenizer for Swedish that does light stemming. + */ + @Generated + public static final StemmerTokenFilterLanguage LIGHT_SWEDISH = fromString("lightSwedish"); + + /** + * Selects the Lucene stemming tokenizer for Turkish. + */ + @Generated + public static final StemmerTokenFilterLanguage TURKISH = fromString("turkish"); + + /** + * Creates a new instance of StemmerTokenFilterLanguage value. + * + * @deprecated Use the {@link #fromString(String)} factory method. + */ + @Generated + @Deprecated + public StemmerTokenFilterLanguage() { + } + + /** + * Creates or finds a StemmerTokenFilterLanguage from its string representation. + * + * @param name a name to look for. + * @return the corresponding StemmerTokenFilterLanguage. + */ + @Generated + public static StemmerTokenFilterLanguage fromString(String name) { + return fromString(name, StemmerTokenFilterLanguage.class); + } + + /** + * Gets known StemmerTokenFilterLanguage values. + * + * @return known StemmerTokenFilterLanguage values. + */ + @Generated + public static Collection values() { + return values(StemmerTokenFilterLanguage.class); + } +} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/StopAnalyzer.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/StopAnalyzer.java similarity index 71% rename from sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/StopAnalyzer.java rename to sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/StopAnalyzer.java index ae035a7d14eb..b6605fac6f48 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/StopAnalyzer.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/StopAnalyzer.java @@ -1,49 +1,51 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. -package com.azure.search.documents.indexes.models; +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.search.documents.models; import com.azure.core.annotation.Fluent; +import com.azure.core.annotation.Generated; import com.azure.json.JsonReader; import com.azure.json.JsonToken; import com.azure.json.JsonWriter; import java.io.IOException; -import java.util.Arrays; import java.util.List; /** - * Divides text at non-letters; Applies the lowercase and stopword token filters. This analyzer is implemented using - * Apache Lucene. + * Divides text at non-letters; Applies the lowercase and stopword token filters. + * This analyzer is implemented using Apache Lucene. */ @Fluent public final class StopAnalyzer extends LexicalAnalyzer { - /* - * A URI fragment specifying the type of analyzer. + * The discriminator for derived types. */ + @Generated private String odataType = "#Microsoft.Azure.Search.StopAnalyzer"; /* * A list of stopwords. */ + @Generated private List stopwords; /** * Creates an instance of StopAnalyzer class. - * + * * @param name the name value to set. */ + @Generated public StopAnalyzer(String name) { super(name); } /** - * Get the odataType property: A URI fragment specifying the type of analyzer. - * + * Get the odataType property: The discriminator for derived types. + * * @return the odataType value. */ + @Generated @Override public String getOdataType() { return this.odataType; @@ -51,19 +53,21 @@ public String getOdataType() { /** * Get the stopwords property: A list of stopwords. - * + * * @return the stopwords value. */ + @Generated public List getStopwords() { return this.stopwords; } /** * Set the stopwords property: A list of stopwords. - * + * * @param stopwords the stopwords value to set. * @return the StopAnalyzer object itself. */ + @Generated public StopAnalyzer setStopwords(List stopwords) { this.stopwords = stopwords; return this; @@ -72,6 +76,7 @@ public StopAnalyzer setStopwords(List stopwords) { /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); @@ -83,25 +88,25 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of StopAnalyzer from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of StopAnalyzer if the JsonReader was pointing to an instance of it, or null if it was * pointing to JSON null. * @throws IllegalStateException If the deserialized JSON object was missing any required properties. * @throws IOException If an error occurs while reading the StopAnalyzer. */ + @Generated public static StopAnalyzer fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { - boolean nameFound = false; String name = null; String odataType = "#Microsoft.Azure.Search.StopAnalyzer"; List stopwords = null; while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); + if ("name".equals(fieldName)) { name = reader.getString(); - nameFound = true; } else if ("@odata.type".equals(fieldName)) { odataType = reader.getString(); } else if ("stopwords".equals(fieldName)) { @@ -110,24 +115,11 @@ public static StopAnalyzer fromJson(JsonReader jsonReader) throws IOException { reader.skipChildren(); } } - if (nameFound) { - StopAnalyzer deserializedStopAnalyzer = new StopAnalyzer(name); - deserializedStopAnalyzer.odataType = odataType; - deserializedStopAnalyzer.stopwords = stopwords; - return deserializedStopAnalyzer; - } - throw new IllegalStateException("Missing required property: name"); - }); - } + StopAnalyzer deserializedStopAnalyzer = new StopAnalyzer(name); + deserializedStopAnalyzer.odataType = odataType; + deserializedStopAnalyzer.stopwords = stopwords; - /** - * Set the stopwords property: A list of stopwords. - * - * @param stopwords the stopwords value to set. - * @return the StopAnalyzer object itself. - */ - public StopAnalyzer setStopwords(String... stopwords) { - this.stopwords = (stopwords == null) ? null : Arrays.asList(stopwords); - return this; + return deserializedStopAnalyzer; + }); } } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/StopwordsList.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/StopwordsList.java new file mode 100644 index 000000000000..5fc0a7f23ed8 --- /dev/null +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/StopwordsList.java @@ -0,0 +1,231 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.search.documents.models; + +import com.azure.core.annotation.Generated; +import com.azure.core.util.ExpandableStringEnum; +import java.util.Collection; + +/** + * Identifies a predefined list of language-specific stopwords. + */ +public final class StopwordsList extends ExpandableStringEnum { + /** + * Selects the stopword list for Arabic. + */ + @Generated + public static final StopwordsList ARABIC = fromString("arabic"); + + /** + * Selects the stopword list for Armenian. + */ + @Generated + public static final StopwordsList ARMENIAN = fromString("armenian"); + + /** + * Selects the stopword list for Basque. + */ + @Generated + public static final StopwordsList BASQUE = fromString("basque"); + + /** + * Selects the stopword list for Portuguese (Brazil). + */ + @Generated + public static final StopwordsList BRAZILIAN = fromString("brazilian"); + + /** + * Selects the stopword list for Bulgarian. + */ + @Generated + public static final StopwordsList BULGARIAN = fromString("bulgarian"); + + /** + * Selects the stopword list for Catalan. + */ + @Generated + public static final StopwordsList CATALAN = fromString("catalan"); + + /** + * Selects the stopword list for Czech. + */ + @Generated + public static final StopwordsList CZECH = fromString("czech"); + + /** + * Selects the stopword list for Danish. + */ + @Generated + public static final StopwordsList DANISH = fromString("danish"); + + /** + * Selects the stopword list for Dutch. + */ + @Generated + public static final StopwordsList DUTCH = fromString("dutch"); + + /** + * Selects the stopword list for English. + */ + @Generated + public static final StopwordsList ENGLISH = fromString("english"); + + /** + * Selects the stopword list for Finnish. + */ + @Generated + public static final StopwordsList FINNISH = fromString("finnish"); + + /** + * Selects the stopword list for French. + */ + @Generated + public static final StopwordsList FRENCH = fromString("french"); + + /** + * Selects the stopword list for Galician. + */ + @Generated + public static final StopwordsList GALICIAN = fromString("galician"); + + /** + * Selects the stopword list for German. + */ + @Generated + public static final StopwordsList GERMAN = fromString("german"); + + /** + * Selects the stopword list for Greek. + */ + @Generated + public static final StopwordsList GREEK = fromString("greek"); + + /** + * Selects the stopword list for Hindi. + */ + @Generated + public static final StopwordsList HINDI = fromString("hindi"); + + /** + * Selects the stopword list for Hungarian. + */ + @Generated + public static final StopwordsList HUNGARIAN = fromString("hungarian"); + + /** + * Selects the stopword list for Indonesian. + */ + @Generated + public static final StopwordsList INDONESIAN = fromString("indonesian"); + + /** + * Selects the stopword list for Irish. + */ + @Generated + public static final StopwordsList IRISH = fromString("irish"); + + /** + * Selects the stopword list for Italian. + */ + @Generated + public static final StopwordsList ITALIAN = fromString("italian"); + + /** + * Selects the stopword list for Latvian. + */ + @Generated + public static final StopwordsList LATVIAN = fromString("latvian"); + + /** + * Selects the stopword list for Norwegian. + */ + @Generated + public static final StopwordsList NORWEGIAN = fromString("norwegian"); + + /** + * Selects the stopword list for Persian. + */ + @Generated + public static final StopwordsList PERSIAN = fromString("persian"); + + /** + * Selects the stopword list for Portuguese. + */ + @Generated + public static final StopwordsList PORTUGUESE = fromString("portuguese"); + + /** + * Selects the stopword list for Romanian. + */ + @Generated + public static final StopwordsList ROMANIAN = fromString("romanian"); + + /** + * Selects the stopword list for Russian. + */ + @Generated + public static final StopwordsList RUSSIAN = fromString("russian"); + + /** + * Selects the stopword list for Sorani. + */ + @Generated + public static final StopwordsList SORANI = fromString("sorani"); + + /** + * Selects the stopword list for Spanish. + */ + @Generated + public static final StopwordsList SPANISH = fromString("spanish"); + + /** + * Selects the stopword list for Swedish. + */ + @Generated + public static final StopwordsList SWEDISH = fromString("swedish"); + + /** + * Selects the stopword list for Thai. + */ + @Generated + public static final StopwordsList THAI = fromString("thai"); + + /** + * Selects the stopword list for Turkish. + */ + @Generated + public static final StopwordsList TURKISH = fromString("turkish"); + + /** + * Creates a new instance of StopwordsList value. + * + * @deprecated Use the {@link #fromString(String)} factory method. + */ + @Generated + @Deprecated + public StopwordsList() { + } + + /** + * Creates or finds a StopwordsList from its string representation. + * + * @param name a name to look for. + * @return the corresponding StopwordsList. + */ + @Generated + public static StopwordsList fromString(String name) { + return fromString(name, StopwordsList.class); + } + + /** + * Gets known StopwordsList values. + * + * @return known StopwordsList values. + */ + @Generated + public static Collection values() { + return values(StopwordsList.class); + } +} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/StopwordsTokenFilter.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/StopwordsTokenFilter.java similarity index 58% rename from sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/StopwordsTokenFilter.java rename to sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/StopwordsTokenFilter.java index 5c934edee0ab..fae9de339333 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/StopwordsTokenFilter.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/StopwordsTokenFilter.java @@ -1,87 +1,97 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. -package com.azure.search.documents.indexes.models; +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.search.documents.models; import com.azure.core.annotation.Fluent; +import com.azure.core.annotation.Generated; import com.azure.json.JsonReader; import com.azure.json.JsonToken; import com.azure.json.JsonWriter; import java.io.IOException; -import java.util.Arrays; import java.util.List; /** - * Removes stop words from a token stream. This token filter is implemented using Apache Lucene. + * Removes stop words from a token stream. This token filter is implemented using + * Apache Lucene. */ @Fluent public final class StopwordsTokenFilter extends TokenFilter { - /* - * A URI fragment specifying the type of token filter. + * The discriminator for derived types. */ + @Generated private String odataType = "#Microsoft.Azure.Search.StopwordsTokenFilter"; /* - * The list of stopwords. This property and the stopwords list property cannot both be set. + * The list of stopwords. This property and the stopwords list property cannot + * both be set. */ + @Generated private List stopwords; /* - * A predefined list of stopwords to use. This property and the stopwords property cannot both be set. Default is - * English. + * A predefined list of stopwords to use. This property and the stopwords property + * cannot both be set. Default is English. */ + @Generated private StopwordsList stopwordsList; /* - * A value indicating whether to ignore case. If true, all words are converted to lower case first. Default is - * false. + * A value indicating whether to ignore case. If true, all words are converted to + * lower case first. Default is false. */ - private Boolean caseIgnored; + @Generated + private Boolean ignoreCase; /* - * A value indicating whether to ignore the last search term if it's a stop word. Default is true. + * A value indicating whether to ignore the last search term if it's a stop word. + * Default is true. */ - private Boolean trailingStopWordsRemoved; + @Generated + private Boolean removeTrailingStopWords; /** * Creates an instance of StopwordsTokenFilter class. - * + * * @param name the name value to set. */ + @Generated public StopwordsTokenFilter(String name) { super(name); } /** - * Get the odataType property: A URI fragment specifying the type of token filter. - * + * Get the odataType property: The discriminator for derived types. + * * @return the odataType value. */ + @Generated @Override public String getOdataType() { return this.odataType; } /** - * Get the stopwords property: The list of stopwords. This property and the stopwords list property cannot both be - * set. - * + * Get the stopwords property: The list of stopwords. This property and the stopwords list property cannot + * both be set. + * * @return the stopwords value. */ + @Generated public List getStopwords() { return this.stopwords; } /** - * Set the stopwords property: The list of stopwords. This property and the stopwords list property cannot both be - * set. - * + * Set the stopwords property: The list of stopwords. This property and the stopwords list property cannot + * both be set. + * * @param stopwords the stopwords value to set. * @return the StopwordsTokenFilter object itself. */ + @Generated public StopwordsTokenFilter setStopwords(List stopwords) { this.stopwords = stopwords; return this; @@ -90,9 +100,10 @@ public StopwordsTokenFilter setStopwords(List stopwords) { /** * Get the stopwordsList property: A predefined list of stopwords to use. This property and the stopwords property * cannot both be set. Default is English. - * + * * @return the stopwordsList value. */ + @Generated public StopwordsList getStopwordsList() { return this.stopwordsList; } @@ -100,62 +111,70 @@ public StopwordsList getStopwordsList() { /** * Set the stopwordsList property: A predefined list of stopwords to use. This property and the stopwords property * cannot both be set. Default is English. - * + * * @param stopwordsList the stopwordsList value to set. * @return the StopwordsTokenFilter object itself. */ + @Generated public StopwordsTokenFilter setStopwordsList(StopwordsList stopwordsList) { this.stopwordsList = stopwordsList; return this; } /** - * Get the caseIgnored property: A value indicating whether to ignore case. If true, all words are converted to + * Get the ignoreCase property: A value indicating whether to ignore case. If true, all words are converted to * lower case first. Default is false. - * - * @return the caseIgnored value. + * + * @return the ignoreCase value. */ - public Boolean isCaseIgnored() { - return this.caseIgnored; + @Generated + public Boolean isIgnoreCase() { + return this.ignoreCase; } /** - * Set the caseIgnored property: A value indicating whether to ignore case. If true, all words are converted to + * Set the ignoreCase property: A value indicating whether to ignore case. If true, all words are converted to * lower case first. Default is false. - * - * @param caseIgnored the caseIgnored value to set. + * + * @param ignoreCase the ignoreCase value to set. * @return the StopwordsTokenFilter object itself. */ - public StopwordsTokenFilter setCaseIgnored(Boolean caseIgnored) { - this.caseIgnored = caseIgnored; + @Generated + public StopwordsTokenFilter setIgnoreCase(Boolean ignoreCase) { + this.ignoreCase = ignoreCase; return this; } /** - * Get the trailingStopWordsRemoved property: A value indicating whether to ignore the last search term if it's a - * stop word. Default is true. - * - * @return the trailingStopWordsRemoved value. - */ - public Boolean areTrailingStopWordsRemoved() { - return this.trailingStopWordsRemoved; + * Get the removeTrailingStopWords property: A value indicating whether to ignore the last search term if it's a + * stop word. + * Default is true. + * + * @return the removeTrailingStopWords value. + */ + @Generated + public Boolean isRemoveTrailingStopWords() { + return this.removeTrailingStopWords; } /** - * Set the trailingStopWordsRemoved property: A value indicating whether to ignore the last search term if it's a - * stop word. Default is true. - * - * @param trailingStopWordsRemoved the trailingStopWordsRemoved value to set. + * Set the removeTrailingStopWords property: A value indicating whether to ignore the last search term if it's a + * stop word. + * Default is true. + * + * @param removeTrailingStopWords the removeTrailingStopWords value to set. * @return the StopwordsTokenFilter object itself. */ - public StopwordsTokenFilter setTrailingStopWordsRemoved(Boolean trailingStopWordsRemoved) { - this.trailingStopWordsRemoved = trailingStopWordsRemoved; + @Generated + public StopwordsTokenFilter setRemoveTrailingStopWords(Boolean removeTrailingStopWords) { + this.removeTrailingStopWords = removeTrailingStopWords; return this; } /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); @@ -163,35 +182,35 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStringField("@odata.type", this.odataType); jsonWriter.writeArrayField("stopwords", this.stopwords, (writer, element) -> writer.writeString(element)); jsonWriter.writeStringField("stopwordsList", this.stopwordsList == null ? null : this.stopwordsList.toString()); - jsonWriter.writeBooleanField("ignoreCase", this.caseIgnored); - jsonWriter.writeBooleanField("removeTrailing", this.trailingStopWordsRemoved); + jsonWriter.writeBooleanField("ignoreCase", this.ignoreCase); + jsonWriter.writeBooleanField("removeTrailing", this.removeTrailingStopWords); return jsonWriter.writeEndObject(); } /** * Reads an instance of StopwordsTokenFilter from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of StopwordsTokenFilter if the JsonReader was pointing to an instance of it, or null if it * was pointing to JSON null. * @throws IllegalStateException If the deserialized JSON object was missing any required properties. * @throws IOException If an error occurs while reading the StopwordsTokenFilter. */ + @Generated public static StopwordsTokenFilter fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { - boolean nameFound = false; String name = null; String odataType = "#Microsoft.Azure.Search.StopwordsTokenFilter"; List stopwords = null; StopwordsList stopwordsList = null; - Boolean caseIgnored = null; - Boolean trailingStopWordsRemoved = null; + Boolean ignoreCase = null; + Boolean removeTrailingStopWords = null; while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); + if ("name".equals(fieldName)) { name = reader.getString(); - nameFound = true; } else if ("@odata.type".equals(fieldName)) { odataType = reader.getString(); } else if ("stopwords".equals(fieldName)) { @@ -199,35 +218,21 @@ public static StopwordsTokenFilter fromJson(JsonReader jsonReader) throws IOExce } else if ("stopwordsList".equals(fieldName)) { stopwordsList = StopwordsList.fromString(reader.getString()); } else if ("ignoreCase".equals(fieldName)) { - caseIgnored = reader.getNullable(JsonReader::getBoolean); + ignoreCase = reader.getNullable(JsonReader::getBoolean); } else if ("removeTrailing".equals(fieldName)) { - trailingStopWordsRemoved = reader.getNullable(JsonReader::getBoolean); + removeTrailingStopWords = reader.getNullable(JsonReader::getBoolean); } else { reader.skipChildren(); } } - if (nameFound) { - StopwordsTokenFilter deserializedStopwordsTokenFilter = new StopwordsTokenFilter(name); - deserializedStopwordsTokenFilter.odataType = odataType; - deserializedStopwordsTokenFilter.stopwords = stopwords; - deserializedStopwordsTokenFilter.stopwordsList = stopwordsList; - deserializedStopwordsTokenFilter.caseIgnored = caseIgnored; - deserializedStopwordsTokenFilter.trailingStopWordsRemoved = trailingStopWordsRemoved; - return deserializedStopwordsTokenFilter; - } - throw new IllegalStateException("Missing required property: name"); + StopwordsTokenFilter deserializedStopwordsTokenFilter = new StopwordsTokenFilter(name); + deserializedStopwordsTokenFilter.odataType = odataType; + deserializedStopwordsTokenFilter.stopwords = stopwords; + deserializedStopwordsTokenFilter.stopwordsList = stopwordsList; + deserializedStopwordsTokenFilter.ignoreCase = ignoreCase; + deserializedStopwordsTokenFilter.removeTrailingStopWords = removeTrailingStopWords; + + return deserializedStopwordsTokenFilter; }); } - - /** - * Set the stopwords property: The list of stopwords. This property and the stopwords list property cannot both be - * set. - * - * @param stopwords the stopwords value to set. - * @return the StopwordsTokenFilter object itself. - */ - public StopwordsTokenFilter setStopwords(String... stopwords) { - this.stopwords = (stopwords == null) ? null : Arrays.asList(stopwords); - return this; - } } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/implementation/models/SuggestDocumentsResult.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SuggestDocumentsResult.java similarity index 75% rename from sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/implementation/models/SuggestDocumentsResult.java rename to sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SuggestDocumentsResult.java index 72a4688d3aa5..507571f51755 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/implementation/models/SuggestDocumentsResult.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SuggestDocumentsResult.java @@ -1,11 +1,10 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) TypeSpec Code Generator. -package com.azure.search.documents.implementation.models; +package com.azure.search.documents.models; +import com.azure.core.annotation.Generated; import com.azure.core.annotation.Immutable; import com.azure.json.JsonReader; import com.azure.json.JsonSerializable; @@ -22,12 +21,14 @@ public final class SuggestDocumentsResult implements JsonSerializable results; /* - * A value indicating the percentage of the index that was included in the query, or null if minimumCoverage was not - * set in the request. + * A value indicating the percentage of the index that was included in the query, + * or null if minimumCoverage was not set in the request. */ + @Generated private Double coverage; /** @@ -35,7 +36,8 @@ public final class SuggestDocumentsResult implements JsonSerializable results) { + @Generated + private SuggestDocumentsResult(List results) { this.results = results; } @@ -44,16 +46,18 @@ public SuggestDocumentsResult(List results) { * * @return the results value. */ + @Generated public List getResults() { return this.results; } /** - * Get the coverage property: A value indicating the percentage of the index that was included in the query, or null - * if minimumCoverage was not set in the request. + * Get the coverage property: A value indicating the percentage of the index that was included in the query, + * or null if minimumCoverage was not set in the request. * * @return the coverage value. */ + @Generated public Double getCoverage() { return this.coverage; } @@ -61,9 +65,12 @@ public Double getCoverage() { /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); + jsonWriter.writeArrayField("value", this.results, (writer, element) -> writer.writeJson(element)); + jsonWriter.writeNumberField("@search.coverage", this.coverage); return jsonWriter.writeEndObject(); } @@ -76,9 +83,9 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { * @throws IllegalStateException If the deserialized JSON object was missing any required properties. * @throws IOException If an error occurs while reading the SuggestDocumentsResult. */ + @Generated public static SuggestDocumentsResult fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { - boolean resultsFound = false; List results = null; Double coverage = null; while (reader.nextToken() != JsonToken.END_OBJECT) { @@ -87,20 +94,16 @@ public static SuggestDocumentsResult fromJson(JsonReader jsonReader) throws IOEx if ("value".equals(fieldName)) { results = reader.readArray(reader1 -> SuggestResult.fromJson(reader1)); - resultsFound = true; } else if ("@search.coverage".equals(fieldName)) { coverage = reader.getNullable(JsonReader::getDouble); } else { reader.skipChildren(); } } - if (resultsFound) { - SuggestDocumentsResult deserializedSuggestDocumentsResult = new SuggestDocumentsResult(results); - deserializedSuggestDocumentsResult.coverage = coverage; + SuggestDocumentsResult deserializedSuggestDocumentsResult = new SuggestDocumentsResult(results); + deserializedSuggestDocumentsResult.coverage = coverage; - return deserializedSuggestDocumentsResult; - } - throw new IllegalStateException("Missing required property: value"); + return deserializedSuggestDocumentsResult; }); } } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SuggestOptions.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SuggestOptions.java deleted file mode 100644 index 4db3ca2eeb4a..000000000000 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SuggestOptions.java +++ /dev/null @@ -1,393 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. -package com.azure.search.documents.models; - -import com.azure.core.annotation.Fluent; -import com.azure.json.JsonReader; -import com.azure.json.JsonSerializable; -import com.azure.json.JsonToken; -import com.azure.json.JsonWriter; -import java.io.IOException; -import java.util.Arrays; -import java.util.List; - -/** - * Parameter group. - */ -@Fluent -public final class SuggestOptions implements JsonSerializable { - - /* - * An OData expression that filters the documents considered for suggestions. - */ - private String filter; - - /* - * 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. - */ - private Boolean useFuzzyMatching; - - /* - * A string tag that is appended to hit highlights. Must be set with highlightPreTag. If omitted, hit highlighting - * of suggestions is disabled. - */ - private String highlightPostTag; - - /* - * A string tag that is prepended to hit highlights. Must be set with highlightPostTag. If omitted, hit highlighting - * of suggestions is disabled. - */ - private String highlightPreTag; - - /* - * 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. - */ - private Double minimumCoverage; - - /* - * 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. - */ - private List orderBy; - - /* - * The list of field names to search for the specified search text. Target fields must be included in the specified - * suggester. - */ - private List searchFields; - - /* - * The list of fields to retrieve. If unspecified, only the key field will be included in the results. - */ - private List select; - - /* - * The number of suggestions to retrieve. The value must be a number between 1 and 100. The default is 5. - */ - private Integer top; - - /** - * Creates an instance of SuggestOptions class. - */ - public SuggestOptions() { - } - - /** - * Get the filter property: An OData expression that filters the documents considered for suggestions. - * - * @return the filter value. - */ - public String getFilter() { - return this.filter; - } - - /** - * Set the filter property: An OData expression that filters the documents considered for suggestions. - * - * @param filter the filter value to set. - * @return the SuggestOptions object itself. - */ - public SuggestOptions setFilter(String filter) { - this.filter = filter; - return this; - } - - /** - * Get the useFuzzyMatching property: 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. - * - * @return the useFuzzyMatching value. - */ - public Boolean useFuzzyMatching() { - return this.useFuzzyMatching; - } - - /** - * Set the useFuzzyMatching property: 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. - * - * @param useFuzzyMatching the useFuzzyMatching value to set. - * @return the SuggestOptions object itself. - */ - public SuggestOptions setUseFuzzyMatching(Boolean useFuzzyMatching) { - this.useFuzzyMatching = useFuzzyMatching; - return this; - } - - /** - * Get the highlightPostTag property: A string tag that is appended to hit highlights. Must be set with - * highlightPreTag. If omitted, hit highlighting of suggestions is disabled. - * - * @return the highlightPostTag value. - */ - public String getHighlightPostTag() { - return this.highlightPostTag; - } - - /** - * Set the highlightPostTag property: A string tag that is appended to hit highlights. Must be set with - * highlightPreTag. If omitted, hit highlighting of suggestions is disabled. - * - * @param highlightPostTag the highlightPostTag value to set. - * @return the SuggestOptions object itself. - */ - public SuggestOptions setHighlightPostTag(String highlightPostTag) { - this.highlightPostTag = highlightPostTag; - return this; - } - - /** - * Get the highlightPreTag property: A string tag that is prepended to hit highlights. Must be set with - * highlightPostTag. If omitted, hit highlighting of suggestions is disabled. - * - * @return the highlightPreTag value. - */ - public String getHighlightPreTag() { - return this.highlightPreTag; - } - - /** - * Set the highlightPreTag property: A string tag that is prepended to hit highlights. Must be set with - * highlightPostTag. If omitted, hit highlighting of suggestions is disabled. - * - * @param highlightPreTag the highlightPreTag value to set. - * @return the SuggestOptions object itself. - */ - public SuggestOptions setHighlightPreTag(String highlightPreTag) { - this.highlightPreTag = highlightPreTag; - return this; - } - - /** - * Get the minimumCoverage property: 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. - * - * @return the minimumCoverage value. - */ - public Double getMinimumCoverage() { - return this.minimumCoverage; - } - - /** - * Set the minimumCoverage property: 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. - * - * @param minimumCoverage the minimumCoverage value to set. - * @return the SuggestOptions object itself. - */ - public SuggestOptions setMinimumCoverage(Double minimumCoverage) { - this.minimumCoverage = minimumCoverage; - return this; - } - - /** - * Get the orderBy property: 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. - * - * @return the orderBy value. - */ - public List getOrderBy() { - return this.orderBy; - } - - /** - * Set the orderBy property: 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. - * - * @param orderBy the orderBy value to set. - * @return the SuggestOptions object itself. - */ - public SuggestOptions setOrderBy(List orderBy) { - this.orderBy = orderBy; - return this; - } - - /** - * Get the searchFields property: The list of field names to search for the specified search text. Target fields - * must be included in the specified suggester. - * - * @return the searchFields value. - */ - public List getSearchFields() { - return this.searchFields; - } - - /** - * Set the searchFields property: The list of field names to search for the specified search text. Target fields - * must be included in the specified suggester. - * - * @param searchFields the searchFields value to set. - * @return the SuggestOptions object itself. - */ - public SuggestOptions setSearchFields(List searchFields) { - this.searchFields = searchFields; - return this; - } - - /** - * Get the select property: The list of fields to retrieve. If unspecified, only the key field will be included in - * the results. - * - * @return the select value. - */ - public List getSelect() { - return this.select; - } - - /** - * Set the select property: The list of fields to retrieve. If unspecified, only the key field will be included in - * the results. - * - * @param select the select value to set. - * @return the SuggestOptions object itself. - */ - public SuggestOptions setSelect(List select) { - this.select = select; - return this; - } - - /** - * Get the top property: The number of suggestions to retrieve. The value must be a number between 1 and 100. The - * default is 5. - * - * @return the top value. - */ - public Integer getTop() { - return this.top; - } - - /** - * Set the top property: The number of suggestions to retrieve. The value must be a number between 1 and 100. The - * default is 5. - * - * @param top the top value to set. - * @return the SuggestOptions object itself. - */ - public SuggestOptions setTop(Integer top) { - this.top = top; - return this; - } - - /** - * Set the orderBy property: 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. - * - * @param orderBy the orderBy value to set. - * @return the SuggestOptions object itself. - */ - public SuggestOptions setOrderBy(String... orderBy) { - this.orderBy = (orderBy == null) ? null : Arrays.asList(orderBy); - return this; - } - - /** - * Set the searchFields property: The list of field names to search for the specified search text. Target fields - * must be included in the specified suggester. - * - * @param searchFields the searchFields value to set. - * @return the SuggestOptions object itself. - */ - public SuggestOptions setSearchFields(String... searchFields) { - this.searchFields = (searchFields == null) ? null : Arrays.asList(searchFields); - return this; - } - - /** - * Set the select property: The list of fields to retrieve. If unspecified, only the key field will be included in - * the results. - * - * @param select the select value to set. - * @return the SuggestOptions object itself. - */ - public SuggestOptions setSelect(String... select) { - this.select = (select == null) ? null : Arrays.asList(select); - return this; - } - - /** - * {@inheritDoc} - */ - @Override - public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { - jsonWriter.writeStartObject(); - jsonWriter.writeStringField("$filter", this.filter); - jsonWriter.writeBooleanField("UseFuzzyMatching", this.useFuzzyMatching); - jsonWriter.writeStringField("highlightPostTag", this.highlightPostTag); - jsonWriter.writeStringField("highlightPreTag", this.highlightPreTag); - jsonWriter.writeNumberField("minimumCoverage", this.minimumCoverage); - jsonWriter.writeArrayField("OrderBy", this.orderBy, (writer, element) -> writer.writeString(element)); - jsonWriter.writeArrayField("searchFields", this.searchFields, (writer, element) -> writer.writeString(element)); - jsonWriter.writeArrayField("$select", this.select, (writer, element) -> writer.writeString(element)); - jsonWriter.writeNumberField("$top", this.top); - return jsonWriter.writeEndObject(); - } - - /** - * Reads an instance of SuggestOptions from the JsonReader. - * - * @param jsonReader The JsonReader being read. - * @return An instance of SuggestOptions if the JsonReader was pointing to an instance of it, or null if it was - * pointing to JSON null. - * @throws IOException If an error occurs while reading the SuggestOptions. - */ - public static SuggestOptions fromJson(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - SuggestOptions deserializedSuggestOptions = new SuggestOptions(); - while (reader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = reader.getFieldName(); - reader.nextToken(); - if ("$filter".equals(fieldName)) { - deserializedSuggestOptions.filter = reader.getString(); - } else if ("UseFuzzyMatching".equals(fieldName)) { - deserializedSuggestOptions.useFuzzyMatching = reader.getNullable(JsonReader::getBoolean); - } else if ("highlightPostTag".equals(fieldName)) { - deserializedSuggestOptions.highlightPostTag = reader.getString(); - } else if ("highlightPreTag".equals(fieldName)) { - deserializedSuggestOptions.highlightPreTag = reader.getString(); - } else if ("minimumCoverage".equals(fieldName)) { - deserializedSuggestOptions.minimumCoverage = reader.getNullable(JsonReader::getDouble); - } else if ("OrderBy".equals(fieldName)) { - List orderBy = reader.readArray(reader1 -> reader1.getString()); - deserializedSuggestOptions.orderBy = orderBy; - } else if ("searchFields".equals(fieldName)) { - List searchFields = reader.readArray(reader1 -> reader1.getString()); - deserializedSuggestOptions.searchFields = searchFields; - } else if ("$select".equals(fieldName)) { - List select = reader.readArray(reader1 -> reader1.getString()); - deserializedSuggestOptions.select = select; - } else if ("$top".equals(fieldName)) { - deserializedSuggestOptions.top = reader.getNullable(JsonReader::getInt); - } else { - reader.skipChildren(); - } - } - return deserializedSuggestOptions; - }); - } -} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/implementation/models/SuggestRequest.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SuggestRequest.java similarity index 67% rename from sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/implementation/models/SuggestRequest.java rename to sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SuggestRequest.java index 2220894264c1..9089ba18aaf1 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/implementation/models/SuggestRequest.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SuggestRequest.java @@ -1,91 +1,107 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) TypeSpec Code Generator. -package com.azure.search.documents.implementation.models; +package com.azure.search.documents.models; import com.azure.core.annotation.Fluent; +import com.azure.core.annotation.Generated; import com.azure.json.JsonReader; import com.azure.json.JsonSerializable; import com.azure.json.JsonToken; import com.azure.json.JsonWriter; import java.io.IOException; -import java.util.ArrayList; -import java.util.List; /** - * Parameters for filtering, sorting, fuzzy matching, and other suggestions query behaviors. + * Parameters for filtering, sorting, fuzzy matching, and other suggestions query + * behaviors. */ @Fluent public final class SuggestRequest implements JsonSerializable { /* * An OData expression that filters the documents considered for suggestions. */ + @Generated private String filter; /* - * 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. + * 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. */ + @Generated private Boolean useFuzzyMatching; /* - * A string tag that is appended to hit highlights. Must be set with highlightPreTag. If omitted, hit highlighting - * of suggestions is disabled. + * A string tag that is appended to hit highlights. Must be set with + * highlightPreTag. If omitted, hit highlighting of suggestions is disabled. */ + @Generated private String highlightPostTag; /* - * A string tag that is prepended to hit highlights. Must be set with highlightPostTag. If omitted, hit highlighting - * of suggestions is disabled. + * A string tag that is prepended to hit highlights. Must be set with + * highlightPostTag. If omitted, hit highlighting of suggestions is disabled. */ + @Generated private String highlightPreTag; /* - * 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. + * 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. */ + @Generated private Double minimumCoverage; /* - * 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. - */ + * 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. + */ + @Generated private String orderBy; /* - * The search text to use to suggest documents. Must be at least 1 character, and no more than 100 characters. + * The search text to use to suggest documents. Must be at least 1 character, and + * no more than 100 characters. */ + @Generated private final String searchText; /* - * The comma-separated list of field names to search for the specified search text. Target fields must be included - * in the specified suggester. + * The comma-separated list of field names to search for the specified search + * text. Target fields must be included in the specified suggester. */ + @Generated private String searchFields; /* - * The comma-separated list of fields to retrieve. If unspecified, only the key field will be included in the - * results. + * The comma-separated list of fields to retrieve. If unspecified, only the key + * field will be included in the results. */ + @Generated private String select; /* - * The name of the suggester as specified in the suggesters collection that's part of the index definition. + * The name of the suggester as specified in the suggesters collection that's part + * of the index definition. */ + @Generated private final String suggesterName; /* - * The number of suggestions to retrieve. This must be a value between 1 and 100. The default is 5. + * The number of suggestions to retrieve. This must be a value between 1 and 100. + * The default is 5. */ + @Generated private Integer top; /** @@ -94,6 +110,7 @@ public final class SuggestRequest implements JsonSerializable { * @param searchText the searchText value to set. * @param suggesterName the suggesterName value to set. */ + @Generated public SuggestRequest(String searchText, String suggesterName) { this.searchText = searchText; this.suggesterName = suggesterName; @@ -104,6 +121,7 @@ public SuggestRequest(String searchText, String suggesterName) { * * @return the filter value. */ + @Generated public String getFilter() { return this.filter; } @@ -114,6 +132,7 @@ public String getFilter() { * @param filter the filter value to set. * @return the SuggestRequest object itself. */ + @Generated public SuggestRequest setFilter(String filter) { this.filter = filter; return this; @@ -121,25 +140,29 @@ public SuggestRequest setFilter(String filter) { /** * Get the useFuzzyMatching property: A value indicating whether to use fuzzy matching for the suggestion query. - * Default is false. When set to true, the query will find suggestions even if there's a substituted or missing - * character in the search text. While this provides a better experience in some scenarios, it comes at a - * performance cost as fuzzy suggestion searches are slower and consume more resources. + * Default 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. * * @return the useFuzzyMatching value. */ + @Generated public Boolean isUseFuzzyMatching() { return this.useFuzzyMatching; } /** * Set the useFuzzyMatching property: A value indicating whether to use fuzzy matching for the suggestion query. - * Default is false. When set to true, the query will find suggestions even if there's a substituted or missing - * character in the search text. While this provides a better experience in some scenarios, it comes at a - * performance cost as fuzzy suggestion searches are slower and consume more resources. + * Default 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. * * @param useFuzzyMatching the useFuzzyMatching value to set. * @return the SuggestRequest object itself. */ + @Generated public SuggestRequest setUseFuzzyMatching(Boolean useFuzzyMatching) { this.useFuzzyMatching = useFuzzyMatching; return this; @@ -151,6 +174,7 @@ public SuggestRequest setUseFuzzyMatching(Boolean useFuzzyMatching) { * * @return the highlightPostTag value. */ + @Generated public String getHighlightPostTag() { return this.highlightPostTag; } @@ -162,6 +186,7 @@ public String getHighlightPostTag() { * @param highlightPostTag the highlightPostTag value to set. * @return the SuggestRequest object itself. */ + @Generated public SuggestRequest setHighlightPostTag(String highlightPostTag) { this.highlightPostTag = highlightPostTag; return this; @@ -173,6 +198,7 @@ public SuggestRequest setHighlightPostTag(String highlightPostTag) { * * @return the highlightPreTag value. */ + @Generated public String getHighlightPreTag() { return this.highlightPreTag; } @@ -184,6 +210,7 @@ public String getHighlightPreTag() { * @param highlightPreTag the highlightPreTag value to set. * @return the SuggestRequest object itself. */ + @Generated public SuggestRequest setHighlightPreTag(String highlightPreTag) { this.highlightPreTag = highlightPreTag; return this; @@ -191,105 +218,120 @@ public SuggestRequest setHighlightPreTag(String highlightPreTag) { /** * Get the minimumCoverage property: 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. + * 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. * * @return the minimumCoverage value. */ + @Generated public Double getMinimumCoverage() { return this.minimumCoverage; } /** * Set the minimumCoverage property: 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. + * 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. * * @param minimumCoverage the minimumCoverage value to set. * @return the SuggestRequest object itself. */ + @Generated public SuggestRequest setMinimumCoverage(Double minimumCoverage) { this.minimumCoverage = minimumCoverage; return this; } /** - * Get the orderBy property: 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. + * Get the orderBy property: 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. * * @return the orderBy value. */ + @Generated public String getOrderBy() { return this.orderBy; } /** - * Set the orderBy property: 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. + * Set the orderBy property: 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. * * @param orderBy the orderBy value to set. * @return the SuggestRequest object itself. */ + @Generated public SuggestRequest setOrderBy(String orderBy) { this.orderBy = orderBy; return this; } /** - * Get the searchText property: The search text to use to suggest documents. Must be at least 1 character, and no - * more than 100 characters. + * Get the searchText property: The search text to use to suggest documents. Must be at least 1 character, and + * no more than 100 characters. * * @return the searchText value. */ + @Generated public String getSearchText() { return this.searchText; } /** - * Get the searchFields property: The comma-separated list of field names to search for the specified search text. - * Target fields must be included in the specified suggester. + * Get the searchFields property: The comma-separated list of field names to search for the specified search + * text. Target fields must be included in the specified suggester. * * @return the searchFields value. */ + @Generated public String getSearchFields() { return this.searchFields; } /** - * Set the searchFields property: The comma-separated list of field names to search for the specified search text. - * Target fields must be included in the specified suggester. + * Set the searchFields property: The comma-separated list of field names to search for the specified search + * text. Target fields must be included in the specified suggester. * * @param searchFields the searchFields value to set. * @return the SuggestRequest object itself. */ + @Generated public SuggestRequest setSearchFields(String searchFields) { this.searchFields = searchFields; return this; } /** - * Get the select property: The comma-separated list of fields to retrieve. If unspecified, only the key field will - * be included in the results. + * Get the select property: The comma-separated list of fields to retrieve. If unspecified, only the key + * field will be included in the results. * * @return the select value. */ + @Generated public String getSelect() { return this.select; } /** - * Set the select property: The comma-separated list of fields to retrieve. If unspecified, only the key field will - * be included in the results. + * Set the select property: The comma-separated list of fields to retrieve. If unspecified, only the key + * field will be included in the results. * * @param select the select value to set. * @return the SuggestRequest object itself. */ + @Generated public SuggestRequest setSelect(String select) { this.select = select; return this; @@ -301,27 +343,30 @@ public SuggestRequest setSelect(String select) { * * @return the suggesterName value. */ + @Generated public String getSuggesterName() { return this.suggesterName; } /** - * Get the top property: The number of suggestions to retrieve. This must be a value between 1 and 100. The default - * is 5. + * Get the top property: The number of suggestions to retrieve. This must be a value between 1 and 100. + * The default is 5. * * @return the top value. */ + @Generated public Integer getTop() { return this.top; } /** - * Set the top property: The number of suggestions to retrieve. This must be a value between 1 and 100. The default - * is 5. + * Set the top property: The number of suggestions to retrieve. This must be a value between 1 and 100. + * The default is 5. * * @param top the top value to set. * @return the SuggestRequest object itself. */ + @Generated public SuggestRequest setTop(Integer top) { this.top = top; return this; @@ -330,6 +375,7 @@ public SuggestRequest setTop(Integer top) { /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); @@ -356,11 +402,10 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { * @throws IllegalStateException If the deserialized JSON object was missing any required properties. * @throws IOException If an error occurs while reading the SuggestRequest. */ + @Generated public static SuggestRequest fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { - boolean searchTextFound = false; String searchText = null; - boolean suggesterNameFound = false; String suggesterName = null; String filter = null; Boolean useFuzzyMatching = null; @@ -377,10 +422,8 @@ public static SuggestRequest fromJson(JsonReader jsonReader) throws IOException if ("search".equals(fieldName)) { searchText = reader.getString(); - searchTextFound = true; } else if ("suggesterName".equals(fieldName)) { suggesterName = reader.getString(); - suggesterNameFound = true; } else if ("filter".equals(fieldName)) { filter = reader.getString(); } else if ("fuzzy".equals(fieldName)) { @@ -403,30 +446,18 @@ public static SuggestRequest fromJson(JsonReader jsonReader) throws IOException reader.skipChildren(); } } - if (searchTextFound && suggesterNameFound) { - SuggestRequest deserializedSuggestRequest = new SuggestRequest(searchText, suggesterName); - deserializedSuggestRequest.filter = filter; - deserializedSuggestRequest.useFuzzyMatching = useFuzzyMatching; - deserializedSuggestRequest.highlightPostTag = highlightPostTag; - deserializedSuggestRequest.highlightPreTag = highlightPreTag; - deserializedSuggestRequest.minimumCoverage = minimumCoverage; - deserializedSuggestRequest.orderBy = orderBy; - deserializedSuggestRequest.searchFields = searchFields; - deserializedSuggestRequest.select = select; - deserializedSuggestRequest.top = top; - - return deserializedSuggestRequest; - } - List missingProperties = new ArrayList<>(); - if (!searchTextFound) { - missingProperties.add("search"); - } - if (!suggesterNameFound) { - missingProperties.add("suggesterName"); - } - - throw new IllegalStateException( - "Missing required property/properties: " + String.join(", ", missingProperties)); + SuggestRequest deserializedSuggestRequest = new SuggestRequest(searchText, suggesterName); + deserializedSuggestRequest.filter = filter; + deserializedSuggestRequest.useFuzzyMatching = useFuzzyMatching; + deserializedSuggestRequest.highlightPostTag = highlightPostTag; + deserializedSuggestRequest.highlightPreTag = highlightPreTag; + deserializedSuggestRequest.minimumCoverage = minimumCoverage; + deserializedSuggestRequest.orderBy = orderBy; + deserializedSuggestRequest.searchFields = searchFields; + deserializedSuggestRequest.select = select; + deserializedSuggestRequest.top = top; + + return deserializedSuggestRequest; }); } } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SuggestResult.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SuggestResult.java index f1ae0f6b42c1..150c41421758 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SuggestResult.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SuggestResult.java @@ -1,85 +1,125 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.search.documents.models; -import com.azure.core.annotation.Fluent; -import com.azure.core.util.serializer.JsonSerializer; -import com.azure.search.documents.SearchDocument; -import com.azure.search.documents.implementation.converters.SuggestResultHelper; - -import static com.azure.core.util.serializer.TypeReference.createInstance; +import com.azure.core.annotation.Generated; +import com.azure.core.annotation.Immutable; +import com.azure.core.util.BinaryData; +import com.azure.json.JsonReader; +import com.azure.json.JsonSerializable; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import java.io.IOException; +import java.util.LinkedHashMap; +import java.util.Map; /** * A result containing a document found by a suggestion query, plus associated * metadata. */ -@Fluent -public final class SuggestResult { - /* - * Unmatched properties from the message are deserialized this collection - */ - private SearchDocument additionalProperties; - +@Immutable +public final class SuggestResult implements JsonSerializable { /* * The text of the suggestion result. */ + @Generated private final String text; - private JsonSerializer jsonSerializer; - - static { - SuggestResultHelper.setAccessor(new SuggestResultHelper.SuggestResultAccessor() { - @Override - public void setAdditionalProperties(SuggestResult suggestResult, SearchDocument additionalProperties) { - suggestResult.setAdditionalProperties(additionalProperties); - } + /* + * A result containing a document found by a suggestion query, plus associated + * metadata. + */ + @Generated + private Map additionalProperties; - @Override - public void setJsonSerializer(SuggestResult suggestResult, JsonSerializer jsonSerializer) { - suggestResult.jsonSerializer = jsonSerializer; - } - }); + /** + * Creates an instance of SuggestResult class. + * + * @param text the text value to set. + */ + @Generated + private SuggestResult(String text) { + this.text = text; } /** - * Constructor of {@link SuggestResult}. - * - * @param text The text of the suggestion result. + * Get the text property: The text of the suggestion result. + * + * @return the text value. */ - public SuggestResult(String text) { - this.text = text; + @Generated + public String getText() { + return this.text; } /** - * Get the additionalProperties property: Unmatched properties from the - * message are deserialized this collection. - * - * @param modelClass The model class converts to. - * @param Convert document to the generic type. + * Get the additionalProperties property: A result containing a document found by a suggestion query, plus + * associated + * metadata. + * * @return the additionalProperties value. */ - public T getDocument(Class modelClass) { - return jsonSerializer.deserializeFromBytes(jsonSerializer.serializeToBytes(additionalProperties), - createInstance(modelClass)); + @Generated + public Map getAdditionalProperties() { + return this.additionalProperties; } /** - * Get the text property: The text of the suggestion result. - * - * @return the text value. + * {@inheritDoc} */ - public String getText() { - return this.text; + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("@search.text", this.text); + if (additionalProperties != null) { + for (Map.Entry additionalProperty : additionalProperties.entrySet()) { + jsonWriter.writeFieldName(additionalProperty.getKey()); + if (additionalProperty.getValue() == null) { + jsonWriter.writeNull(); + } else { + additionalProperty.getValue().writeTo(jsonWriter); + } + } + } + return jsonWriter.writeEndObject(); } /** - * The private setter to set the select property - * via {@link SuggestResultHelper.SuggestResultAccessor}. - * - * @param additionalProperties The unmatched properties from the message. + * Reads an instance of SuggestResult from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of SuggestResult if the JsonReader was pointing to an instance of it, or null if it was + * pointing to JSON null. + * @throws IllegalStateException If the deserialized JSON object was missing any required properties. + * @throws IOException If an error occurs while reading the SuggestResult. */ - private void setAdditionalProperties(SearchDocument additionalProperties) { - this.additionalProperties = additionalProperties; + @Generated + public static SuggestResult fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + String text = null; + Map additionalProperties = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("@search.text".equals(fieldName)) { + text = reader.getString(); + } else { + if (additionalProperties == null) { + additionalProperties = new LinkedHashMap<>(); + } + + additionalProperties.put(fieldName, + reader.getNullable(nonNullReader -> BinaryData.fromObject(nonNullReader.readUntyped()))); + } + } + SuggestResult deserializedSuggestResult = new SuggestResult(text); + deserializedSuggestResult.additionalProperties = additionalProperties; + + return deserializedSuggestResult; + }); } } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/SynonymMap.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SynonymMap.java similarity index 52% rename from sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/SynonymMap.java rename to sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SynonymMap.java index fb8bbc98a3f4..f1d8fc2c9ebf 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/SynonymMap.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SynonymMap.java @@ -1,11 +1,11 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. -package com.azure.search.documents.indexes.models; +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.search.documents.models; import com.azure.core.annotation.Fluent; +import com.azure.core.annotation.Generated; import com.azure.json.JsonReader; import com.azure.json.JsonSerializable; import com.azure.json.JsonToken; @@ -17,101 +17,121 @@ */ @Fluent public final class SynonymMap implements JsonSerializable { - /* * The name of the synonym map. */ - private String name; + @Generated + private final String name; /* * The format of the synonym map. Only the 'solr' format is currently supported. */ - private String format = "solr"; + @Generated + private final String format = "solr"; /* - * A series of synonym rules in the specified synonym map format. The rules must be separated by newlines. + * A series of synonym rules in the specified synonym map format. The rules must + * be separated by newlines. */ - private String synonyms; + @Generated + private final String synonyms; /* - * 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. + * 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. */ + @Generated private SearchResourceEncryptionKey encryptionKey; /* * The ETag of the synonym map. */ + @Generated private String eTag; /** * Creates an instance of SynonymMap class. + * + * @param name the name value to set. + * @param synonyms the synonyms value to set. */ - public SynonymMap() { + @Generated + public SynonymMap(String name, String synonyms) { + this.name = name; + this.synonyms = synonyms; } /** * Get the name property: The name of the synonym map. - * + * * @return the name value. */ + @Generated public String getName() { return this.name; } /** - * Get the synonyms property: A series of synonym rules in the specified synonym map format. The rules must be - * separated by newlines. - * - * @return the synonyms value. + * Get the format property: The format of the synonym map. Only the 'solr' format is currently supported. + * + * @return the format value. */ - public String getSynonyms() { - return this.synonyms; + @Generated + public String getFormat() { + return this.format; } /** - * Set the synonyms property: A series of synonym rules in the specified synonym map format. The rules must be - * separated by newlines. - * - * @param synonyms the synonyms value to set. - * @return the SynonymMap object itself. + * Get the synonyms property: A series of synonym rules in the specified synonym map format. The rules must + * be separated by newlines. + * + * @return the synonyms value. */ - public SynonymMap setSynonyms(String synonyms) { - this.synonyms = synonyms; - return this; + @Generated + public String getSynonyms() { + return this.synonyms; } /** * Get the encryptionKey property: 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 + * 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. - * + * * @return the encryptionKey value. */ + @Generated public SearchResourceEncryptionKey getEncryptionKey() { return this.encryptionKey; } /** * Set the encryptionKey property: 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 + * 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. - * + * * @param encryptionKey the encryptionKey value to set. * @return the SynonymMap object itself. */ + @Generated public SynonymMap setEncryptionKey(SearchResourceEncryptionKey encryptionKey) { this.encryptionKey = encryptionKey; return this; @@ -119,19 +139,21 @@ public SynonymMap setEncryptionKey(SearchResourceEncryptionKey encryptionKey) { /** * Get the eTag property: The ETag of the synonym map. - * + * * @return the eTag value. */ + @Generated public String getETag() { return this.eTag; } /** * Set the eTag property: The ETag of the synonym map. - * + * * @param eTag the eTag value to set. * @return the SynonymMap object itself. */ + @Generated public SynonymMap setETag(String eTag) { this.eTag = eTag; return this; @@ -140,6 +162,7 @@ public SynonymMap setETag(String eTag) { /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); @@ -153,68 +176,41 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of SynonymMap from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of SynonymMap if the JsonReader was pointing to an instance of it, or null if it was pointing * to JSON null. + * @throws IllegalStateException If the deserialized JSON object was missing any required properties. * @throws IOException If an error occurs while reading the SynonymMap. */ + @Generated public static SynonymMap fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { - SynonymMap deserializedSynonymMap = new SynonymMap(); + String name = null; + String synonyms = null; + SearchResourceEncryptionKey encryptionKey = null; + String eTag = null; while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); + if ("name".equals(fieldName)) { - deserializedSynonymMap.name = reader.getString(); - } else if ("format".equals(fieldName)) { - deserializedSynonymMap.format = reader.getString(); + name = reader.getString(); } else if ("synonyms".equals(fieldName)) { - deserializedSynonymMap.synonyms = reader.getString(); + synonyms = reader.getString(); } else if ("encryptionKey".equals(fieldName)) { - deserializedSynonymMap.encryptionKey = SearchResourceEncryptionKey.fromJson(reader); + encryptionKey = SearchResourceEncryptionKey.fromJson(reader); } else if ("@odata.etag".equals(fieldName)) { - deserializedSynonymMap.eTag = reader.getString(); + eTag = reader.getString(); } else { reader.skipChildren(); } } + SynonymMap deserializedSynonymMap = new SynonymMap(name, synonyms); + deserializedSynonymMap.encryptionKey = encryptionKey; + deserializedSynonymMap.eTag = eTag; + return deserializedSynonymMap; }); } - - /** - * Constructor of {@link SynonymMap}. - * - * @param name The name of the synonym map. - */ - public SynonymMap(String name) { - this(name, null); - } - - /** - * Constructor of {@link SynonymMap}. - * - * @param name The name of the synonym map. - * @param synonyms A series of synonym rules in the specified synonym map format. The rules must be separated by - * newlines. - */ - public SynonymMap(String name, String synonyms) { - this.format = "solr"; - this.name = name; - this.synonyms = synonyms; - } - - /** - * Creates a new instance of SynonymMap with synonyms read from the passed file. - * - * @param name The name of the synonym map. - * @param filePath The path to the file where the formatted synonyms are read. - * @return A SynonymMap. - * @throws java.io.UncheckedIOException If reading {@code filePath} fails. - */ - public static SynonymMap createFromFile(String name, java.nio.file.Path filePath) { - String synonyms = com.azure.search.documents.implementation.util.Utility.readSynonymsFromFile(filePath); - return new SynonymMap(name, synonyms); - } } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/SynonymTokenFilter.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SynonymTokenFilter.java similarity index 50% rename from sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/SynonymTokenFilter.java rename to sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SynonymTokenFilter.java index 32632d91e589..8eb6360d06b1 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/SynonymTokenFilter.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SynonymTokenFilter.java @@ -1,130 +1,148 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. -package com.azure.search.documents.indexes.models; +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.search.documents.models; import com.azure.core.annotation.Fluent; +import com.azure.core.annotation.Generated; import com.azure.json.JsonReader; import com.azure.json.JsonToken; import com.azure.json.JsonWriter; import java.io.IOException; -import java.util.ArrayList; import java.util.List; /** - * Matches single or multi-word synonyms in a token stream. This token filter is implemented using Apache Lucene. + * Matches single or multi-word synonyms in a token stream. This token filter is + * implemented using Apache Lucene. */ @Fluent public final class SynonymTokenFilter extends TokenFilter { - /* - * A URI fragment specifying the type of token filter. + * The discriminator for derived types. */ + @Generated private String odataType = "#Microsoft.Azure.Search.SynonymTokenFilter"; /* - * 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. + * 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. */ + @Generated private final List synonyms; /* * A value indicating whether to case-fold input for matching. Default is false. */ - private Boolean caseIgnored; + @Generated + private Boolean ignoreCase; /* - * 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. + * 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. */ + @Generated private Boolean expand; /** * Creates an instance of SynonymTokenFilter class. - * + * * @param name the name value to set. * @param synonyms the synonyms value to set. */ + @Generated public SynonymTokenFilter(String name, List synonyms) { super(name); this.synonyms = synonyms; } /** - * Get the odataType property: A URI fragment specifying the type of token filter. - * + * Get the odataType property: The discriminator for derived types. + * * @return the odataType value. */ + @Generated @Override public String getOdataType() { return this.odataType; } /** - * Get the synonyms property: 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 + * Get the synonyms property: 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. - * + * * @return the synonyms value. */ + @Generated public List getSynonyms() { return this.synonyms; } /** - * Get the caseIgnored property: A value indicating whether to case-fold input for matching. Default is false. - * - * @return the caseIgnored value. + * Get the ignoreCase property: A value indicating whether to case-fold input for matching. Default is false. + * + * @return the ignoreCase value. */ - public Boolean isCaseIgnored() { - return this.caseIgnored; + @Generated + public Boolean isIgnoreCase() { + return this.ignoreCase; } /** - * Set the caseIgnored property: A value indicating whether to case-fold input for matching. Default is false. - * - * @param caseIgnored the caseIgnored value to set. + * Set the ignoreCase property: A value indicating whether to case-fold input for matching. Default is false. + * + * @param ignoreCase the ignoreCase value to set. * @return the SynonymTokenFilter object itself. */ - public SynonymTokenFilter setCaseIgnored(Boolean caseIgnored) { - this.caseIgnored = caseIgnored; + @Generated + public SynonymTokenFilter setIgnoreCase(Boolean ignoreCase) { + this.ignoreCase = ignoreCase; return this; } /** - * Get the expand property: 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. - * + * Get the expand property: 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. + * * @return the expand value. */ - public Boolean getExpand() { + @Generated + public Boolean isExpand() { return this.expand; } /** - * Set the expand property: 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. - * + * Set the expand property: 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. + * * @param expand the expand value to set. * @return the SynonymTokenFilter object itself. */ + @Generated public SynonymTokenFilter setExpand(Boolean expand) { this.expand = expand; return this; @@ -133,70 +151,59 @@ public SynonymTokenFilter setExpand(Boolean expand) { /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); jsonWriter.writeStringField("name", getName()); jsonWriter.writeArrayField("synonyms", this.synonyms, (writer, element) -> writer.writeString(element)); jsonWriter.writeStringField("@odata.type", this.odataType); - jsonWriter.writeBooleanField("ignoreCase", this.caseIgnored); + jsonWriter.writeBooleanField("ignoreCase", this.ignoreCase); jsonWriter.writeBooleanField("expand", this.expand); return jsonWriter.writeEndObject(); } /** * Reads an instance of SynonymTokenFilter from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of SynonymTokenFilter if the JsonReader was pointing to an instance of it, or null if it was * pointing to JSON null. * @throws IllegalStateException If the deserialized JSON object was missing any required properties. * @throws IOException If an error occurs while reading the SynonymTokenFilter. */ + @Generated public static SynonymTokenFilter fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { - boolean nameFound = false; String name = null; - boolean synonymsFound = false; List synonyms = null; String odataType = "#Microsoft.Azure.Search.SynonymTokenFilter"; - Boolean caseIgnored = null; + Boolean ignoreCase = null; Boolean expand = null; while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); + if ("name".equals(fieldName)) { name = reader.getString(); - nameFound = true; } else if ("synonyms".equals(fieldName)) { synonyms = reader.readArray(reader1 -> reader1.getString()); - synonymsFound = true; } else if ("@odata.type".equals(fieldName)) { odataType = reader.getString(); } else if ("ignoreCase".equals(fieldName)) { - caseIgnored = reader.getNullable(JsonReader::getBoolean); + ignoreCase = reader.getNullable(JsonReader::getBoolean); } else if ("expand".equals(fieldName)) { expand = reader.getNullable(JsonReader::getBoolean); } else { reader.skipChildren(); } } - if (nameFound && synonymsFound) { - SynonymTokenFilter deserializedSynonymTokenFilter = new SynonymTokenFilter(name, synonyms); - deserializedSynonymTokenFilter.odataType = odataType; - deserializedSynonymTokenFilter.caseIgnored = caseIgnored; - deserializedSynonymTokenFilter.expand = expand; - return deserializedSynonymTokenFilter; - } - List missingProperties = new ArrayList<>(); - if (!nameFound) { - missingProperties.add("name"); - } - if (!synonymsFound) { - missingProperties.add("synonyms"); - } - throw new IllegalStateException( - "Missing required property/properties: " + String.join(", ", missingProperties)); + SynonymTokenFilter deserializedSynonymTokenFilter = new SynonymTokenFilter(name, synonyms); + deserializedSynonymTokenFilter.odataType = odataType; + deserializedSynonymTokenFilter.ignoreCase = ignoreCase; + deserializedSynonymTokenFilter.expand = expand; + + return deserializedSynonymTokenFilter; }); } } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/TagScoringFunction.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/TagScoringFunction.java similarity index 68% rename from sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/TagScoringFunction.java rename to sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/TagScoringFunction.java index 87ea7a507d8e..6be8d8ee1eb0 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/TagScoringFunction.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/TagScoringFunction.java @@ -1,33 +1,32 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) TypeSpec Code Generator. -package com.azure.search.documents.indexes.models; +package com.azure.search.documents.models; import com.azure.core.annotation.Fluent; +import com.azure.core.annotation.Generated; import com.azure.json.JsonReader; import com.azure.json.JsonToken; import com.azure.json.JsonWriter; import java.io.IOException; -import java.util.ArrayList; -import java.util.List; /** - * Defines a function that boosts scores of documents with string values matching a given list of tags. + * Defines a function that boosts scores of documents with string values matching + * a given list of tags. */ @Fluent public final class TagScoringFunction extends ScoringFunction { /* - * Indicates the type of function to use. Valid values include magnitude, freshness, distance, and tag. The function - * type must be lower case. + * Type of ScoringFunction. */ + @Generated private String type = "tag"; /* * Parameter values for the tag scoring function. */ + @Generated private final TagScoringParameters parameters; /** @@ -37,17 +36,18 @@ public final class TagScoringFunction extends ScoringFunction { * @param boost the boost value to set. * @param parameters the parameters value to set. */ + @Generated public TagScoringFunction(String fieldName, double boost, TagScoringParameters parameters) { super(fieldName, boost); this.parameters = parameters; } /** - * Get the type property: Indicates the type of function to use. Valid values include magnitude, freshness, - * distance, and tag. The function type must be lower case. + * Get the type property: Type of ScoringFunction. * * @return the type value. */ + @Generated @Override public String getType() { return this.type; @@ -58,6 +58,7 @@ public String getType() { * * @return the parameters value. */ + @Generated public TagScoringParameters getParameters() { return this.parameters; } @@ -65,6 +66,7 @@ public TagScoringParameters getParameters() { /** * {@inheritDoc} */ + @Generated @Override public TagScoringFunction setInterpolation(ScoringFunctionInterpolation interpolation) { super.setInterpolation(interpolation); @@ -74,6 +76,7 @@ public TagScoringFunction setInterpolation(ScoringFunctionInterpolation interpol /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); @@ -94,14 +97,12 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { * @throws IllegalStateException If the deserialized JSON object was missing any required properties. * @throws IOException If an error occurs while reading the TagScoringFunction. */ + @Generated public static TagScoringFunction fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { - boolean fieldNameFound = false; String fieldName = null; - boolean boostFound = false; double boost = 0.0; ScoringFunctionInterpolation interpolation = null; - boolean parametersFound = false; TagScoringParameters parameters = null; String type = "tag"; while (reader.nextToken() != JsonToken.END_OBJECT) { @@ -110,42 +111,23 @@ public static TagScoringFunction fromJson(JsonReader jsonReader) throws IOExcept if ("fieldName".equals(jsonFieldName)) { fieldName = reader.getString(); - fieldNameFound = true; } else if ("boost".equals(jsonFieldName)) { boost = reader.getDouble(); - boostFound = true; } else if ("interpolation".equals(jsonFieldName)) { interpolation = ScoringFunctionInterpolation.fromString(reader.getString()); } else if ("tag".equals(jsonFieldName)) { parameters = TagScoringParameters.fromJson(reader); - parametersFound = true; } else if ("type".equals(jsonFieldName)) { type = reader.getString(); } else { reader.skipChildren(); } } - if (fieldNameFound && boostFound && parametersFound) { - TagScoringFunction deserializedTagScoringFunction - = new TagScoringFunction(fieldName, boost, parameters); - deserializedTagScoringFunction.setInterpolation(interpolation); - deserializedTagScoringFunction.type = type; + TagScoringFunction deserializedTagScoringFunction = new TagScoringFunction(fieldName, boost, parameters); + deserializedTagScoringFunction.setInterpolation(interpolation); + deserializedTagScoringFunction.type = type; - return deserializedTagScoringFunction; - } - List missingProperties = new ArrayList<>(); - if (!fieldNameFound) { - missingProperties.add("fieldName"); - } - if (!boostFound) { - missingProperties.add("boost"); - } - if (!parametersFound) { - missingProperties.add("tag"); - } - - throw new IllegalStateException( - "Missing required property/properties: " + String.join(", ", missingProperties)); + return deserializedTagScoringFunction; }); } } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/TagScoringParameters.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/TagScoringParameters.java similarity index 78% rename from sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/TagScoringParameters.java rename to sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/TagScoringParameters.java index 6700026f5703..86b864ba3690 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/TagScoringParameters.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/TagScoringParameters.java @@ -1,11 +1,10 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) TypeSpec Code Generator. -package com.azure.search.documents.indexes.models; +package com.azure.search.documents.models; +import com.azure.core.annotation.Generated; import com.azure.core.annotation.Immutable; import com.azure.json.JsonReader; import com.azure.json.JsonSerializable; @@ -19,9 +18,10 @@ @Immutable public final class TagScoringParameters implements JsonSerializable { /* - * The name of the parameter passed in search queries to specify the list of tags to compare against the target - * field. + * The name of the parameter passed in search queries to specify the list of tags + * to compare against the target field. */ + @Generated private final String tagsParameter; /** @@ -29,16 +29,18 @@ public final class TagScoringParameters implements JsonSerializable { - boolean tagsParameterFound = false; String tagsParameter = null; while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); @@ -72,15 +75,11 @@ public static TagScoringParameters fromJson(JsonReader jsonReader) throws IOExce if ("tagsParameter".equals(fieldName)) { tagsParameter = reader.getString(); - tagsParameterFound = true; } else { reader.skipChildren(); } } - if (tagsParameterFound) { - return new TagScoringParameters(tagsParameter); - } - throw new IllegalStateException("Missing required property: tagsParameter"); + return new TagScoringParameters(tagsParameter); }); } } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/TextResult.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/TextResult.java index 53811f11c5b8..c5d8d35608d1 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/TextResult.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/TextResult.java @@ -1,11 +1,10 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.search.documents.models; +import com.azure.core.annotation.Generated; import com.azure.core.annotation.Immutable; import com.azure.json.JsonReader; import com.azure.json.JsonSerializable; @@ -21,12 +20,14 @@ public final class TextResult implements JsonSerializable { /* * The BM25 or Classic score for the text portion of the query. */ + @Generated private Double searchScore; /** * Creates an instance of TextResult class. */ - public TextResult() { + @Generated + private TextResult() { } /** @@ -34,6 +35,7 @@ public TextResult() { * * @return the searchScore value. */ + @Generated public Double getSearchScore() { return this.searchScore; } @@ -41,6 +43,7 @@ public Double getSearchScore() { /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); @@ -55,6 +58,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { * to JSON null. * @throws IOException If an error occurs while reading the TextResult. */ + @Generated public static TextResult fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { TextResult deserializedTextResult = new TextResult(); diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/TextSplitMode.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/TextSplitMode.java similarity index 85% rename from sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/TextSplitMode.java rename to sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/TextSplitMode.java index 997d3189c0ef..b1fff91d7e65 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/TextSplitMode.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/TextSplitMode.java @@ -1,11 +1,10 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) TypeSpec Code Generator. -package com.azure.search.documents.indexes.models; +package com.azure.search.documents.models; +import com.azure.core.annotation.Generated; import com.azure.core.util.ExpandableStringEnum; import java.util.Collection; @@ -16,11 +15,13 @@ public final class TextSplitMode extends ExpandableStringEnum { /** * Split the text into individual pages. */ + @Generated public static final TextSplitMode PAGES = fromString("pages"); /** * Split the text into individual sentences. */ + @Generated public static final TextSplitMode SENTENCES = fromString("sentences"); /** @@ -28,6 +29,7 @@ public final class TextSplitMode extends ExpandableStringEnum { * * @deprecated Use the {@link #fromString(String)} factory method. */ + @Generated @Deprecated public TextSplitMode() { } @@ -38,6 +40,7 @@ public TextSplitMode() { * @param name a name to look for. * @return the corresponding TextSplitMode. */ + @Generated public static TextSplitMode fromString(String name) { return fromString(name, TextSplitMode.class); } @@ -47,6 +50,7 @@ public static TextSplitMode fromString(String name) { * * @return known TextSplitMode values. */ + @Generated public static Collection values() { return values(TextSplitMode.class); } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/TextTranslationSkill.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/TextTranslationSkill.java similarity index 75% rename from sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/TextTranslationSkill.java rename to sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/TextTranslationSkill.java index e33c2e3016ec..f7e6b1fd8a38 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/TextTranslationSkill.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/TextTranslationSkill.java @@ -1,17 +1,15 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) TypeSpec Code Generator. -package com.azure.search.documents.indexes.models; +package com.azure.search.documents.models; import com.azure.core.annotation.Fluent; +import com.azure.core.annotation.Generated; import com.azure.json.JsonReader; import com.azure.json.JsonToken; import com.azure.json.JsonWriter; import java.io.IOException; -import java.util.ArrayList; import java.util.List; /** @@ -20,25 +18,31 @@ @Fluent public final class TextTranslationSkill extends SearchIndexerSkill { /* - * A URI fragment specifying the type of skill. + * The discriminator for derived types. */ + @Generated private String odataType = "#Microsoft.Skills.Text.TranslationSkill"; /* - * The language code to translate documents into for documents that don't specify the to language explicitly. + * The language code to translate documents into for documents that don't specify + * the to language explicitly. */ + @Generated private final TextTranslationSkillLanguage defaultToLanguageCode; /* - * The language code to translate documents from for documents that don't specify the from language explicitly. + * The language code to translate documents from for documents that don't specify + * the from language explicitly. */ + @Generated private TextTranslationSkillLanguage defaultFromLanguageCode; /* - * 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`. + * 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`. */ + @Generated private TextTranslationSkillLanguage suggestedFrom; /** @@ -48,6 +52,7 @@ public final class TextTranslationSkill extends SearchIndexerSkill { * @param outputs the outputs value to set. * @param defaultToLanguageCode the defaultToLanguageCode value to set. */ + @Generated public TextTranslationSkill(List inputs, List outputs, TextTranslationSkillLanguage defaultToLanguageCode) { super(inputs, outputs); @@ -55,10 +60,11 @@ public TextTranslationSkill(List inputs, List { - boolean inputsFound = false; List inputs = null; - boolean outputsFound = false; List outputs = null; String name = null; String description = null; String context = null; - boolean defaultToLanguageCodeFound = false; TextTranslationSkillLanguage defaultToLanguageCode = null; String odataType = "#Microsoft.Skills.Text.TranslationSkill"; TextTranslationSkillLanguage defaultFromLanguageCode = null; @@ -196,10 +212,8 @@ public static TextTranslationSkill fromJson(JsonReader jsonReader) throws IOExce if ("inputs".equals(fieldName)) { inputs = reader.readArray(reader1 -> InputFieldMappingEntry.fromJson(reader1)); - inputsFound = true; } else if ("outputs".equals(fieldName)) { outputs = reader.readArray(reader1 -> OutputFieldMappingEntry.fromJson(reader1)); - outputsFound = true; } else if ("name".equals(fieldName)) { name = reader.getString(); } else if ("description".equals(fieldName)) { @@ -208,7 +222,6 @@ public static TextTranslationSkill fromJson(JsonReader jsonReader) throws IOExce context = reader.getString(); } else if ("defaultToLanguageCode".equals(fieldName)) { defaultToLanguageCode = TextTranslationSkillLanguage.fromString(reader.getString()); - defaultToLanguageCodeFound = true; } else if ("@odata.type".equals(fieldName)) { odataType = reader.getString(); } else if ("defaultFromLanguageCode".equals(fieldName)) { @@ -219,31 +232,16 @@ public static TextTranslationSkill fromJson(JsonReader jsonReader) throws IOExce reader.skipChildren(); } } - if (inputsFound && outputsFound && defaultToLanguageCodeFound) { - TextTranslationSkill deserializedTextTranslationSkill - = new TextTranslationSkill(inputs, outputs, defaultToLanguageCode); - deserializedTextTranslationSkill.setName(name); - deserializedTextTranslationSkill.setDescription(description); - deserializedTextTranslationSkill.setContext(context); - deserializedTextTranslationSkill.odataType = odataType; - deserializedTextTranslationSkill.defaultFromLanguageCode = defaultFromLanguageCode; - deserializedTextTranslationSkill.suggestedFrom = suggestedFrom; - - return deserializedTextTranslationSkill; - } - List missingProperties = new ArrayList<>(); - if (!inputsFound) { - missingProperties.add("inputs"); - } - if (!outputsFound) { - missingProperties.add("outputs"); - } - if (!defaultToLanguageCodeFound) { - missingProperties.add("defaultToLanguageCode"); - } - - throw new IllegalStateException( - "Missing required property/properties: " + String.join(", ", missingProperties)); + TextTranslationSkill deserializedTextTranslationSkill + = new TextTranslationSkill(inputs, outputs, defaultToLanguageCode); + deserializedTextTranslationSkill.setName(name); + deserializedTextTranslationSkill.setDescription(description); + deserializedTextTranslationSkill.setContext(context); + deserializedTextTranslationSkill.odataType = odataType; + deserializedTextTranslationSkill.defaultFromLanguageCode = defaultFromLanguageCode; + deserializedTextTranslationSkill.suggestedFrom = suggestedFrom; + + return deserializedTextTranslationSkill; }); } } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/TextTranslationSkillLanguage.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/TextTranslationSkillLanguage.java similarity index 87% rename from sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/TextTranslationSkillLanguage.java rename to sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/TextTranslationSkillLanguage.java index c7ede27aa338..e9c6475bd516 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/TextTranslationSkillLanguage.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/TextTranslationSkillLanguage.java @@ -1,11 +1,10 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) TypeSpec Code Generator. -package com.azure.search.documents.indexes.models; +package com.azure.search.documents.models; +import com.azure.core.annotation.Generated; import com.azure.core.util.ExpandableStringEnum; import java.util.Collection; @@ -16,361 +15,433 @@ public final class TextTranslationSkillLanguage extends ExpandableStringEnum values() { return values(TextTranslationSkillLanguage.class); } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/TextWeights.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/TextWeights.java similarity index 77% rename from sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/TextWeights.java rename to sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/TextWeights.java index 8c610cfa73d8..f7df04742519 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/TextWeights.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/TextWeights.java @@ -1,11 +1,10 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) TypeSpec Code Generator. -package com.azure.search.documents.indexes.models; +package com.azure.search.documents.models; +import com.azure.core.annotation.Generated; import com.azure.core.annotation.Immutable; import com.azure.json.JsonReader; import com.azure.json.JsonSerializable; @@ -15,14 +14,16 @@ import java.util.Map; /** - * Defines weights on index fields for which matches should boost scoring in search queries. + * Defines weights on index fields for which matches should boost scoring in + * search queries. */ @Immutable public final class TextWeights implements JsonSerializable { /* - * The dictionary of per-field weights to boost document scoring. The keys are field names and the values are the - * weights for each field. + * The dictionary of per-field weights to boost document scoring. The keys are + * field names and the values are the weights for each field. */ + @Generated private final Map weights; /** @@ -30,16 +31,18 @@ public final class TextWeights implements JsonSerializable { * * @param weights the weights value to set. */ + @Generated public TextWeights(Map weights) { this.weights = weights; } /** - * Get the weights property: The dictionary of per-field weights to boost document scoring. The keys are field names - * and the values are the weights for each field. + * Get the weights property: The dictionary of per-field weights to boost document scoring. The keys are + * field names and the values are the weights for each field. * * @return the weights value. */ + @Generated public Map getWeights() { return this.weights; } @@ -47,6 +50,7 @@ public Map getWeights() { /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); @@ -63,9 +67,9 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { * @throws IllegalStateException If the deserialized JSON object was missing any required properties. * @throws IOException If an error occurs while reading the TextWeights. */ + @Generated public static TextWeights fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { - boolean weightsFound = false; Map weights = null; while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); @@ -73,15 +77,11 @@ public static TextWeights fromJson(JsonReader jsonReader) throws IOException { if ("weights".equals(fieldName)) { weights = reader.readMap(reader1 -> reader1.getDouble()); - weightsFound = true; } else { reader.skipChildren(); } } - if (weightsFound) { - return new TextWeights(weights); - } - throw new IllegalStateException("Missing required property: weights"); + return new TextWeights(weights); }); } } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/TokenCharacterKind.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/TokenCharacterKind.java new file mode 100644 index 000000000000..b563c3fb5c8c --- /dev/null +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/TokenCharacterKind.java @@ -0,0 +1,75 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.search.documents.models; + +import com.azure.core.annotation.Generated; +import com.azure.core.util.ExpandableStringEnum; +import java.util.Collection; + +/** + * Represents classes of characters on which a token filter can operate. + */ +public final class TokenCharacterKind extends ExpandableStringEnum { + /** + * Keeps letters in tokens. + */ + @Generated + public static final TokenCharacterKind LETTER = fromString("letter"); + + /** + * Keeps digits in tokens. + */ + @Generated + public static final TokenCharacterKind DIGIT = fromString("digit"); + + /** + * Keeps whitespace in tokens. + */ + @Generated + public static final TokenCharacterKind WHITESPACE = fromString("whitespace"); + + /** + * Keeps punctuation in tokens. + */ + @Generated + public static final TokenCharacterKind PUNCTUATION = fromString("punctuation"); + + /** + * Keeps symbols in tokens. + */ + @Generated + public static final TokenCharacterKind SYMBOL = fromString("symbol"); + + /** + * Creates a new instance of TokenCharacterKind value. + * + * @deprecated Use the {@link #fromString(String)} factory method. + */ + @Generated + @Deprecated + public TokenCharacterKind() { + } + + /** + * Creates or finds a TokenCharacterKind from its string representation. + * + * @param name a name to look for. + * @return the corresponding TokenCharacterKind. + */ + @Generated + public static TokenCharacterKind fromString(String name) { + return fromString(name, TokenCharacterKind.class); + } + + /** + * Gets known TokenCharacterKind values. + * + * @return known TokenCharacterKind values. + */ + @Generated + public static Collection values() { + return values(TokenCharacterKind.class); + } +} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/TokenFilter.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/TokenFilter.java similarity index 81% rename from sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/TokenFilter.java rename to sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/TokenFilter.java index 9c76e220f495..baeac6f0e60c 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/TokenFilter.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/TokenFilter.java @@ -1,20 +1,15 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) TypeSpec Code Generator. -package com.azure.search.documents.indexes.models; +package com.azure.search.documents.models; +import com.azure.core.annotation.Generated; import com.azure.core.annotation.Immutable; import com.azure.json.JsonReader; import com.azure.json.JsonSerializable; import com.azure.json.JsonToken; import com.azure.json.JsonWriter; -import com.azure.search.documents.indexes.implementation.models.EdgeNGramTokenFilterV1; -import com.azure.search.documents.indexes.implementation.models.EdgeNGramTokenFilterV2; -import com.azure.search.documents.indexes.implementation.models.NGramTokenFilterV1; -import com.azure.search.documents.indexes.implementation.models.NGramTokenFilterV2; import java.io.IOException; /** @@ -23,14 +18,17 @@ @Immutable public class TokenFilter implements JsonSerializable { /* - * A URI fragment specifying the type of token filter. + * The discriminator for derived types. */ + @Generated private String odataType = "TokenFilter"; /* - * 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. + * 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. */ + @Generated private final String name; /** @@ -38,25 +36,29 @@ public class TokenFilter implements JsonSerializable { * * @param name the name value to set. */ + @Generated public TokenFilter(String name) { this.name = name; } /** - * Get the odataType property: A URI fragment specifying the type of token filter. + * Get the odataType property: The discriminator for derived types. * * @return the odataType value. */ + @Generated public String getOdataType() { return this.odataType; } /** - * Get the name property: 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. + * Get the name property: 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. * * @return the name value. */ + @Generated public String getName() { return this.name; } @@ -64,6 +66,7 @@ public String getName() { /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); @@ -81,6 +84,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { * @throws IllegalStateException If the deserialized JSON object was missing any required properties. * @throws IOException If an error occurs while reading the TokenFilter. */ + @Generated public static TokenFilter fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { String discriminatorValue = null; @@ -143,10 +147,6 @@ public static TokenFilter fromJson(JsonReader jsonReader) throws IOException { return UniqueTokenFilter.fromJson(readerToUse.reset()); } else if ("#Microsoft.Azure.Search.WordDelimiterTokenFilter".equals(discriminatorValue)) { return WordDelimiterTokenFilter.fromJson(readerToUse.reset()); - } else if ("#Microsoft.Azure.Search.EdgeNGramTokenFilter".equals(discriminatorValue)) { - return EdgeNGramTokenFilterV1.fromJson(readerToUse.reset()); - } else if ("#Microsoft.Azure.Search.NGramTokenFilter".equals(discriminatorValue)) { - return NGramTokenFilterV1.fromJson(readerToUse.reset()); } else { return fromJsonKnownDiscriminator(readerToUse.reset()); } @@ -154,9 +154,9 @@ public static TokenFilter fromJson(JsonReader jsonReader) throws IOException { }); } + @Generated static TokenFilter fromJsonKnownDiscriminator(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { - boolean nameFound = false; String name = null; String odataType = null; while (reader.nextToken() != JsonToken.END_OBJECT) { @@ -165,20 +165,16 @@ static TokenFilter fromJsonKnownDiscriminator(JsonReader jsonReader) throws IOEx if ("name".equals(fieldName)) { name = reader.getString(); - nameFound = true; } else if ("@odata.type".equals(fieldName)) { odataType = reader.getString(); } else { reader.skipChildren(); } } - if (nameFound) { - TokenFilter deserializedTokenFilter = new TokenFilter(name); - deserializedTokenFilter.odataType = odataType; + TokenFilter deserializedTokenFilter = new TokenFilter(name); + deserializedTokenFilter.odataType = odataType; - return deserializedTokenFilter; - } - throw new IllegalStateException("Missing required property: name"); + return deserializedTokenFilter; }); } } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/TokenFilterName.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/TokenFilterName.java similarity index 86% rename from sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/TokenFilterName.java rename to sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/TokenFilterName.java index cf5498e387ca..cd9dde858b07 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/TokenFilterName.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/TokenFilterName.java @@ -1,11 +1,10 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) TypeSpec Code Generator. -package com.azure.search.documents.indexes.models; +package com.azure.search.documents.models; +import com.azure.core.annotation.Generated; import com.azure.core.util.ExpandableStringEnum; import java.util.Collection; @@ -14,209 +13,253 @@ */ public final class TokenFilterName extends ExpandableStringEnum { /** - * A token filter that applies the Arabic normalizer to normalize the orthography. See + * 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. */ + @Generated public static final TokenFilterName ARABIC_NORMALIZATION = fromString("arabic_normalization"); /** - * Strips all characters after an apostrophe (including the apostrophe itself). See + * 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. */ + @Generated public static final TokenFilterName APOSTROPHE = fromString("apostrophe"); /** - * 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 + * 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. */ + @Generated public static final TokenFilterName ASCII_FOLDING = fromString("asciifolding"); /** * 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. */ + @Generated public static final TokenFilterName CJK_BIGRAM = fromString("cjk_bigram"); /** - * Normalizes CJK width differences. Folds fullwidth ASCII variants into the equivalent basic Latin, and half-width - * Katakana variants into the equivalent Kana. See + * 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. */ + @Generated public static final TokenFilterName CJK_WIDTH = fromString("cjk_width"); /** * 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. */ + @Generated public static final TokenFilterName CLASSIC = fromString("classic"); /** - * Construct bigrams for frequently occurring terms while indexing. Single terms are still indexed too, with bigrams - * overlaid. See + * 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. */ + @Generated public static final TokenFilterName COMMON_GRAM = fromString("common_grams"); /** - * Generates n-grams of the given size(s) starting from the front or the back of an input token. See + * 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. */ + @Generated public static final TokenFilterName EDGE_NGRAM = fromString("edgeNGram_v2"); /** - * Removes elisions. For example, "l'avion" (the plane) will be converted to "avion" (plane). See + * 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. */ + @Generated public static final TokenFilterName ELISION = fromString("elision"); /** - * Normalizes German characters according to the heuristics of the German2 snowball algorithm. See + * 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. */ + @Generated public static final TokenFilterName GERMAN_NORMALIZATION = fromString("german_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. */ + @Generated public static final TokenFilterName HINDI_NORMALIZATION = fromString("hindi_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. */ + @Generated public static final TokenFilterName INDIC_NORMALIZATION = fromString("indic_normalization"); /** * 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. */ + @Generated public static final TokenFilterName KEYWORD_REPEAT = fromString("keyword_repeat"); /** * 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. */ + @Generated public static final TokenFilterName KSTEM = fromString("kstem"); /** * 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. */ + @Generated public static final TokenFilterName LENGTH = fromString("length"); /** * 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. */ + @Generated public static final TokenFilterName LIMIT = fromString("limit"); /** * Normalizes token text to lower case. See * https://lucene.apache.org/core/6_6_1/analyzers-common/org/apache/lucene/analysis/core/LowerCaseFilter.html. */ + @Generated public static final TokenFilterName LOWERCASE = fromString("lowercase"); /** * 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. */ + @Generated public static final TokenFilterName NGRAM = fromString("nGram_v2"); /** * Applies normalization for Persian. See * http://lucene.apache.org/core/4_10_3/analyzers-common/org/apache/lucene/analysis/fa/PersianNormalizationFilter.html. */ + @Generated public static final TokenFilterName PERSIAN_NORMALIZATION = fromString("persian_normalization"); /** * Create tokens for phonetic matches. See * https://lucene.apache.org/core/4_10_3/analyzers-phonetic/org/apache/lucene/analysis/phonetic/package-tree.html. */ + @Generated public static final TokenFilterName PHONETIC = fromString("phonetic"); /** - * Uses the Porter stemming algorithm to transform the token stream. See http://tartarus.org/~martin/PorterStemmer. + * Uses the Porter stemming algorithm to transform the token stream. See + * http://tartarus.org/~martin/PorterStemmer. */ + @Generated public static final TokenFilterName PORTER_STEM = fromString("porter_stem"); /** * Reverses the token string. See * http://lucene.apache.org/core/4_10_3/analyzers-common/org/apache/lucene/analysis/reverse/ReverseStringFilter.html. */ + @Generated public static final TokenFilterName REVERSE = fromString("reverse"); /** * 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. */ + @Generated public static final TokenFilterName SCANDINAVIAN_NORMALIZATION = fromString("scandinavian_normalization"); /** - * Folds Scandinavian characters åÅäæÄÆ-&gt;a and öÖøØ-&gt;o. It also discriminates against use of double - * vowels aa, ae, ao, oe and oo, leaving just the first one. See + * Folds Scandinavian characters åÅäæÄÆ-&gt;a and öÖøØ-&gt;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. */ + @Generated public static final TokenFilterName SCANDINAVIAN_FOLDING_NORMALIZATION = fromString("scandinavian_folding"); /** * 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. */ + @Generated public static final TokenFilterName SHINGLE = fromString("shingle"); /** * 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. */ + @Generated public static final TokenFilterName SNOWBALL = fromString("snowball"); /** * 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. */ + @Generated public static final TokenFilterName SORANI_NORMALIZATION = fromString("sorani_normalization"); /** * Language specific stemming filter. See * https://learn.microsoft.com/rest/api/searchservice/Custom-analyzers-in-Azure-Search#TokenFilters. */ + @Generated public static final TokenFilterName STEMMER = fromString("stemmer"); /** * 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. */ + @Generated public static final TokenFilterName STOPWORDS = fromString("stopwords"); /** * 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. */ + @Generated public static final TokenFilterName TRIM = fromString("trim"); /** * 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. */ + @Generated public static final TokenFilterName TRUNCATE = fromString("truncate"); /** * 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. */ + @Generated public static final TokenFilterName UNIQUE = fromString("unique"); /** * Normalizes token text to upper case. See * https://lucene.apache.org/core/6_6_1/analyzers-common/org/apache/lucene/analysis/core/UpperCaseFilter.html. */ + @Generated public static final TokenFilterName UPPERCASE = fromString("uppercase"); /** - * Splits words into subwords and performs optional transformations on subword groups. + * Splits words into subwords and performs optional transformations on subword + * groups. */ + @Generated public static final TokenFilterName WORD_DELIMITER = fromString("word_delimiter"); /** @@ -224,6 +267,7 @@ public final class TokenFilterName extends ExpandableStringEnum * * @deprecated Use the {@link #fromString(String)} factory method. */ + @Generated @Deprecated public TokenFilterName() { } @@ -234,6 +278,7 @@ public TokenFilterName() { * @param name a name to look for. * @return the corresponding TokenFilterName. */ + @Generated public static TokenFilterName fromString(String name) { return fromString(name, TokenFilterName.class); } @@ -243,6 +288,7 @@ public static TokenFilterName fromString(String name) { * * @return known TokenFilterName values. */ + @Generated public static Collection values() { return values(TokenFilterName.class); } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/TruncateTokenFilter.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/TruncateTokenFilter.java similarity index 79% rename from sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/TruncateTokenFilter.java rename to sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/TruncateTokenFilter.java index 207e58e22b4e..44cc7d46ca9b 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/TruncateTokenFilter.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/TruncateTokenFilter.java @@ -1,30 +1,32 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) TypeSpec Code Generator. -package com.azure.search.documents.indexes.models; +package com.azure.search.documents.models; import com.azure.core.annotation.Fluent; +import com.azure.core.annotation.Generated; import com.azure.json.JsonReader; import com.azure.json.JsonToken; import com.azure.json.JsonWriter; import java.io.IOException; /** - * Truncates the terms to a specific length. This token filter is implemented using Apache Lucene. + * Truncates the terms to a specific length. This token filter is implemented + * using Apache Lucene. */ @Fluent public final class TruncateTokenFilter extends TokenFilter { /* - * A URI fragment specifying the type of token filter. + * The discriminator for derived types. */ + @Generated private String odataType = "#Microsoft.Azure.Search.TruncateTokenFilter"; /* * The length at which terms will be truncated. Default and maximum is 300. */ + @Generated private Integer length; /** @@ -32,15 +34,17 @@ public final class TruncateTokenFilter extends TokenFilter { * * @param name the name value to set. */ + @Generated public TruncateTokenFilter(String name) { super(name); } /** - * Get the odataType property: A URI fragment specifying the type of token filter. + * Get the odataType property: The discriminator for derived types. * * @return the odataType value. */ + @Generated @Override public String getOdataType() { return this.odataType; @@ -51,6 +55,7 @@ public String getOdataType() { * * @return the length value. */ + @Generated public Integer getLength() { return this.length; } @@ -61,6 +66,7 @@ public Integer getLength() { * @param length the length value to set. * @return the TruncateTokenFilter object itself. */ + @Generated public TruncateTokenFilter setLength(Integer length) { this.length = length; return this; @@ -69,6 +75,7 @@ public TruncateTokenFilter setLength(Integer length) { /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); @@ -87,9 +94,9 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { * @throws IllegalStateException If the deserialized JSON object was missing any required properties. * @throws IOException If an error occurs while reading the TruncateTokenFilter. */ + @Generated public static TruncateTokenFilter fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { - boolean nameFound = false; String name = null; String odataType = "#Microsoft.Azure.Search.TruncateTokenFilter"; Integer length = null; @@ -99,7 +106,6 @@ public static TruncateTokenFilter fromJson(JsonReader jsonReader) throws IOExcep if ("name".equals(fieldName)) { name = reader.getString(); - nameFound = true; } else if ("@odata.type".equals(fieldName)) { odataType = reader.getString(); } else if ("length".equals(fieldName)) { @@ -108,14 +114,11 @@ public static TruncateTokenFilter fromJson(JsonReader jsonReader) throws IOExcep reader.skipChildren(); } } - if (nameFound) { - TruncateTokenFilter deserializedTruncateTokenFilter = new TruncateTokenFilter(name); - deserializedTruncateTokenFilter.odataType = odataType; - deserializedTruncateTokenFilter.length = length; + TruncateTokenFilter deserializedTruncateTokenFilter = new TruncateTokenFilter(name); + deserializedTruncateTokenFilter.odataType = odataType; + deserializedTruncateTokenFilter.length = length; - return deserializedTruncateTokenFilter; - } - throw new IllegalStateException("Missing required property: name"); + return deserializedTruncateTokenFilter; }); } } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/UaxUrlEmailTokenizer.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/UaxUrlEmailTokenizer.java similarity index 78% rename from sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/UaxUrlEmailTokenizer.java rename to sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/UaxUrlEmailTokenizer.java index 04ab67f6f727..33afedb65a53 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/UaxUrlEmailTokenizer.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/UaxUrlEmailTokenizer.java @@ -1,31 +1,33 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) TypeSpec Code Generator. -package com.azure.search.documents.indexes.models; +package com.azure.search.documents.models; import com.azure.core.annotation.Fluent; +import com.azure.core.annotation.Generated; import com.azure.json.JsonReader; import com.azure.json.JsonToken; import com.azure.json.JsonWriter; import java.io.IOException; /** - * Tokenizes urls and emails as one token. This tokenizer is implemented using Apache Lucene. + * Tokenizes urls and emails as one token. This tokenizer is implemented using + * Apache Lucene. */ @Fluent public final class UaxUrlEmailTokenizer extends LexicalTokenizer { /* - * A URI fragment specifying the type of tokenizer. + * The discriminator for derived types. */ + @Generated private String odataType = "#Microsoft.Azure.Search.UaxUrlEmailTokenizer"; /* - * 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. + * 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. */ + @Generated private Integer maxTokenLength; /** @@ -33,15 +35,17 @@ public final class UaxUrlEmailTokenizer extends LexicalTokenizer { * * @param name the name value to set. */ + @Generated public UaxUrlEmailTokenizer(String name) { super(name); } /** - * Get the odataType property: A URI fragment specifying the type of tokenizer. + * Get the odataType property: The discriminator for derived types. * * @return the odataType value. */ + @Generated @Override public String getOdataType() { return this.odataType; @@ -53,6 +57,7 @@ public String getOdataType() { * * @return the maxTokenLength value. */ + @Generated public Integer getMaxTokenLength() { return this.maxTokenLength; } @@ -64,6 +69,7 @@ public Integer getMaxTokenLength() { * @param maxTokenLength the maxTokenLength value to set. * @return the UaxUrlEmailTokenizer object itself. */ + @Generated public UaxUrlEmailTokenizer setMaxTokenLength(Integer maxTokenLength) { this.maxTokenLength = maxTokenLength; return this; @@ -72,6 +78,7 @@ public UaxUrlEmailTokenizer setMaxTokenLength(Integer maxTokenLength) { /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); @@ -90,9 +97,9 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { * @throws IllegalStateException If the deserialized JSON object was missing any required properties. * @throws IOException If an error occurs while reading the UaxUrlEmailTokenizer. */ + @Generated public static UaxUrlEmailTokenizer fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { - boolean nameFound = false; String name = null; String odataType = "#Microsoft.Azure.Search.UaxUrlEmailTokenizer"; Integer maxTokenLength = null; @@ -102,7 +109,6 @@ public static UaxUrlEmailTokenizer fromJson(JsonReader jsonReader) throws IOExce if ("name".equals(fieldName)) { name = reader.getString(); - nameFound = true; } else if ("@odata.type".equals(fieldName)) { odataType = reader.getString(); } else if ("maxTokenLength".equals(fieldName)) { @@ -111,14 +117,11 @@ public static UaxUrlEmailTokenizer fromJson(JsonReader jsonReader) throws IOExce reader.skipChildren(); } } - if (nameFound) { - UaxUrlEmailTokenizer deserializedUaxUrlEmailTokenizer = new UaxUrlEmailTokenizer(name); - deserializedUaxUrlEmailTokenizer.odataType = odataType; - deserializedUaxUrlEmailTokenizer.maxTokenLength = maxTokenLength; + UaxUrlEmailTokenizer deserializedUaxUrlEmailTokenizer = new UaxUrlEmailTokenizer(name); + deserializedUaxUrlEmailTokenizer.odataType = odataType; + deserializedUaxUrlEmailTokenizer.maxTokenLength = maxTokenLength; - return deserializedUaxUrlEmailTokenizer; - } - throw new IllegalStateException("Missing required property: name"); + return deserializedUaxUrlEmailTokenizer; }); } } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/UniqueTokenFilter.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/UniqueTokenFilter.java similarity index 79% rename from sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/UniqueTokenFilter.java rename to sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/UniqueTokenFilter.java index 59ed2b5ab8ca..2f8e95fa314d 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/UniqueTokenFilter.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/UniqueTokenFilter.java @@ -1,30 +1,33 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) TypeSpec Code Generator. -package com.azure.search.documents.indexes.models; +package com.azure.search.documents.models; import com.azure.core.annotation.Fluent; +import com.azure.core.annotation.Generated; import com.azure.json.JsonReader; import com.azure.json.JsonToken; import com.azure.json.JsonWriter; import java.io.IOException; /** - * Filters out tokens with same text as the previous token. This token filter is implemented using Apache Lucene. + * Filters out tokens with same text as the previous token. This token filter is + * implemented using Apache Lucene. */ @Fluent public final class UniqueTokenFilter extends TokenFilter { /* - * A URI fragment specifying the type of token filter. + * The discriminator for derived types. */ + @Generated private String odataType = "#Microsoft.Azure.Search.UniqueTokenFilter"; /* - * A value indicating whether to remove duplicates only at the same position. Default is false. + * A value indicating whether to remove duplicates only at the same position. + * Default is false. */ + @Generated private Boolean onlyOnSamePosition; /** @@ -32,15 +35,17 @@ public final class UniqueTokenFilter extends TokenFilter { * * @param name the name value to set. */ + @Generated public UniqueTokenFilter(String name) { super(name); } /** - * Get the odataType property: A URI fragment specifying the type of token filter. + * Get the odataType property: The discriminator for derived types. * * @return the odataType value. */ + @Generated @Override public String getOdataType() { return this.odataType; @@ -52,6 +57,7 @@ public String getOdataType() { * * @return the onlyOnSamePosition value. */ + @Generated public Boolean isOnlyOnSamePosition() { return this.onlyOnSamePosition; } @@ -63,6 +69,7 @@ public Boolean isOnlyOnSamePosition() { * @param onlyOnSamePosition the onlyOnSamePosition value to set. * @return the UniqueTokenFilter object itself. */ + @Generated public UniqueTokenFilter setOnlyOnSamePosition(Boolean onlyOnSamePosition) { this.onlyOnSamePosition = onlyOnSamePosition; return this; @@ -71,6 +78,7 @@ public UniqueTokenFilter setOnlyOnSamePosition(Boolean onlyOnSamePosition) { /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); @@ -89,9 +97,9 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { * @throws IllegalStateException If the deserialized JSON object was missing any required properties. * @throws IOException If an error occurs while reading the UniqueTokenFilter. */ + @Generated public static UniqueTokenFilter fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { - boolean nameFound = false; String name = null; String odataType = "#Microsoft.Azure.Search.UniqueTokenFilter"; Boolean onlyOnSamePosition = null; @@ -101,7 +109,6 @@ public static UniqueTokenFilter fromJson(JsonReader jsonReader) throws IOExcepti if ("name".equals(fieldName)) { name = reader.getString(); - nameFound = true; } else if ("@odata.type".equals(fieldName)) { odataType = reader.getString(); } else if ("onlyOnSamePosition".equals(fieldName)) { @@ -110,14 +117,11 @@ public static UniqueTokenFilter fromJson(JsonReader jsonReader) throws IOExcepti reader.skipChildren(); } } - if (nameFound) { - UniqueTokenFilter deserializedUniqueTokenFilter = new UniqueTokenFilter(name); - deserializedUniqueTokenFilter.odataType = odataType; - deserializedUniqueTokenFilter.onlyOnSamePosition = onlyOnSamePosition; + UniqueTokenFilter deserializedUniqueTokenFilter = new UniqueTokenFilter(name); + deserializedUniqueTokenFilter.odataType = odataType; + deserializedUniqueTokenFilter.onlyOnSamePosition = onlyOnSamePosition; - return deserializedUniqueTokenFilter; - } - throw new IllegalStateException("Missing required property: name"); + return deserializedUniqueTokenFilter; }); } } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/ValueFacetResult.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/ValueFacetResult.java deleted file mode 100644 index 99b0648e4ee7..000000000000 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/ValueFacetResult.java +++ /dev/null @@ -1,59 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.search.documents.models; - -import com.azure.core.annotation.Immutable; - -/** - * A single bucket of a simple or interval facet query result that reports the number of documents with a field falling - * within a particular interval or having a specific value. - * - * @param The type of the facet. - */ -@Immutable -public class ValueFacetResult { - private static final String VALUE = "value"; - private final Long count; - private final T value; - - /** - * Constructor - * - * @param count The approximate count of documents. - * @param value The value of the facet. - */ - public ValueFacetResult(Long count, T value) { - this.count = count; - this.value = value; - } - - /** - * Constructor from {@link FacetResult} - * - * @param facetResult {@link FacetResult}. - */ - @SuppressWarnings("unchecked") - public ValueFacetResult(FacetResult facetResult) { - this.count = facetResult.getCount(); - this.value = (T) facetResult.getAdditionalProperties().get(VALUE); - } - - /** - * Gets the approximate count of documents falling within the bucket described by this facet. - * - * @return count - */ - public Long getCount() { - return count; - } - - /** - * Gets the value of the facet, or the inclusive lower bound if it's an interval facet. - * - * @return value - */ - public T getValue() { - return value; - } -} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/VectorEncodingFormat.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/VectorEncodingFormat.java similarity index 86% rename from sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/VectorEncodingFormat.java rename to sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/VectorEncodingFormat.java index 165db00c1f18..a42babd716bd 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/VectorEncodingFormat.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/VectorEncodingFormat.java @@ -1,11 +1,10 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) TypeSpec Code Generator. -package com.azure.search.documents.indexes.models; +package com.azure.search.documents.models; +import com.azure.core.annotation.Generated; import com.azure.core.util.ExpandableStringEnum; import java.util.Collection; @@ -16,6 +15,7 @@ public final class VectorEncodingFormat extends ExpandableStringEnum values() { return values(VectorEncodingFormat.class); } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/VectorFilterMode.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/VectorFilterMode.java index d7f509ee1e2d..7f7467b5a3f1 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/VectorFilterMode.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/VectorFilterMode.java @@ -1,27 +1,30 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.search.documents.models; +import com.azure.core.annotation.Generated; import com.azure.core.util.ExpandableStringEnum; import java.util.Collection; /** - * Determines whether or not filters are applied before or after the vector search is performed. + * Determines whether or not filters are applied before or after the vector search + * is performed. */ public final class VectorFilterMode extends ExpandableStringEnum { /** - * The filter will be applied after the candidate set of vector results is returned. Depending on the filter - * selectivity, this can result in fewer results than requested by the parameter 'k'. + * The filter will be applied after the candidate set of vector results is + * returned. Depending on the filter selectivity, this can result in fewer results + * than requested by the parameter 'k'. */ + @Generated public static final VectorFilterMode POST_FILTER = fromString("postFilter"); /** * The filter will be applied before the search query. */ + @Generated public static final VectorFilterMode PRE_FILTER = fromString("preFilter"); /** @@ -29,6 +32,7 @@ public final class VectorFilterMode extends ExpandableStringEnum values() { return values(VectorFilterMode.class); } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/VectorQuery.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/VectorQuery.java index 27b5eca80415..6153e9a4aa4d 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/VectorQuery.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/VectorQuery.java @@ -1,11 +1,11 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) TypeSpec Code Generator. + package com.azure.search.documents.models; import com.azure.core.annotation.Fluent; +import com.azure.core.annotation.Generated; import com.azure.json.JsonReader; import com.azure.json.JsonSerializable; import com.azure.json.JsonToken; @@ -17,129 +17,152 @@ */ @Fluent public class VectorQuery implements JsonSerializable { - /* - * The kind of vector query being performed. + * Type of query. */ + @Generated private VectorQueryKind kind = VectorQueryKind.fromString("VectorQuery"); /* * Number of nearest neighbors to return as top hits. */ - private Integer kNearestNeighborsCount; + @Generated + private Integer kNearestNeighbors; /* - * Vector Fields of type Collection(Edm.Single) to be included in the vector searched. + * Vector Fields of type Collection(Edm.Single) to be included in the vector + * searched. */ + @Generated private String fields; /* - * 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. + * 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. */ + @Generated private Boolean exhaustive; /* - * 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 + * 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. */ + @Generated private Double oversampling; /* - * 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. + * 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. */ - private Float weight; + @Generated + private Double weight; /* * The threshold used for vector queries. Note this can only be set if all 'fields' use the same similarity metric. */ + @Generated private VectorThreshold threshold; /* - * 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. + * 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. */ + @Generated private String filterOverride; /** * Creates an instance of VectorQuery class. */ + @Generated public VectorQuery() { } /** - * Get the kind property: The kind of vector query being performed. - * + * Get the kind property: Type of query. + * * @return the kind value. */ + @Generated public VectorQueryKind getKind() { return this.kind; } /** - * Get the kNearestNeighborsCount property: Number of nearest neighbors to return as top hits. - * - * @return the kNearestNeighborsCount value. + * Get the kNearestNeighbors property: Number of nearest neighbors to return as top hits. + * + * @return the kNearestNeighbors value. */ - public Integer getKNearestNeighborsCount() { - return this.kNearestNeighborsCount; + @Generated + public Integer getKNearestNeighbors() { + return this.kNearestNeighbors; } /** - * Set the kNearestNeighborsCount property: Number of nearest neighbors to return as top hits. - * - * @param kNearestNeighborsCount the kNearestNeighborsCount value to set. + * Set the kNearestNeighbors property: Number of nearest neighbors to return as top hits. + * + * @param kNearestNeighbors the kNearestNeighbors value to set. * @return the VectorQuery object itself. */ - public VectorQuery setKNearestNeighborsCount(Integer kNearestNeighborsCount) { - this.kNearestNeighborsCount = kNearestNeighborsCount; + @Generated + public VectorQuery setKNearestNeighbors(Integer kNearestNeighbors) { + this.kNearestNeighbors = kNearestNeighbors; return this; } /** - * Get the fields property: Vector Fields of type Collection(Edm.Single) to be included in the vector searched. - * + * Get the fields property: Vector Fields of type Collection(Edm.Single) to be included in the vector + * searched. + * * @return the fields value. */ + @Generated public String getFields() { return this.fields; } /** - * Set the fields property: Vector Fields of type Collection(Edm.Single) to be included in the vector searched. - * + * Set the fields property: Vector Fields of type Collection(Edm.Single) to be included in the vector + * searched. + * * @param fields the fields value to set. * @return the VectorQuery object itself. */ - public VectorQuery setFields(String... fields) { - this.fields = (fields == null) ? null : String.join(",", fields); + @Generated + public VectorQuery setFields(String fields) { + this.fields = fields; return this; } /** * Get the exhaustive property: 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. - * + * within the vector index. Useful for scenarios where exact matches are critical, + * such as determining ground truth values. + * * @return the exhaustive value. */ + @Generated public Boolean isExhaustive() { return this.exhaustive; } /** * Set the exhaustive property: 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. - * + * within the vector index. Useful for scenarios where exact matches are critical, + * such as determining ground truth values. + * * @param exhaustive the exhaustive value to set. * @return the VectorQuery object itself. */ + @Generated public VectorQuery setExhaustive(Boolean exhaustive) { this.exhaustive = exhaustive; return this; @@ -147,52 +170,62 @@ public VectorQuery setExhaustive(Boolean exhaustive) { /** * Get the oversampling property: 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. - * + * 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. + * * @return the oversampling value. */ + @Generated public Double getOversampling() { return this.oversampling; } /** * Set the oversampling property: 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. - * + * 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. + * * @param oversampling the oversampling value to set. * @return the VectorQuery object itself. */ + @Generated public VectorQuery setOversampling(Double oversampling) { this.oversampling = oversampling; return this; } /** - * Get the weight property: 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. - * + * Get the weight property: 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. + * * @return the weight value. */ - public Float getWeight() { + @Generated + public Double getWeight() { return this.weight; } /** - * Set the weight property: 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. - * + * Set the weight property: 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. + * * @param weight the weight value to set. * @return the VectorQuery object itself. */ - public VectorQuery setWeight(Float weight) { + @Generated + public VectorQuery setWeight(Double weight) { this.weight = weight; return this; } @@ -200,9 +233,10 @@ public VectorQuery setWeight(Float weight) { /** * Get the threshold property: The threshold used for vector queries. Note this can only be set if all 'fields' use * the same similarity metric. - * + * * @return the threshold value. */ + @Generated public VectorThreshold getThreshold() { return this.threshold; } @@ -210,34 +244,37 @@ public VectorThreshold getThreshold() { /** * Set the threshold property: The threshold used for vector queries. Note this can only be set if all 'fields' use * the same similarity metric. - * + * * @param threshold the threshold value to set. * @return the VectorQuery object itself. */ + @Generated public VectorQuery setThreshold(VectorThreshold threshold) { this.threshold = threshold; return this; } /** - * Get the filterOverride property: 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. - * + * Get the filterOverride property: 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. + * * @return the filterOverride value. */ + @Generated public String getFilterOverride() { return this.filterOverride; } /** - * Set the filterOverride property: 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. - * + * Set the filterOverride property: 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. + * * @param filterOverride the filterOverride value to set. * @return the VectorQuery object itself. */ + @Generated public VectorQuery setFilterOverride(String filterOverride) { this.filterOverride = filterOverride; return this; @@ -246,11 +283,12 @@ public VectorQuery setFilterOverride(String filterOverride) { /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); jsonWriter.writeStringField("kind", this.kind == null ? null : this.kind.toString()); - jsonWriter.writeNumberField("k", this.kNearestNeighborsCount); + jsonWriter.writeNumberField("k", this.kNearestNeighbors); jsonWriter.writeStringField("fields", this.fields); jsonWriter.writeBooleanField("exhaustive", this.exhaustive); jsonWriter.writeNumberField("oversampling", this.oversampling); @@ -262,18 +300,18 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of VectorQuery from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of VectorQuery if the JsonReader was pointing to an instance of it, or null if it was * pointing to JSON null. * @throws IOException If an error occurs while reading the VectorQuery. */ + @Generated public static VectorQuery fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { String discriminatorValue = null; try (JsonReader readerToUse = reader.bufferObject()) { - // Prepare for reading - readerToUse.nextToken(); + readerToUse.nextToken(); // Prepare for reading while (readerToUse.nextToken() != JsonToken.END_OBJECT) { String fieldName = readerToUse.getFieldName(); readerToUse.nextToken(); @@ -285,14 +323,14 @@ public static VectorQuery fromJson(JsonReader jsonReader) throws IOException { } } // Use the discriminator value to determine which subtype should be deserialized. - if ("text".equals(discriminatorValue)) { + if ("vector".equals(discriminatorValue)) { + return VectorizedQuery.fromJson(readerToUse.reset()); + } else if ("text".equals(discriminatorValue)) { return VectorizableTextQuery.fromJson(readerToUse.reset()); } else if ("imageUrl".equals(discriminatorValue)) { return VectorizableImageUrlQuery.fromJson(readerToUse.reset()); } else if ("imageBinary".equals(discriminatorValue)) { return VectorizableImageBinaryQuery.fromJson(readerToUse.reset()); - } else if ("vector".equals(discriminatorValue)) { - return VectorizedQuery.fromJson(readerToUse.reset()); } else { return fromJsonKnownDiscriminator(readerToUse.reset()); } @@ -300,16 +338,18 @@ public static VectorQuery fromJson(JsonReader jsonReader) throws IOException { }); } + @Generated static VectorQuery fromJsonKnownDiscriminator(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { VectorQuery deserializedVectorQuery = new VectorQuery(); while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); + if ("kind".equals(fieldName)) { deserializedVectorQuery.kind = VectorQueryKind.fromString(reader.getString()); } else if ("k".equals(fieldName)) { - deserializedVectorQuery.kNearestNeighborsCount = reader.getNullable(JsonReader::getInt); + deserializedVectorQuery.kNearestNeighbors = reader.getNullable(JsonReader::getInt); } else if ("fields".equals(fieldName)) { deserializedVectorQuery.fields = reader.getString(); } else if ("exhaustive".equals(fieldName)) { @@ -317,7 +357,7 @@ static VectorQuery fromJsonKnownDiscriminator(JsonReader jsonReader) throws IOEx } else if ("oversampling".equals(fieldName)) { deserializedVectorQuery.oversampling = reader.getNullable(JsonReader::getDouble); } else if ("weight".equals(fieldName)) { - deserializedVectorQuery.weight = reader.getNullable(JsonReader::getFloat); + deserializedVectorQuery.weight = reader.getNullable(JsonReader::getDouble); } else if ("threshold".equals(fieldName)) { deserializedVectorQuery.threshold = VectorThreshold.fromJson(reader); } else if ("filterOverride".equals(fieldName)) { @@ -326,6 +366,7 @@ static VectorQuery fromJsonKnownDiscriminator(JsonReader jsonReader) throws IOEx reader.skipChildren(); } } + return deserializedVectorQuery; }); } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/VectorQueryKind.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/VectorQueryKind.java index 58e53b65716b..dcc54a495caa 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/VectorQueryKind.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/VectorQueryKind.java @@ -1,11 +1,10 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.search.documents.models; +import com.azure.core.annotation.Generated; import com.azure.core.util.ExpandableStringEnum; import java.util.Collection; @@ -16,21 +15,27 @@ public final class VectorQueryKind extends ExpandableStringEnum /** * Vector query where a raw vector value is provided. */ + @Generated public static final VectorQueryKind VECTOR = fromString("vector"); /** * Vector query where a text value that needs to be vectorized is provided. */ + @Generated public static final VectorQueryKind TEXT = fromString("text"); /** - * Vector query where an url that represents an image value that needs to be vectorized is provided. + * Vector query where an url that represents an image value that needs to be + * vectorized is provided. */ + @Generated public static final VectorQueryKind IMAGE_URL = fromString("imageUrl"); /** - * Vector query where a base 64 encoded binary of an image that needs to be vectorized is provided. + * Vector query where a base 64 encoded binary of an image that needs to be + * vectorized is provided. */ + @Generated public static final VectorQueryKind IMAGE_BINARY = fromString("imageBinary"); /** @@ -38,6 +43,7 @@ public final class VectorQueryKind extends ExpandableStringEnum * * @deprecated Use the {@link #fromString(String)} factory method. */ + @Generated @Deprecated public VectorQueryKind() { } @@ -48,6 +54,7 @@ public VectorQueryKind() { * @param name a name to look for. * @return the corresponding VectorQueryKind. */ + @Generated public static VectorQueryKind fromString(String name) { return fromString(name, VectorQueryKind.class); } @@ -57,6 +64,7 @@ public static VectorQueryKind fromString(String name) { * * @return known VectorQueryKind values. */ + @Generated public static Collection values() { return values(VectorQueryKind.class); } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/VectorSearch.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/VectorSearch.java similarity index 74% rename from sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/VectorSearch.java rename to sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/VectorSearch.java index afe414520366..0f145949ae33 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/VectorSearch.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/VectorSearch.java @@ -1,17 +1,16 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. -package com.azure.search.documents.indexes.models; +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.search.documents.models; import com.azure.core.annotation.Fluent; +import com.azure.core.annotation.Generated; import com.azure.json.JsonReader; import com.azure.json.JsonSerializable; import com.azure.json.JsonToken; import com.azure.json.JsonWriter; import java.io.IOException; -import java.util.Arrays; import java.util.List; /** @@ -19,70 +18,80 @@ */ @Fluent public final class VectorSearch implements JsonSerializable { - /* * Defines combinations of configurations to use with vector search. */ + @Generated private List profiles; /* - * Contains configuration options specific to the algorithm used during indexing or querying. + * Contains configuration options specific to the algorithm used during indexing + * or querying. */ + @Generated private List algorithms; /* * Contains configuration options on how to vectorize text vector queries. */ + @Generated private List vectorizers; /* - * Contains configuration options specific to the compression method used during indexing or querying. + * Contains configuration options specific to the compression method used during + * indexing or querying. */ + @Generated private List compressions; /** * Creates an instance of VectorSearch class. */ + @Generated public VectorSearch() { } /** * Get the profiles property: Defines combinations of configurations to use with vector search. - * + * * @return the profiles value. */ + @Generated public List getProfiles() { return this.profiles; } /** * Set the profiles property: Defines combinations of configurations to use with vector search. - * + * * @param profiles the profiles value to set. * @return the VectorSearch object itself. */ + @Generated public VectorSearch setProfiles(List profiles) { this.profiles = profiles; return this; } /** - * Get the algorithms property: Contains configuration options specific to the algorithm used during indexing or - * querying. - * + * Get the algorithms property: Contains configuration options specific to the algorithm used during indexing + * or querying. + * * @return the algorithms value. */ + @Generated public List getAlgorithms() { return this.algorithms; } /** - * Set the algorithms property: Contains configuration options specific to the algorithm used during indexing or - * querying. - * + * Set the algorithms property: Contains configuration options specific to the algorithm used during indexing + * or querying. + * * @param algorithms the algorithms value to set. * @return the VectorSearch object itself. */ + @Generated public VectorSearch setAlgorithms(List algorithms) { this.algorithms = algorithms; return this; @@ -90,19 +99,21 @@ public VectorSearch setAlgorithms(List algor /** * Get the vectorizers property: Contains configuration options on how to vectorize text vector queries. - * + * * @return the vectorizers value. */ + @Generated public List getVectorizers() { return this.vectorizers; } /** * Set the vectorizers property: Contains configuration options on how to vectorize text vector queries. - * + * * @param vectorizers the vectorizers value to set. * @return the VectorSearch object itself. */ + @Generated public VectorSearch setVectorizers(List vectorizers) { this.vectorizers = vectorizers; return this; @@ -111,9 +122,10 @@ public VectorSearch setVectorizers(List vectorizers) { /** * Get the compressions property: Contains configuration options specific to the compression method used during * indexing or querying. - * + * * @return the compressions value. */ + @Generated public List getCompressions() { return this.compressions; } @@ -121,10 +133,11 @@ public List getCompressions() { /** * Set the compressions property: Contains configuration options specific to the compression method used during * indexing or querying. - * + * * @param compressions the compressions value to set. * @return the VectorSearch object itself. */ + @Generated public VectorSearch setCompressions(List compressions) { this.compressions = compressions; return this; @@ -133,6 +146,7 @@ public VectorSearch setCompressions(List compressions) /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); @@ -145,18 +159,20 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of VectorSearch from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of VectorSearch if the JsonReader was pointing to an instance of it, or null if it was * pointing to JSON null. * @throws IOException If an error occurs while reading the VectorSearch. */ + @Generated public static VectorSearch fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { VectorSearch deserializedVectorSearch = new VectorSearch(); while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); + if ("profiles".equals(fieldName)) { List profiles = reader.readArray(reader1 -> VectorSearchProfile.fromJson(reader1)); @@ -177,53 +193,8 @@ public static VectorSearch fromJson(JsonReader jsonReader) throws IOException { reader.skipChildren(); } } + return deserializedVectorSearch; }); } - - /** - * Set the profiles property: Defines combinations of configurations to use with vector search. - * - * @param profiles the profiles value to set. - * @return the VectorSearch object itself. - */ - public VectorSearch setProfiles(VectorSearchProfile... profiles) { - this.profiles = (profiles == null) ? null : Arrays.asList(profiles); - return this; - } - - /** - * Set the algorithms property: Contains configuration options specific to the algorithm used during indexing or - * querying. - * - * @param algorithms the algorithms value to set. - * @return the VectorSearch object itself. - */ - public VectorSearch setAlgorithms(VectorSearchAlgorithmConfiguration... algorithms) { - this.algorithms = (algorithms == null) ? null : Arrays.asList(algorithms); - return this; - } - - /** - * Set the compressions property: Contains configuration options specific to the compression method used during - * indexing or querying. - * - * @param compressions the compressions value to set. - * @return the VectorSearch object itself. - */ - public VectorSearch setCompressions(VectorSearchCompression... compressions) { - this.compressions = (compressions == null) ? null : Arrays.asList(compressions); - return this; - } - - /** - * Set the vectorizers property: Contains configuration options on how to vectorize text vector queries. - * - * @param vectorizers the vectorizers value to set. - * @return the VectorSearch object itself. - */ - public VectorSearch setVectorizers(VectorSearchVectorizer... vectorizers) { - this.vectorizers = (vectorizers == null) ? null : Arrays.asList(vectorizers); - return this; - } } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/VectorSearchAlgorithmConfiguration.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/VectorSearchAlgorithmConfiguration.java similarity index 82% rename from sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/VectorSearchAlgorithmConfiguration.java rename to sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/VectorSearchAlgorithmConfiguration.java index 173f72aac4df..69ef0d942d69 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/VectorSearchAlgorithmConfiguration.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/VectorSearchAlgorithmConfiguration.java @@ -1,11 +1,10 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) TypeSpec Code Generator. -package com.azure.search.documents.indexes.models; +package com.azure.search.documents.models; +import com.azure.core.annotation.Generated; import com.azure.core.annotation.Immutable; import com.azure.json.JsonReader; import com.azure.json.JsonSerializable; @@ -14,18 +13,21 @@ import java.io.IOException; /** - * Contains configuration options specific to the algorithm used during indexing or querying. + * Contains configuration options specific to the algorithm used during indexing + * or querying. */ @Immutable public class VectorSearchAlgorithmConfiguration implements JsonSerializable { /* - * The name of the kind of algorithm being configured for use with vector search. + * Type of VectorSearchAlgorithmConfiguration. */ + @Generated private VectorSearchAlgorithmKind kind = VectorSearchAlgorithmKind.fromString("VectorSearchAlgorithmConfiguration"); /* * The name to associate with this particular configuration. */ + @Generated private final String name; /** @@ -33,15 +35,17 @@ public class VectorSearchAlgorithmConfiguration implements JsonSerializable { String discriminatorValue = null; @@ -102,9 +109,9 @@ public static VectorSearchAlgorithmConfiguration fromJson(JsonReader jsonReader) }); } + @Generated static VectorSearchAlgorithmConfiguration fromJsonKnownDiscriminator(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { - boolean nameFound = false; String name = null; VectorSearchAlgorithmKind kind = null; while (reader.nextToken() != JsonToken.END_OBJECT) { @@ -113,21 +120,17 @@ static VectorSearchAlgorithmConfiguration fromJsonKnownDiscriminator(JsonReader if ("name".equals(fieldName)) { name = reader.getString(); - nameFound = true; } else if ("kind".equals(fieldName)) { kind = VectorSearchAlgorithmKind.fromString(reader.getString()); } else { reader.skipChildren(); } } - if (nameFound) { - VectorSearchAlgorithmConfiguration deserializedVectorSearchAlgorithmConfiguration - = new VectorSearchAlgorithmConfiguration(name); - deserializedVectorSearchAlgorithmConfiguration.kind = kind; + VectorSearchAlgorithmConfiguration deserializedVectorSearchAlgorithmConfiguration + = new VectorSearchAlgorithmConfiguration(name); + deserializedVectorSearchAlgorithmConfiguration.kind = kind; - return deserializedVectorSearchAlgorithmConfiguration; - } - throw new IllegalStateException("Missing required property: name"); + return deserializedVectorSearchAlgorithmConfiguration; }); } } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/VectorSearchAlgorithmKind.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/VectorSearchAlgorithmKind.java similarity index 85% rename from sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/VectorSearchAlgorithmKind.java rename to sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/VectorSearchAlgorithmKind.java index d9e40b0b27a5..a2c29bca09f7 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/VectorSearchAlgorithmKind.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/VectorSearchAlgorithmKind.java @@ -1,11 +1,10 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) TypeSpec Code Generator. -package com.azure.search.documents.indexes.models; +package com.azure.search.documents.models; +import com.azure.core.annotation.Generated; import com.azure.core.util.ExpandableStringEnum; import java.util.Collection; @@ -14,13 +13,16 @@ */ public final class VectorSearchAlgorithmKind extends ExpandableStringEnum { /** - * HNSW (Hierarchical Navigable Small World), a type of approximate nearest neighbors algorithm. + * HNSW (Hierarchical Navigable Small World), a type of approximate nearest + * neighbors algorithm. */ + @Generated public static final VectorSearchAlgorithmKind HNSW = fromString("hnsw"); /** * Exhaustive KNN algorithm which will perform brute-force search. */ + @Generated public static final VectorSearchAlgorithmKind EXHAUSTIVE_KNN = fromString("exhaustiveKnn"); /** @@ -28,6 +30,7 @@ public final class VectorSearchAlgorithmKind extends ExpandableStringEnum values() { return values(VectorSearchAlgorithmKind.class); } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/VectorSearchAlgorithmMetric.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/VectorSearchAlgorithmMetric.java similarity index 72% rename from sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/VectorSearchAlgorithmMetric.java rename to sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/VectorSearchAlgorithmMetric.java index 3aaa01a904f5..66a9f744383e 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/VectorSearchAlgorithmMetric.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/VectorSearchAlgorithmMetric.java @@ -1,41 +1,45 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) TypeSpec Code Generator. -package com.azure.search.documents.indexes.models; +package com.azure.search.documents.models; +import com.azure.core.annotation.Generated; import com.azure.core.util.ExpandableStringEnum; import java.util.Collection; /** - * The similarity metric to use for vector comparisons. It is recommended to choose the same similarity metric as the - * embedding model was trained on. + * The similarity metric to use for vector comparisons. It is recommended to + * choose the same similarity metric as the embedding model was trained on. */ public final class VectorSearchAlgorithmMetric extends ExpandableStringEnum { /** - * Measures the angle between vectors to quantify their similarity, disregarding magnitude. The smaller the angle, - * the closer the similarity. + * Measures the angle between vectors to quantify their similarity, disregarding + * magnitude. The smaller the angle, the closer the similarity. */ + @Generated public static final VectorSearchAlgorithmMetric COSINE = fromString("cosine"); /** - * Computes the straight-line distance between vectors in a multi-dimensional space. The smaller the distance, the - * closer the similarity. + * Computes the straight-line distance between vectors in a multi-dimensional + * space. The smaller the distance, the closer the similarity. */ + @Generated public static final VectorSearchAlgorithmMetric EUCLIDEAN = fromString("euclidean"); /** - * Calculates the sum of element-wise products to gauge alignment and magnitude similarity. The larger and more - * positive, the closer the similarity. + * Calculates the sum of element-wise products to gauge alignment and magnitude + * similarity. The larger and more positive, the closer the similarity. */ + @Generated public static final VectorSearchAlgorithmMetric DOT_PRODUCT = fromString("dotProduct"); /** - * Only applicable to bit-packed binary data types. Determines dissimilarity by counting differing positions in - * binary vectors. The fewer differences, the closer the similarity. + * Only applicable to bit-packed binary data types. Determines dissimilarity by + * counting differing positions in binary vectors. The fewer differences, the + * closer the similarity. */ + @Generated public static final VectorSearchAlgorithmMetric HAMMING = fromString("hamming"); /** @@ -43,6 +47,7 @@ public final class VectorSearchAlgorithmMetric extends ExpandableStringEnum values() { return values(VectorSearchAlgorithmMetric.class); } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/VectorSearchCompression.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/VectorSearchCompression.java similarity index 71% rename from sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/VectorSearchCompression.java rename to sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/VectorSearchCompression.java index 11a7f511875a..5bb79e18b1fd 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/VectorSearchCompression.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/VectorSearchCompression.java @@ -1,12 +1,11 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) TypeSpec Code Generator. -package com.azure.search.documents.indexes.models; +package com.azure.search.documents.models; import com.azure.core.annotation.Fluent; +import com.azure.core.annotation.Generated; import com.azure.json.JsonReader; import com.azure.json.JsonSerializable; import com.azure.json.JsonToken; @@ -14,47 +13,59 @@ import java.io.IOException; /** - * Contains configuration options specific to the compression method used during indexing or querying. + * Contains configuration options specific to the compression method used during + * indexing or querying. */ @Fluent public class VectorSearchCompression implements JsonSerializable { /* - * The name of the kind of compression method being configured for use with vector search. + * Type of VectorSearchCompression. */ + @Generated private VectorSearchCompressionKind kind = VectorSearchCompressionKind.fromString("VectorSearchCompression"); /* * The name to associate with this particular configuration. */ + @Generated private final String compressionName; /* - * 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 + * 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. */ + @Generated private Boolean rerankWithOriginalVectors; /* - * 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. + * 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. */ + @Generated private Double defaultOversampling; /* * Contains the options for rescoring. */ + @Generated private RescoringOptions rescoringOptions; /* - * 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. + * 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. */ + @Generated private Integer truncationDimension; /** @@ -62,15 +73,17 @@ public class VectorSearchCompression implements JsonSerializable { String discriminatorValue = null; @@ -235,9 +269,9 @@ public static VectorSearchCompression fromJson(JsonReader jsonReader) throws IOE }); } + @Generated static VectorSearchCompression fromJsonKnownDiscriminator(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { - boolean compressionNameFound = false; String compressionName = null; VectorSearchCompressionKind kind = null; Boolean rerankWithOriginalVectors = null; @@ -250,7 +284,6 @@ static VectorSearchCompression fromJsonKnownDiscriminator(JsonReader jsonReader) if ("name".equals(fieldName)) { compressionName = reader.getString(); - compressionNameFound = true; } else if ("kind".equals(fieldName)) { kind = VectorSearchCompressionKind.fromString(reader.getString()); } else if ("rerankWithOriginalVectors".equals(fieldName)) { @@ -265,18 +298,14 @@ static VectorSearchCompression fromJsonKnownDiscriminator(JsonReader jsonReader) reader.skipChildren(); } } - if (compressionNameFound) { - VectorSearchCompression deserializedVectorSearchCompression - = new VectorSearchCompression(compressionName); - deserializedVectorSearchCompression.kind = kind; - deserializedVectorSearchCompression.rerankWithOriginalVectors = rerankWithOriginalVectors; - deserializedVectorSearchCompression.defaultOversampling = defaultOversampling; - deserializedVectorSearchCompression.rescoringOptions = rescoringOptions; - deserializedVectorSearchCompression.truncationDimension = truncationDimension; + VectorSearchCompression deserializedVectorSearchCompression = new VectorSearchCompression(compressionName); + deserializedVectorSearchCompression.kind = kind; + deserializedVectorSearchCompression.rerankWithOriginalVectors = rerankWithOriginalVectors; + deserializedVectorSearchCompression.defaultOversampling = defaultOversampling; + deserializedVectorSearchCompression.rescoringOptions = rescoringOptions; + deserializedVectorSearchCompression.truncationDimension = truncationDimension; - return deserializedVectorSearchCompression; - } - throw new IllegalStateException("Missing required property: name"); + return deserializedVectorSearchCompression; }); } } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/VectorSearchCompressionKind.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/VectorSearchCompressionKind.java similarity index 71% rename from sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/VectorSearchCompressionKind.java rename to sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/VectorSearchCompressionKind.java index e74f09a683fe..93c674a5249e 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/VectorSearchCompressionKind.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/VectorSearchCompressionKind.java @@ -1,11 +1,10 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) TypeSpec Code Generator. -package com.azure.search.documents.indexes.models; +package com.azure.search.documents.models; +import com.azure.core.annotation.Generated; import com.azure.core.util.ExpandableStringEnum; import java.util.Collection; @@ -14,17 +13,21 @@ */ public final class VectorSearchCompressionKind extends ExpandableStringEnum { /** - * 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. + * 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. */ + @Generated public static final VectorSearchCompressionKind SCALAR_QUANTIZATION = fromString("scalarQuantization"); /** - * 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. + * 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. */ + @Generated public static final VectorSearchCompressionKind BINARY_QUANTIZATION = fromString("binaryQuantization"); /** @@ -32,6 +35,7 @@ public final class VectorSearchCompressionKind extends ExpandableStringEnum values() { return values(VectorSearchCompressionKind.class); } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/VectorSearchCompressionRescoreStorageMethod.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/VectorSearchCompressionRescoreStorageMethod.java similarity index 73% rename from sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/VectorSearchCompressionRescoreStorageMethod.java rename to sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/VectorSearchCompressionRescoreStorageMethod.java index 037364ddbaf0..6d7110bdb83b 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/VectorSearchCompressionRescoreStorageMethod.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/VectorSearchCompressionRescoreStorageMethod.java @@ -1,31 +1,34 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) TypeSpec Code Generator. -package com.azure.search.documents.indexes.models; +package com.azure.search.documents.models; +import com.azure.core.annotation.Generated; import com.azure.core.util.ExpandableStringEnum; import java.util.Collection; /** - * The storage method for the original full-precision vectors used for rescoring and internal index operations. + * The storage method for the original full-precision vectors used for rescoring + * and internal index operations. */ public final class VectorSearchCompressionRescoreStorageMethod extends ExpandableStringEnum { /** - * This option preserves the original full-precision vectors. Choose this option for maximum flexibility and highest - * quality of compressed search results. This consumes more storage but allows for rescoring and oversampling. + * This option preserves the original full-precision vectors. Choose this option + * for maximum flexibility and highest quality of compressed search results. This + * consumes more storage but allows for rescoring and oversampling. */ + @Generated public static final VectorSearchCompressionRescoreStorageMethod PRESERVE_ORIGINALS = fromString("preserveOriginals"); /** - * This option discards the original full-precision vectors. Choose this option for maximum storage savings. Since - * this option does not allow for rescoring and oversampling, it will often cause slight to moderate reductions in - * quality. + * This option discards the original full-precision vectors. Choose this option + * for maximum storage savings. Since this option does not allow for rescoring and + * oversampling, it will often cause slight to moderate reductions in quality. */ + @Generated public static final VectorSearchCompressionRescoreStorageMethod DISCARD_ORIGINALS = fromString("discardOriginals"); /** @@ -33,6 +36,7 @@ public final class VectorSearchCompressionRescoreStorageMethod * * @deprecated Use the {@link #fromString(String)} factory method. */ + @Generated @Deprecated public VectorSearchCompressionRescoreStorageMethod() { } @@ -43,6 +47,7 @@ public VectorSearchCompressionRescoreStorageMethod() { * @param name a name to look for. * @return the corresponding VectorSearchCompressionRescoreStorageMethod. */ + @Generated public static VectorSearchCompressionRescoreStorageMethod fromString(String name) { return fromString(name, VectorSearchCompressionRescoreStorageMethod.class); } @@ -52,6 +57,7 @@ public static VectorSearchCompressionRescoreStorageMethod fromString(String name * * @return known VectorSearchCompressionRescoreStorageMethod values. */ + @Generated public static Collection values() { return values(VectorSearchCompressionRescoreStorageMethod.class); } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/VectorSearchCompressionTarget.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/VectorSearchCompressionTarget.java similarity index 83% rename from sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/VectorSearchCompressionTarget.java rename to sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/VectorSearchCompressionTarget.java index 3c0e2469602f..653a90d78e60 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/VectorSearchCompressionTarget.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/VectorSearchCompressionTarget.java @@ -1,11 +1,10 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) TypeSpec Code Generator. -package com.azure.search.documents.indexes.models; +package com.azure.search.documents.models; +import com.azure.core.annotation.Generated; import com.azure.core.util.ExpandableStringEnum; import java.util.Collection; @@ -14,8 +13,9 @@ */ public final class VectorSearchCompressionTarget extends ExpandableStringEnum { /** - * Static value int8 for VectorSearchCompressionTarget. + * 8-bit signed integer. */ + @Generated public static final VectorSearchCompressionTarget INT8 = fromString("int8"); /** @@ -23,6 +23,7 @@ public final class VectorSearchCompressionTarget extends ExpandableStringEnum values() { return values(VectorSearchCompressionTarget.class); } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/VectorSearchOptions.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/VectorSearchOptions.java deleted file mode 100644 index c46ade897ac5..000000000000 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/VectorSearchOptions.java +++ /dev/null @@ -1,71 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -package com.azure.search.documents.models; - -import java.util.Arrays; -import java.util.List; - -/** - * Parameters for performing vector searches. - */ -public final class VectorSearchOptions { - private VectorFilterMode filterMode; - private List queries; - - /** - * Creates a new instance of {@link VectorSearchOptions}. - */ - public VectorSearchOptions() { - } - - /** - * Gets the filter mode to apply to vector queries. - * - * @return The filter mode to apply to vector queries. - */ - public VectorFilterMode getFilterMode() { - return filterMode; - } - - /** - * Sets the filter mode to apply to vector queries. - * - * @param filterMode The filter mode to apply to vector queries. - * @return The VectorSearchOptions object itself. - */ - public VectorSearchOptions setFilterMode(VectorFilterMode filterMode) { - this.filterMode = filterMode; - return this; - } - - /** - * Gets the list of vector queries to perform. - * - * @return The list of vector queries to perform. - */ - public List getQueries() { - return queries; - } - - /** - * Sets the list of vector queries to perform. - * - * @param queries The list of vector queries to perform. - * @return The VectorSearchOptions object itself. - */ - public VectorSearchOptions setQueries(VectorQuery... queries) { - this.queries = queries == null ? null : Arrays.asList(queries); - return this; - } - - /** - * Sets the list of vector queries to perform. - * - * @param queries The list of vector queries to perform. - * @return The VectorSearchOptions object itself. - */ - public VectorSearchOptions setQueries(List queries) { - this.queries = queries; - return this; - } -} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/VectorSearchProfile.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/VectorSearchProfile.java similarity index 78% rename from sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/VectorSearchProfile.java rename to sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/VectorSearchProfile.java index 0215b8843b88..1310b1e044f5 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/VectorSearchProfile.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/VectorSearchProfile.java @@ -1,19 +1,16 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) TypeSpec Code Generator. -package com.azure.search.documents.indexes.models; +package com.azure.search.documents.models; import com.azure.core.annotation.Fluent; +import com.azure.core.annotation.Generated; import com.azure.json.JsonReader; import com.azure.json.JsonSerializable; import com.azure.json.JsonToken; import com.azure.json.JsonWriter; import java.io.IOException; -import java.util.ArrayList; -import java.util.List; /** * Defines a combination of configurations to use with vector search. @@ -23,21 +20,27 @@ public final class VectorSearchProfile implements JsonSerializable { - boolean nameFound = false; String name = null; - boolean algorithmConfigurationNameFound = false; String algorithmConfigurationName = null; String vectorizerName = null; String compressionName = null; @@ -148,10 +159,8 @@ public static VectorSearchProfile fromJson(JsonReader jsonReader) throws IOExcep if ("name".equals(fieldName)) { name = reader.getString(); - nameFound = true; } else if ("algorithm".equals(fieldName)) { algorithmConfigurationName = reader.getString(); - algorithmConfigurationNameFound = true; } else if ("vectorizer".equals(fieldName)) { vectorizerName = reader.getString(); } else if ("compression".equals(fieldName)) { @@ -160,24 +169,12 @@ public static VectorSearchProfile fromJson(JsonReader jsonReader) throws IOExcep reader.skipChildren(); } } - if (nameFound && algorithmConfigurationNameFound) { - VectorSearchProfile deserializedVectorSearchProfile - = new VectorSearchProfile(name, algorithmConfigurationName); - deserializedVectorSearchProfile.vectorizerName = vectorizerName; - deserializedVectorSearchProfile.compressionName = compressionName; - - return deserializedVectorSearchProfile; - } - List missingProperties = new ArrayList<>(); - if (!nameFound) { - missingProperties.add("name"); - } - if (!algorithmConfigurationNameFound) { - missingProperties.add("algorithm"); - } + VectorSearchProfile deserializedVectorSearchProfile + = new VectorSearchProfile(name, algorithmConfigurationName); + deserializedVectorSearchProfile.vectorizerName = vectorizerName; + deserializedVectorSearchProfile.compressionName = compressionName; - throw new IllegalStateException( - "Missing required property/properties: " + String.join(", ", missingProperties)); + return deserializedVectorSearchProfile; }); } } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/VectorSearchVectorizer.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/VectorSearchVectorizer.java similarity index 84% rename from sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/VectorSearchVectorizer.java rename to sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/VectorSearchVectorizer.java index 48e1f0bddcb7..8321aecce890 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/VectorSearchVectorizer.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/VectorSearchVectorizer.java @@ -1,11 +1,10 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) TypeSpec Code Generator. -package com.azure.search.documents.indexes.models; +package com.azure.search.documents.models; +import com.azure.core.annotation.Generated; import com.azure.core.annotation.Immutable; import com.azure.json.JsonReader; import com.azure.json.JsonSerializable; @@ -19,13 +18,15 @@ @Immutable public class VectorSearchVectorizer implements JsonSerializable { /* - * The name of the kind of vectorization method being configured for use with vector search. + * Type of VectorSearchVectorizer. */ + @Generated private VectorSearchVectorizerKind kind = VectorSearchVectorizerKind.fromString("VectorSearchVectorizer"); /* * The name to associate with this particular vectorization method. */ + @Generated private final String vectorizerName; /** @@ -33,15 +34,17 @@ public class VectorSearchVectorizer implements JsonSerializable { String discriminatorValue = null; @@ -106,9 +112,9 @@ public static VectorSearchVectorizer fromJson(JsonReader jsonReader) throws IOEx }); } + @Generated static VectorSearchVectorizer fromJsonKnownDiscriminator(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { - boolean vectorizerNameFound = false; String vectorizerName = null; VectorSearchVectorizerKind kind = null; while (reader.nextToken() != JsonToken.END_OBJECT) { @@ -117,20 +123,16 @@ static VectorSearchVectorizer fromJsonKnownDiscriminator(JsonReader jsonReader) if ("name".equals(fieldName)) { vectorizerName = reader.getString(); - vectorizerNameFound = true; } else if ("kind".equals(fieldName)) { kind = VectorSearchVectorizerKind.fromString(reader.getString()); } else { reader.skipChildren(); } } - if (vectorizerNameFound) { - VectorSearchVectorizer deserializedVectorSearchVectorizer = new VectorSearchVectorizer(vectorizerName); - deserializedVectorSearchVectorizer.kind = kind; + VectorSearchVectorizer deserializedVectorSearchVectorizer = new VectorSearchVectorizer(vectorizerName); + deserializedVectorSearchVectorizer.kind = kind; - return deserializedVectorSearchVectorizer; - } - throw new IllegalStateException("Missing required property: name"); + return deserializedVectorSearchVectorizer; }); } } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/VectorSearchVectorizerKind.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/VectorSearchVectorizerKind.java similarity index 83% rename from sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/VectorSearchVectorizerKind.java rename to sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/VectorSearchVectorizerKind.java index 449b45268b89..6c426f471875 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/VectorSearchVectorizerKind.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/VectorSearchVectorizerKind.java @@ -1,11 +1,10 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) TypeSpec Code Generator. -package com.azure.search.documents.indexes.models; +package com.azure.search.documents.models; +import com.azure.core.annotation.Generated; import com.azure.core.util.ExpandableStringEnum; import java.util.Collection; @@ -16,22 +15,27 @@ public final class VectorSearchVectorizerKind extends ExpandableStringEnum values() { return values(VectorSearchVectorizerKind.class); } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/VectorSimilarityThreshold.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/VectorSimilarityThreshold.java index 7297aacd88d3..bf78e112d3cb 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/VectorSimilarityThreshold.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/VectorSimilarityThreshold.java @@ -1,11 +1,10 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.search.documents.models; +import com.azure.core.annotation.Generated; import com.azure.core.annotation.Immutable; import com.azure.json.JsonReader; import com.azure.json.JsonToken; @@ -13,22 +12,26 @@ import java.io.IOException; /** - * 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. + * 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. */ @Immutable public final class VectorSimilarityThreshold extends VectorThreshold { /* - * The kind of threshold used to filter vector queries + * Type of threshold. */ + @Generated private VectorThresholdKind kind = VectorThresholdKind.VECTOR_SIMILARITY; /* - * 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. + * 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. */ + @Generated private final double value; /** @@ -36,27 +39,31 @@ public final class VectorSimilarityThreshold extends VectorThreshold { * * @param value the value value to set. */ + @Generated public VectorSimilarityThreshold(double value) { this.value = value; } /** - * Get the kind property: The kind of threshold used to filter vector queries. + * Get the kind property: Type of threshold. * * @return the kind value. */ + @Generated @Override public VectorThresholdKind getKind() { return this.kind; } /** - * Get the value property: 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. + * Get the value property: 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. * * @return the value value. */ + @Generated public double getValue() { return this.value; } @@ -64,6 +71,7 @@ public double getValue() { /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); @@ -81,9 +89,9 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { * @throws IllegalStateException If the deserialized JSON object was missing any required properties. * @throws IOException If an error occurs while reading the VectorSimilarityThreshold. */ + @Generated public static VectorSimilarityThreshold fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { - boolean valueFound = false; double value = 0.0; VectorThresholdKind kind = VectorThresholdKind.VECTOR_SIMILARITY; while (reader.nextToken() != JsonToken.END_OBJECT) { @@ -92,20 +100,16 @@ public static VectorSimilarityThreshold fromJson(JsonReader jsonReader) throws I if ("value".equals(fieldName)) { value = reader.getDouble(); - valueFound = true; } else if ("kind".equals(fieldName)) { kind = VectorThresholdKind.fromString(reader.getString()); } else { reader.skipChildren(); } } - if (valueFound) { - VectorSimilarityThreshold deserializedVectorSimilarityThreshold = new VectorSimilarityThreshold(value); - deserializedVectorSimilarityThreshold.kind = kind; + VectorSimilarityThreshold deserializedVectorSimilarityThreshold = new VectorSimilarityThreshold(value); + deserializedVectorSimilarityThreshold.kind = kind; - return deserializedVectorSimilarityThreshold; - } - throw new IllegalStateException("Missing required property: value"); + return deserializedVectorSimilarityThreshold; }); } } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/VectorThreshold.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/VectorThreshold.java index 6256f5f7b9a6..8633a205aa7d 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/VectorThreshold.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/VectorThreshold.java @@ -1,11 +1,10 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.search.documents.models; +import com.azure.core.annotation.Generated; import com.azure.core.annotation.Immutable; import com.azure.json.JsonReader; import com.azure.json.JsonSerializable; @@ -19,21 +18,24 @@ @Immutable public class VectorThreshold implements JsonSerializable { /* - * The kind of threshold used to filter vector queries + * Type of threshold. */ + @Generated private VectorThresholdKind kind = VectorThresholdKind.fromString("VectorThreshold"); /** * Creates an instance of VectorThreshold class. */ + @Generated public VectorThreshold() { } /** - * Get the kind property: The kind of threshold used to filter vector queries. + * Get the kind property: Type of threshold. * * @return the kind value. */ + @Generated public VectorThresholdKind getKind() { return this.kind; } @@ -41,6 +43,7 @@ public VectorThresholdKind getKind() { /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); @@ -56,6 +59,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { * pointing to JSON null. * @throws IOException If an error occurs while reading the VectorThreshold. */ + @Generated public static VectorThreshold fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { String discriminatorValue = null; @@ -83,6 +87,7 @@ public static VectorThreshold fromJson(JsonReader jsonReader) throws IOException }); } + @Generated static VectorThreshold fromJsonKnownDiscriminator(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { VectorThreshold deserializedVectorThreshold = new VectorThreshold(); diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/VectorThresholdKind.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/VectorThresholdKind.java index c1447a4612b6..34047cf24eb4 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/VectorThresholdKind.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/VectorThresholdKind.java @@ -1,11 +1,10 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.search.documents.models; +import com.azure.core.annotation.Generated; import com.azure.core.util.ExpandableStringEnum; import java.util.Collection; @@ -14,17 +13,20 @@ */ public final class VectorThresholdKind extends ExpandableStringEnum { /** - * 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. + * 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. */ + @Generated public static final VectorThresholdKind VECTOR_SIMILARITY = fromString("vectorSimilarity"); /** - * 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. + * 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. */ + @Generated public static final VectorThresholdKind SEARCH_SCORE = fromString("searchScore"); /** @@ -32,6 +34,7 @@ public final class VectorThresholdKind extends ExpandableStringEnum values() { return values(VectorThresholdKind.class); } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/VectorizableImageBinaryQuery.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/VectorizableImageBinaryQuery.java index bb9c1f2374f7..879710062e31 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/VectorizableImageBinaryQuery.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/VectorizableImageBinaryQuery.java @@ -1,66 +1,72 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) TypeSpec Code Generator. + package com.azure.search.documents.models; import com.azure.core.annotation.Fluent; +import com.azure.core.annotation.Generated; import com.azure.json.JsonReader; import com.azure.json.JsonToken; import com.azure.json.JsonWriter; import java.io.IOException; /** - * The query parameters to use for vector search when a base 64 encoded binary of an image that needs to be vectorized - * is provided. + * The query parameters to use for vector search when a base 64 encoded binary of + * an image that needs to be vectorized is provided. */ @Fluent public final class VectorizableImageBinaryQuery extends VectorQuery { - /* - * The kind of vector query being performed. + * Type of query. */ + @Generated private VectorQueryKind kind = VectorQueryKind.IMAGE_BINARY; /* - * The base 64 encoded binary of an image to be vectorized to perform a vector search query. + * The base 64 encoded binary of an image to be vectorized to perform a vector + * search query. */ + @Generated private String base64Image; /** * Creates an instance of VectorizableImageBinaryQuery class. */ + @Generated public VectorizableImageBinaryQuery() { } /** - * Get the kind property: The kind of vector query being performed. - * + * Get the kind property: Type of query. + * * @return the kind value. */ + @Generated @Override public VectorQueryKind getKind() { return this.kind; } /** - * Get the base64Image property: The base 64 encoded binary of an image to be vectorized to perform a vector search - * query. - * + * Get the base64Image property: The base 64 encoded binary of an image to be vectorized to perform a vector + * search query. + * * @return the base64Image value. */ + @Generated public String getBase64Image() { return this.base64Image; } /** - * Set the base64Image property: The base 64 encoded binary of an image to be vectorized to perform a vector search - * query. - * + * Set the base64Image property: The base 64 encoded binary of an image to be vectorized to perform a vector + * search query. + * * @param base64Image the base64Image value to set. * @return the VectorizableImageBinaryQuery object itself. */ + @Generated public VectorizableImageBinaryQuery setBase64Image(String base64Image) { this.base64Image = base64Image; return this; @@ -69,17 +75,19 @@ public VectorizableImageBinaryQuery setBase64Image(String base64Image) { /** * {@inheritDoc} */ + @Generated @Override - public VectorizableImageBinaryQuery setKNearestNeighborsCount(Integer kNearestNeighborsCount) { - super.setKNearestNeighborsCount(kNearestNeighborsCount); + public VectorizableImageBinaryQuery setKNearestNeighbors(Integer kNearestNeighbors) { + super.setKNearestNeighbors(kNearestNeighbors); return this; } /** * {@inheritDoc} */ + @Generated @Override - public VectorizableImageBinaryQuery setFields(String... fields) { + public VectorizableImageBinaryQuery setFields(String fields) { super.setFields(fields); return this; } @@ -87,6 +95,7 @@ public VectorizableImageBinaryQuery setFields(String... fields) { /** * {@inheritDoc} */ + @Generated @Override public VectorizableImageBinaryQuery setExhaustive(Boolean exhaustive) { super.setExhaustive(exhaustive); @@ -96,6 +105,7 @@ public VectorizableImageBinaryQuery setExhaustive(Boolean exhaustive) { /** * {@inheritDoc} */ + @Generated @Override public VectorizableImageBinaryQuery setOversampling(Double oversampling) { super.setOversampling(oversampling); @@ -105,8 +115,9 @@ public VectorizableImageBinaryQuery setOversampling(Double oversampling) { /** * {@inheritDoc} */ + @Generated @Override - public VectorizableImageBinaryQuery setWeight(Float weight) { + public VectorizableImageBinaryQuery setWeight(Double weight) { super.setWeight(weight); return this; } @@ -114,6 +125,7 @@ public VectorizableImageBinaryQuery setWeight(Float weight) { /** * {@inheritDoc} */ + @Generated @Override public VectorizableImageBinaryQuery setThreshold(VectorThreshold threshold) { super.setThreshold(threshold); @@ -123,6 +135,7 @@ public VectorizableImageBinaryQuery setThreshold(VectorThreshold threshold) { /** * {@inheritDoc} */ + @Generated @Override public VectorizableImageBinaryQuery setFilterOverride(String filterOverride) { super.setFilterOverride(filterOverride); @@ -132,10 +145,11 @@ public VectorizableImageBinaryQuery setFilterOverride(String filterOverride) { /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); - jsonWriter.writeNumberField("k", getKNearestNeighborsCount()); + jsonWriter.writeNumberField("k", getKNearestNeighbors()); jsonWriter.writeStringField("fields", getFields()); jsonWriter.writeBooleanField("exhaustive", isExhaustive()); jsonWriter.writeNumberField("oversampling", getOversampling()); @@ -149,21 +163,23 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of VectorizableImageBinaryQuery from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of VectorizableImageBinaryQuery if the JsonReader was pointing to an instance of it, or null * if it was pointing to JSON null. * @throws IOException If an error occurs while reading the VectorizableImageBinaryQuery. */ + @Generated public static VectorizableImageBinaryQuery fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { VectorizableImageBinaryQuery deserializedVectorizableImageBinaryQuery = new VectorizableImageBinaryQuery(); while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); + if ("k".equals(fieldName)) { deserializedVectorizableImageBinaryQuery - .setKNearestNeighborsCount(reader.getNullable(JsonReader::getInt)); + .setKNearestNeighbors(reader.getNullable(JsonReader::getInt)); } else if ("fields".equals(fieldName)) { deserializedVectorizableImageBinaryQuery.setFields(reader.getString()); } else if ("exhaustive".equals(fieldName)) { @@ -171,7 +187,7 @@ public static VectorizableImageBinaryQuery fromJson(JsonReader jsonReader) throw } else if ("oversampling".equals(fieldName)) { deserializedVectorizableImageBinaryQuery.setOversampling(reader.getNullable(JsonReader::getDouble)); } else if ("weight".equals(fieldName)) { - deserializedVectorizableImageBinaryQuery.setWeight(reader.getNullable(JsonReader::getFloat)); + deserializedVectorizableImageBinaryQuery.setWeight(reader.getNullable(JsonReader::getDouble)); } else if ("threshold".equals(fieldName)) { deserializedVectorizableImageBinaryQuery.setThreshold(VectorThreshold.fromJson(reader)); } else if ("filterOverride".equals(fieldName)) { @@ -184,6 +200,7 @@ public static VectorizableImageBinaryQuery fromJson(JsonReader jsonReader) throw reader.skipChildren(); } } + return deserializedVectorizableImageBinaryQuery; }); } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/VectorizableImageUrlQuery.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/VectorizableImageUrlQuery.java index f1a5a23499ca..22101e7aed2b 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/VectorizableImageUrlQuery.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/VectorizableImageUrlQuery.java @@ -1,44 +1,47 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) TypeSpec Code Generator. + package com.azure.search.documents.models; import com.azure.core.annotation.Fluent; +import com.azure.core.annotation.Generated; import com.azure.json.JsonReader; import com.azure.json.JsonToken; import com.azure.json.JsonWriter; import java.io.IOException; /** - * The query parameters to use for vector search when an url that represents an image value that needs to be vectorized - * is provided. + * The query parameters to use for vector search when an url that represents an + * image value that needs to be vectorized is provided. */ @Fluent public final class VectorizableImageUrlQuery extends VectorQuery { - /* - * The kind of vector query being performed. + * Type of query. */ + @Generated private VectorQueryKind kind = VectorQueryKind.IMAGE_URL; /* * The URL of an image to be vectorized to perform a vector search query. */ + @Generated private String url; /** * Creates an instance of VectorizableImageUrlQuery class. */ + @Generated public VectorizableImageUrlQuery() { } /** - * Get the kind property: The kind of vector query being performed. - * + * Get the kind property: Type of query. + * * @return the kind value. */ + @Generated @Override public VectorQueryKind getKind() { return this.kind; @@ -46,19 +49,21 @@ public VectorQueryKind getKind() { /** * Get the url property: The URL of an image to be vectorized to perform a vector search query. - * + * * @return the url value. */ + @Generated public String getUrl() { return this.url; } /** * Set the url property: The URL of an image to be vectorized to perform a vector search query. - * + * * @param url the url value to set. * @return the VectorizableImageUrlQuery object itself. */ + @Generated public VectorizableImageUrlQuery setUrl(String url) { this.url = url; return this; @@ -67,17 +72,19 @@ public VectorizableImageUrlQuery setUrl(String url) { /** * {@inheritDoc} */ + @Generated @Override - public VectorizableImageUrlQuery setKNearestNeighborsCount(Integer kNearestNeighborsCount) { - super.setKNearestNeighborsCount(kNearestNeighborsCount); + public VectorizableImageUrlQuery setKNearestNeighbors(Integer kNearestNeighbors) { + super.setKNearestNeighbors(kNearestNeighbors); return this; } /** * {@inheritDoc} */ + @Generated @Override - public VectorizableImageUrlQuery setFields(String... fields) { + public VectorizableImageUrlQuery setFields(String fields) { super.setFields(fields); return this; } @@ -85,6 +92,7 @@ public VectorizableImageUrlQuery setFields(String... fields) { /** * {@inheritDoc} */ + @Generated @Override public VectorizableImageUrlQuery setExhaustive(Boolean exhaustive) { super.setExhaustive(exhaustive); @@ -94,6 +102,7 @@ public VectorizableImageUrlQuery setExhaustive(Boolean exhaustive) { /** * {@inheritDoc} */ + @Generated @Override public VectorizableImageUrlQuery setOversampling(Double oversampling) { super.setOversampling(oversampling); @@ -103,8 +112,9 @@ public VectorizableImageUrlQuery setOversampling(Double oversampling) { /** * {@inheritDoc} */ + @Generated @Override - public VectorizableImageUrlQuery setWeight(Float weight) { + public VectorizableImageUrlQuery setWeight(Double weight) { super.setWeight(weight); return this; } @@ -112,6 +122,7 @@ public VectorizableImageUrlQuery setWeight(Float weight) { /** * {@inheritDoc} */ + @Generated @Override public VectorizableImageUrlQuery setThreshold(VectorThreshold threshold) { super.setThreshold(threshold); @@ -121,6 +132,7 @@ public VectorizableImageUrlQuery setThreshold(VectorThreshold threshold) { /** * {@inheritDoc} */ + @Generated @Override public VectorizableImageUrlQuery setFilterOverride(String filterOverride) { super.setFilterOverride(filterOverride); @@ -130,10 +142,11 @@ public VectorizableImageUrlQuery setFilterOverride(String filterOverride) { /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); - jsonWriter.writeNumberField("k", getKNearestNeighborsCount()); + jsonWriter.writeNumberField("k", getKNearestNeighbors()); jsonWriter.writeStringField("fields", getFields()); jsonWriter.writeBooleanField("exhaustive", isExhaustive()); jsonWriter.writeNumberField("oversampling", getOversampling()); @@ -147,21 +160,22 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of VectorizableImageUrlQuery from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of VectorizableImageUrlQuery if the JsonReader was pointing to an instance of it, or null if * it was pointing to JSON null. * @throws IOException If an error occurs while reading the VectorizableImageUrlQuery. */ + @Generated public static VectorizableImageUrlQuery fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { VectorizableImageUrlQuery deserializedVectorizableImageUrlQuery = new VectorizableImageUrlQuery(); while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); + if ("k".equals(fieldName)) { - deserializedVectorizableImageUrlQuery - .setKNearestNeighborsCount(reader.getNullable(JsonReader::getInt)); + deserializedVectorizableImageUrlQuery.setKNearestNeighbors(reader.getNullable(JsonReader::getInt)); } else if ("fields".equals(fieldName)) { deserializedVectorizableImageUrlQuery.setFields(reader.getString()); } else if ("exhaustive".equals(fieldName)) { @@ -169,7 +183,7 @@ public static VectorizableImageUrlQuery fromJson(JsonReader jsonReader) throws I } else if ("oversampling".equals(fieldName)) { deserializedVectorizableImageUrlQuery.setOversampling(reader.getNullable(JsonReader::getDouble)); } else if ("weight".equals(fieldName)) { - deserializedVectorizableImageUrlQuery.setWeight(reader.getNullable(JsonReader::getFloat)); + deserializedVectorizableImageUrlQuery.setWeight(reader.getNullable(JsonReader::getDouble)); } else if ("threshold".equals(fieldName)) { deserializedVectorizableImageUrlQuery.setThreshold(VectorThreshold.fromJson(reader)); } else if ("filterOverride".equals(fieldName)) { @@ -182,6 +196,7 @@ public static VectorizableImageUrlQuery fromJson(JsonReader jsonReader) throws I reader.skipChildren(); } } + return deserializedVectorizableImageUrlQuery; }); } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/VectorizableTextQuery.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/VectorizableTextQuery.java index 25c6b8af58f4..565906862d82 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/VectorizableTextQuery.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/VectorizableTextQuery.java @@ -1,51 +1,57 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) TypeSpec Code Generator. + package com.azure.search.documents.models; import com.azure.core.annotation.Fluent; +import com.azure.core.annotation.Generated; import com.azure.json.JsonReader; import com.azure.json.JsonToken; import com.azure.json.JsonWriter; import java.io.IOException; /** - * The query parameters to use for vector search when a text value that needs to be vectorized is provided. + * The query parameters to use for vector search when a text value that needs to + * be vectorized is provided. */ @Fluent public final class VectorizableTextQuery extends VectorQuery { - /* - * The kind of vector query being performed. + * Type of query. */ + @Generated private VectorQueryKind kind = VectorQueryKind.TEXT; /* * The text to be vectorized to perform a vector search query. */ + @Generated private final String text; /* - * Can be configured to let a generative model rewrite the query before sending it to be vectorized. + * Can be configured to let a generative model rewrite the query before sending it + * to be vectorized. */ - private QueryRewrites queryRewrites; + @Generated + private QueryRewritesType queryRewrites; /** * Creates an instance of VectorizableTextQuery class. - * + * * @param text the text value to set. */ + @Generated public VectorizableTextQuery(String text) { this.text = text; } /** - * Get the kind property: The kind of vector query being performed. - * + * Get the kind property: Type of query. + * * @return the kind value. */ + @Generated @Override public VectorQueryKind getKind() { return this.kind; @@ -53,9 +59,10 @@ public VectorQueryKind getKind() { /** * Get the text property: The text to be vectorized to perform a vector search query. - * + * * @return the text value. */ + @Generated public String getText() { return this.text; } @@ -63,21 +70,23 @@ public String getText() { /** * Get the queryRewrites property: Can be configured to let a generative model rewrite the query before sending it * to be vectorized. - * + * * @return the queryRewrites value. */ - public QueryRewrites getQueryRewrites() { + @Generated + public QueryRewritesType getQueryRewrites() { return this.queryRewrites; } /** * Set the queryRewrites property: Can be configured to let a generative model rewrite the query before sending it * to be vectorized. - * + * * @param queryRewrites the queryRewrites value to set. * @return the VectorizableTextQuery object itself. */ - public VectorizableTextQuery setQueryRewrites(QueryRewrites queryRewrites) { + @Generated + public VectorizableTextQuery setQueryRewrites(QueryRewritesType queryRewrites) { this.queryRewrites = queryRewrites; return this; } @@ -85,17 +94,19 @@ public VectorizableTextQuery setQueryRewrites(QueryRewrites queryRewrites) { /** * {@inheritDoc} */ + @Generated @Override - public VectorizableTextQuery setKNearestNeighborsCount(Integer kNearestNeighborsCount) { - super.setKNearestNeighborsCount(kNearestNeighborsCount); + public VectorizableTextQuery setKNearestNeighbors(Integer kNearestNeighbors) { + super.setKNearestNeighbors(kNearestNeighbors); return this; } /** * {@inheritDoc} */ + @Generated @Override - public VectorizableTextQuery setFields(String... fields) { + public VectorizableTextQuery setFields(String fields) { super.setFields(fields); return this; } @@ -103,6 +114,7 @@ public VectorizableTextQuery setFields(String... fields) { /** * {@inheritDoc} */ + @Generated @Override public VectorizableTextQuery setExhaustive(Boolean exhaustive) { super.setExhaustive(exhaustive); @@ -112,6 +124,7 @@ public VectorizableTextQuery setExhaustive(Boolean exhaustive) { /** * {@inheritDoc} */ + @Generated @Override public VectorizableTextQuery setOversampling(Double oversampling) { super.setOversampling(oversampling); @@ -121,8 +134,9 @@ public VectorizableTextQuery setOversampling(Double oversampling) { /** * {@inheritDoc} */ + @Generated @Override - public VectorizableTextQuery setWeight(Float weight) { + public VectorizableTextQuery setWeight(Double weight) { super.setWeight(weight); return this; } @@ -130,6 +144,7 @@ public VectorizableTextQuery setWeight(Float weight) { /** * {@inheritDoc} */ + @Generated @Override public VectorizableTextQuery setThreshold(VectorThreshold threshold) { super.setThreshold(threshold); @@ -139,6 +154,7 @@ public VectorizableTextQuery setThreshold(VectorThreshold threshold) { /** * {@inheritDoc} */ + @Generated @Override public VectorizableTextQuery setFilterOverride(String filterOverride) { super.setFilterOverride(filterOverride); @@ -148,10 +164,11 @@ public VectorizableTextQuery setFilterOverride(String filterOverride) { /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); - jsonWriter.writeNumberField("k", getKNearestNeighborsCount()); + jsonWriter.writeNumberField("k", getKNearestNeighbors()); jsonWriter.writeStringField("fields", getFields()); jsonWriter.writeBooleanField("exhaustive", isExhaustive()); jsonWriter.writeNumberField("oversampling", getOversampling()); @@ -166,31 +183,32 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of VectorizableTextQuery from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of VectorizableTextQuery if the JsonReader was pointing to an instance of it, or null if it * was pointing to JSON null. * @throws IllegalStateException If the deserialized JSON object was missing any required properties. * @throws IOException If an error occurs while reading the VectorizableTextQuery. */ + @Generated public static VectorizableTextQuery fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { - Integer kNearestNeighborsCount = null; + Integer kNearestNeighbors = null; String fields = null; Boolean exhaustive = null; Double oversampling = null; - Float weight = null; + Double weight = null; VectorThreshold threshold = null; String filterOverride = null; - boolean textFound = false; String text = null; VectorQueryKind kind = VectorQueryKind.TEXT; - QueryRewrites queryRewrites = null; + QueryRewritesType queryRewrites = null; while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); + if ("k".equals(fieldName)) { - kNearestNeighborsCount = reader.getNullable(JsonReader::getInt); + kNearestNeighbors = reader.getNullable(JsonReader::getInt); } else if ("fields".equals(fieldName)) { fields = reader.getString(); } else if ("exhaustive".equals(fieldName)) { @@ -198,36 +216,33 @@ public static VectorizableTextQuery fromJson(JsonReader jsonReader) throws IOExc } else if ("oversampling".equals(fieldName)) { oversampling = reader.getNullable(JsonReader::getDouble); } else if ("weight".equals(fieldName)) { - weight = reader.getNullable(JsonReader::getFloat); + weight = reader.getNullable(JsonReader::getDouble); } else if ("threshold".equals(fieldName)) { threshold = VectorThreshold.fromJson(reader); } else if ("filterOverride".equals(fieldName)) { filterOverride = reader.getString(); } else if ("text".equals(fieldName)) { text = reader.getString(); - textFound = true; } else if ("kind".equals(fieldName)) { kind = VectorQueryKind.fromString(reader.getString()); } else if ("queryRewrites".equals(fieldName)) { - queryRewrites = QueryRewrites.fromString(reader.getString()); + queryRewrites = QueryRewritesType.fromString(reader.getString()); } else { reader.skipChildren(); } } - if (textFound) { - VectorizableTextQuery deserializedVectorizableTextQuery = new VectorizableTextQuery(text); - deserializedVectorizableTextQuery.setKNearestNeighborsCount(kNearestNeighborsCount); - deserializedVectorizableTextQuery.setFields(fields); - deserializedVectorizableTextQuery.setExhaustive(exhaustive); - deserializedVectorizableTextQuery.setOversampling(oversampling); - deserializedVectorizableTextQuery.setWeight(weight); - deserializedVectorizableTextQuery.setThreshold(threshold); - deserializedVectorizableTextQuery.setFilterOverride(filterOverride); - deserializedVectorizableTextQuery.kind = kind; - deserializedVectorizableTextQuery.queryRewrites = queryRewrites; - return deserializedVectorizableTextQuery; - } - throw new IllegalStateException("Missing required property: text"); + VectorizableTextQuery deserializedVectorizableTextQuery = new VectorizableTextQuery(text); + deserializedVectorizableTextQuery.setKNearestNeighbors(kNearestNeighbors); + deserializedVectorizableTextQuery.setFields(fields); + deserializedVectorizableTextQuery.setExhaustive(exhaustive); + deserializedVectorizableTextQuery.setOversampling(oversampling); + deserializedVectorizableTextQuery.setWeight(weight); + deserializedVectorizableTextQuery.setThreshold(threshold); + deserializedVectorizableTextQuery.setFilterOverride(filterOverride); + deserializedVectorizableTextQuery.kind = kind; + deserializedVectorizableTextQuery.queryRewrites = queryRewrites; + + return deserializedVectorizableTextQuery; }); } } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/VectorizedQuery.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/VectorizedQuery.java index 3135f3aca958..d4d99de9a7f0 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/VectorizedQuery.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/VectorizedQuery.java @@ -1,11 +1,11 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) TypeSpec Code Generator. + package com.azure.search.documents.models; import com.azure.core.annotation.Fluent; +import com.azure.core.annotation.Generated; import com.azure.json.JsonReader; import com.azure.json.JsonToken; import com.azure.json.JsonWriter; @@ -13,35 +13,39 @@ import java.util.List; /** - * The query parameters to use for vector search when a raw vector value is provided. + * The query parameters to use for vector search when a raw vector value is + * provided. */ @Fluent public final class VectorizedQuery extends VectorQuery { - /* - * The kind of vector query being performed. + * Type of query. */ + @Generated private VectorQueryKind kind = VectorQueryKind.VECTOR; /* * The vector representation of a search query. */ - private final List vector; + @Generated + private final List vector; /** * Creates an instance of VectorizedQuery class. - * + * * @param vector the vector value to set. */ - public VectorizedQuery(List vector) { + @Generated + public VectorizedQuery(List vector) { this.vector = vector; } /** - * Get the kind property: The kind of vector query being performed. - * + * Get the kind property: Type of query. + * * @return the kind value. */ + @Generated @Override public VectorQueryKind getKind() { return this.kind; @@ -49,27 +53,30 @@ public VectorQueryKind getKind() { /** * Get the vector property: The vector representation of a search query. - * + * * @return the vector value. */ - public List getVector() { + @Generated + public List getVector() { return this.vector; } /** * {@inheritDoc} */ + @Generated @Override - public VectorizedQuery setKNearestNeighborsCount(Integer kNearestNeighborsCount) { - super.setKNearestNeighborsCount(kNearestNeighborsCount); + public VectorizedQuery setKNearestNeighbors(Integer kNearestNeighbors) { + super.setKNearestNeighbors(kNearestNeighbors); return this; } /** * {@inheritDoc} */ + @Generated @Override - public VectorizedQuery setFields(String... fields) { + public VectorizedQuery setFields(String fields) { super.setFields(fields); return this; } @@ -77,6 +84,7 @@ public VectorizedQuery setFields(String... fields) { /** * {@inheritDoc} */ + @Generated @Override public VectorizedQuery setExhaustive(Boolean exhaustive) { super.setExhaustive(exhaustive); @@ -86,6 +94,7 @@ public VectorizedQuery setExhaustive(Boolean exhaustive) { /** * {@inheritDoc} */ + @Generated @Override public VectorizedQuery setOversampling(Double oversampling) { super.setOversampling(oversampling); @@ -95,8 +104,9 @@ public VectorizedQuery setOversampling(Double oversampling) { /** * {@inheritDoc} */ + @Generated @Override - public VectorizedQuery setWeight(Float weight) { + public VectorizedQuery setWeight(Double weight) { super.setWeight(weight); return this; } @@ -104,6 +114,7 @@ public VectorizedQuery setWeight(Float weight) { /** * {@inheritDoc} */ + @Generated @Override public VectorizedQuery setThreshold(VectorThreshold threshold) { super.setThreshold(threshold); @@ -113,6 +124,7 @@ public VectorizedQuery setThreshold(VectorThreshold threshold) { /** * {@inheritDoc} */ + @Generated @Override public VectorizedQuery setFilterOverride(String filterOverride) { super.setFilterOverride(filterOverride); @@ -122,47 +134,49 @@ public VectorizedQuery setFilterOverride(String filterOverride) { /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); - jsonWriter.writeNumberField("k", getKNearestNeighborsCount()); + jsonWriter.writeNumberField("k", getKNearestNeighbors()); jsonWriter.writeStringField("fields", getFields()); jsonWriter.writeBooleanField("exhaustive", isExhaustive()); jsonWriter.writeNumberField("oversampling", getOversampling()); jsonWriter.writeNumberField("weight", getWeight()); jsonWriter.writeJsonField("threshold", getThreshold()); jsonWriter.writeStringField("filterOverride", getFilterOverride()); - jsonWriter.writeArrayField("vector", this.vector, (writer, element) -> writer.writeFloat(element)); + jsonWriter.writeArrayField("vector", this.vector, (writer, element) -> writer.writeDouble(element)); jsonWriter.writeStringField("kind", this.kind == null ? null : this.kind.toString()); return jsonWriter.writeEndObject(); } /** * Reads an instance of VectorizedQuery from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of VectorizedQuery if the JsonReader was pointing to an instance of it, or null if it was * pointing to JSON null. * @throws IllegalStateException If the deserialized JSON object was missing any required properties. * @throws IOException If an error occurs while reading the VectorizedQuery. */ + @Generated public static VectorizedQuery fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { - Integer kNearestNeighborsCount = null; + Integer kNearestNeighbors = null; String fields = null; Boolean exhaustive = null; Double oversampling = null; - Float weight = null; + Double weight = null; VectorThreshold threshold = null; String filterOverride = null; - boolean vectorFound = false; - List vector = null; + List vector = null; VectorQueryKind kind = VectorQueryKind.VECTOR; while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); + if ("k".equals(fieldName)) { - kNearestNeighborsCount = reader.getNullable(JsonReader::getInt); + kNearestNeighbors = reader.getNullable(JsonReader::getInt); } else if ("fields".equals(fieldName)) { fields = reader.getString(); } else if ("exhaustive".equals(fieldName)) { @@ -170,33 +184,30 @@ public static VectorizedQuery fromJson(JsonReader jsonReader) throws IOException } else if ("oversampling".equals(fieldName)) { oversampling = reader.getNullable(JsonReader::getDouble); } else if ("weight".equals(fieldName)) { - weight = reader.getNullable(JsonReader::getFloat); + weight = reader.getNullable(JsonReader::getDouble); } else if ("threshold".equals(fieldName)) { threshold = VectorThreshold.fromJson(reader); } else if ("filterOverride".equals(fieldName)) { filterOverride = reader.getString(); } else if ("vector".equals(fieldName)) { - vector = reader.readArray(reader1 -> reader1.getFloat()); - vectorFound = true; + vector = reader.readArray(reader1 -> reader1.getDouble()); } else if ("kind".equals(fieldName)) { kind = VectorQueryKind.fromString(reader.getString()); } else { reader.skipChildren(); } } - if (vectorFound) { - VectorizedQuery deserializedVectorizedQuery = new VectorizedQuery(vector); - deserializedVectorizedQuery.setKNearestNeighborsCount(kNearestNeighborsCount); - deserializedVectorizedQuery.setFields(fields); - deserializedVectorizedQuery.setExhaustive(exhaustive); - deserializedVectorizedQuery.setOversampling(oversampling); - deserializedVectorizedQuery.setWeight(weight); - deserializedVectorizedQuery.setThreshold(threshold); - deserializedVectorizedQuery.setFilterOverride(filterOverride); - deserializedVectorizedQuery.kind = kind; - return deserializedVectorizedQuery; - } - throw new IllegalStateException("Missing required property: vector"); + VectorizedQuery deserializedVectorizedQuery = new VectorizedQuery(vector); + deserializedVectorizedQuery.setKNearestNeighbors(kNearestNeighbors); + deserializedVectorizedQuery.setFields(fields); + deserializedVectorizedQuery.setExhaustive(exhaustive); + deserializedVectorizedQuery.setOversampling(oversampling); + deserializedVectorizedQuery.setWeight(weight); + deserializedVectorizedQuery.setThreshold(threshold); + deserializedVectorizedQuery.setFilterOverride(filterOverride); + deserializedVectorizedQuery.kind = kind; + + return deserializedVectorizedQuery; }); } } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/VectorsDebugInfo.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/VectorsDebugInfo.java index 874442a5b4a7..c4ed872d5612 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/VectorsDebugInfo.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/VectorsDebugInfo.java @@ -1,11 +1,10 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) TypeSpec Code Generator. package com.azure.search.documents.models; +import com.azure.core.annotation.Generated; import com.azure.core.annotation.Immutable; import com.azure.json.JsonReader; import com.azure.json.JsonSerializable; @@ -14,19 +13,22 @@ import java.io.IOException; /** - * The VectorsDebugInfo model. + * "Contains debugging information specific to vector and hybrid search."). */ @Immutable public final class VectorsDebugInfo implements JsonSerializable { /* - * The breakdown of subscores of the document prior to the chosen result set fusion/combination method such as RRF. + * The breakdown of subscores of the document prior to the chosen result set + * fusion/combination method such as RRF. */ + @Generated private QueryResultDocumentSubscores subscores; /** * Creates an instance of VectorsDebugInfo class. */ - public VectorsDebugInfo() { + @Generated + private VectorsDebugInfo() { } /** @@ -35,6 +37,7 @@ public VectorsDebugInfo() { * * @return the subscores value. */ + @Generated public QueryResultDocumentSubscores getSubscores() { return this.subscores; } @@ -42,6 +45,7 @@ public QueryResultDocumentSubscores getSubscores() { /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); @@ -56,6 +60,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { * pointing to JSON null. * @throws IOException If an error occurs while reading the VectorsDebugInfo. */ + @Generated public static VectorsDebugInfo fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { VectorsDebugInfo deserializedVectorsDebugInfo = new VectorsDebugInfo(); diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/VisionVectorizeSkill.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/VisionVectorizeSkill.java similarity index 72% rename from sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/VisionVectorizeSkill.java rename to sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/VisionVectorizeSkill.java index 568a2a07bc40..386ed6f85003 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/VisionVectorizeSkill.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/VisionVectorizeSkill.java @@ -1,34 +1,34 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) TypeSpec Code Generator. -package com.azure.search.documents.indexes.models; +package com.azure.search.documents.models; import com.azure.core.annotation.Fluent; +import com.azure.core.annotation.Generated; import com.azure.json.JsonReader; import com.azure.json.JsonToken; import com.azure.json.JsonWriter; import java.io.IOException; -import java.util.ArrayList; import java.util.List; /** - * Allows you to generate a vector embedding for a given image or text input using the Azure AI Services Vision - * Vectorize API. + * Allows you to generate a vector embedding for a given image or text input using + * the Azure AI Services Vision Vectorize API. */ @Fluent public final class VisionVectorizeSkill extends SearchIndexerSkill { /* - * A URI fragment specifying the type of skill. + * The discriminator for derived types. */ + @Generated private String odataType = "#Microsoft.Skills.Vision.VectorizeSkill"; /* - * The version of the model to use when calling the AI Services Vision service. It will default to the latest - * available when not specified. + * The version of the model to use when calling the AI Services Vision service. It + * will default to the latest available when not specified. */ + @Generated private final String modelVersion; /** @@ -38,6 +38,7 @@ public final class VisionVectorizeSkill extends SearchIndexerSkill { * @param outputs the outputs value to set. * @param modelVersion the modelVersion value to set. */ + @Generated public VisionVectorizeSkill(List inputs, List outputs, String modelVersion) { super(inputs, outputs); @@ -45,10 +46,11 @@ public VisionVectorizeSkill(List inputs, List { - boolean inputsFound = false; List inputs = null; - boolean outputsFound = false; List outputs = null; String name = null; String description = null; String context = null; - boolean modelVersionFound = false; String modelVersion = null; String odataType = "#Microsoft.Skills.Vision.VectorizeSkill"; while (reader.nextToken() != JsonToken.END_OBJECT) { @@ -134,10 +139,8 @@ public static VisionVectorizeSkill fromJson(JsonReader jsonReader) throws IOExce if ("inputs".equals(fieldName)) { inputs = reader.readArray(reader1 -> InputFieldMappingEntry.fromJson(reader1)); - inputsFound = true; } else if ("outputs".equals(fieldName)) { outputs = reader.readArray(reader1 -> OutputFieldMappingEntry.fromJson(reader1)); - outputsFound = true; } else if ("name".equals(fieldName)) { name = reader.getString(); } else if ("description".equals(fieldName)) { @@ -146,36 +149,20 @@ public static VisionVectorizeSkill fromJson(JsonReader jsonReader) throws IOExce context = reader.getString(); } else if ("modelVersion".equals(fieldName)) { modelVersion = reader.getString(); - modelVersionFound = true; } else if ("@odata.type".equals(fieldName)) { odataType = reader.getString(); } else { reader.skipChildren(); } } - if (inputsFound && outputsFound && modelVersionFound) { - VisionVectorizeSkill deserializedVisionVectorizeSkill - = new VisionVectorizeSkill(inputs, outputs, modelVersion); - deserializedVisionVectorizeSkill.setName(name); - deserializedVisionVectorizeSkill.setDescription(description); - deserializedVisionVectorizeSkill.setContext(context); - deserializedVisionVectorizeSkill.odataType = odataType; - - return deserializedVisionVectorizeSkill; - } - List missingProperties = new ArrayList<>(); - if (!inputsFound) { - missingProperties.add("inputs"); - } - if (!outputsFound) { - missingProperties.add("outputs"); - } - if (!modelVersionFound) { - missingProperties.add("modelVersion"); - } + VisionVectorizeSkill deserializedVisionVectorizeSkill + = new VisionVectorizeSkill(inputs, outputs, modelVersion); + deserializedVisionVectorizeSkill.setName(name); + deserializedVisionVectorizeSkill.setDescription(description); + deserializedVisionVectorizeSkill.setContext(context); + deserializedVisionVectorizeSkill.odataType = odataType; - throw new IllegalStateException( - "Missing required property/properties: " + String.join(", ", missingProperties)); + return deserializedVisionVectorizeSkill; }); } } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/VisualFeature.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/VisualFeature.java similarity index 86% rename from sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/VisualFeature.java rename to sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/VisualFeature.java index f68904c0f5b7..0570379c3058 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/VisualFeature.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/VisualFeature.java @@ -1,11 +1,10 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) TypeSpec Code Generator. -package com.azure.search.documents.indexes.models; +package com.azure.search.documents.models; +import com.azure.core.annotation.Generated; import com.azure.core.util.ExpandableStringEnum; import java.util.Collection; @@ -16,36 +15,43 @@ public final class VisualFeature extends ExpandableStringEnum { /** * Visual features recognized as adult persons. */ + @Generated public static final VisualFeature ADULT = fromString("adult"); /** * Visual features recognized as commercial brands. */ + @Generated public static final VisualFeature BRANDS = fromString("brands"); /** * Categories. */ + @Generated public static final VisualFeature CATEGORIES = fromString("categories"); /** * Description. */ + @Generated public static final VisualFeature DESCRIPTION = fromString("description"); /** * Visual features recognized as people faces. */ + @Generated public static final VisualFeature FACES = fromString("faces"); /** * Visual features recognized as objects. */ + @Generated public static final VisualFeature OBJECTS = fromString("objects"); /** * Tags. */ + @Generated public static final VisualFeature TAGS = fromString("tags"); /** @@ -53,6 +59,7 @@ public final class VisualFeature extends ExpandableStringEnum { * * @deprecated Use the {@link #fromString(String)} factory method. */ + @Generated @Deprecated public VisualFeature() { } @@ -63,6 +70,7 @@ public VisualFeature() { * @param name a name to look for. * @return the corresponding VisualFeature. */ + @Generated public static VisualFeature fromString(String name) { return fromString(name, VisualFeature.class); } @@ -72,6 +80,7 @@ public static VisualFeature fromString(String name) { * * @return known VisualFeature values. */ + @Generated public static Collection values() { return values(VisualFeature.class); } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/WebApiSkill.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/WebApiSkill.java similarity index 74% rename from sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/WebApiSkill.java rename to sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/WebApiSkill.java index 960dded4c3bf..585cf24ae797 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/WebApiSkill.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/WebApiSkill.java @@ -1,76 +1,88 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) TypeSpec Code Generator. -package com.azure.search.documents.indexes.models; +package com.azure.search.documents.models; import com.azure.core.annotation.Fluent; +import com.azure.core.annotation.Generated; import com.azure.core.util.CoreUtils; import com.azure.json.JsonReader; import com.azure.json.JsonToken; import com.azure.json.JsonWriter; import java.io.IOException; import java.time.Duration; -import java.util.ArrayList; import java.util.List; import java.util.Map; /** - * A skill that can call a Web API endpoint, allowing you to extend a skillset by having it call your custom code. + * A skill that can call a Web API endpoint, allowing you to extend a skillset by + * having it call your custom code. */ @Fluent public final class WebApiSkill extends SearchIndexerSkill { /* - * A URI fragment specifying the type of skill. + * The discriminator for derived types. */ + @Generated private String odataType = "#Microsoft.Skills.Custom.WebApiSkill"; /* * The url for the Web API. */ + @Generated private final String uri; /* * The headers required to make the http request. */ + @Generated private Map httpHeaders; /* * The method for the http request. */ + @Generated private String httpMethod; /* * The desired timeout for the request. Default is 30 seconds. */ + @Generated private Duration timeout; /* * The desired batch size which indicates number of documents. */ + @Generated private Integer batchSize; /* * If set, the number of parallel calls that can be made to the Web API. */ + @Generated private Integer degreeOfParallelism; /* - * 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. + * 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. */ + @Generated private String authResourceId; /* - * 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. + * 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. */ + @Generated private SearchIndexerDataIdentity authIdentity; /** @@ -80,16 +92,18 @@ public final class WebApiSkill extends SearchIndexerSkill { * @param outputs the outputs value to set. * @param uri the uri value to set. */ + @Generated public WebApiSkill(List inputs, List outputs, String uri) { super(inputs, outputs); this.uri = uri; } /** - * Get the odataType property: A URI fragment specifying the type of skill. + * Get the odataType property: The discriminator for derived types. * * @return the odataType value. */ + @Generated @Override public String getOdataType() { return this.odataType; @@ -100,6 +114,7 @@ public String getOdataType() { * * @return the uri value. */ + @Generated public String getUri() { return this.uri; } @@ -109,6 +124,7 @@ public String getUri() { * * @return the httpHeaders value. */ + @Generated public Map getHttpHeaders() { return this.httpHeaders; } @@ -119,6 +135,7 @@ public Map getHttpHeaders() { * @param httpHeaders the httpHeaders value to set. * @return the WebApiSkill object itself. */ + @Generated public WebApiSkill setHttpHeaders(Map httpHeaders) { this.httpHeaders = httpHeaders; return this; @@ -129,6 +146,7 @@ public WebApiSkill setHttpHeaders(Map httpHeaders) { * * @return the httpMethod value. */ + @Generated public String getHttpMethod() { return this.httpMethod; } @@ -139,6 +157,7 @@ public String getHttpMethod() { * @param httpMethod the httpMethod value to set. * @return the WebApiSkill object itself. */ + @Generated public WebApiSkill setHttpMethod(String httpMethod) { this.httpMethod = httpMethod; return this; @@ -149,6 +168,7 @@ public WebApiSkill setHttpMethod(String httpMethod) { * * @return the timeout value. */ + @Generated public Duration getTimeout() { return this.timeout; } @@ -159,6 +179,7 @@ public Duration getTimeout() { * @param timeout the timeout value to set. * @return the WebApiSkill object itself. */ + @Generated public WebApiSkill setTimeout(Duration timeout) { this.timeout = timeout; return this; @@ -169,6 +190,7 @@ public WebApiSkill setTimeout(Duration timeout) { * * @return the batchSize value. */ + @Generated public Integer getBatchSize() { return this.batchSize; } @@ -179,6 +201,7 @@ public Integer getBatchSize() { * @param batchSize the batchSize value to set. * @return the WebApiSkill object itself. */ + @Generated public WebApiSkill setBatchSize(Integer batchSize) { this.batchSize = batchSize; return this; @@ -189,6 +212,7 @@ public WebApiSkill setBatchSize(Integer batchSize) { * * @return the degreeOfParallelism value. */ + @Generated public Integer getDegreeOfParallelism() { return this.degreeOfParallelism; } @@ -199,6 +223,7 @@ public Integer getDegreeOfParallelism() { * @param degreeOfParallelism the degreeOfParallelism value to set. * @return the WebApiSkill object itself. */ + @Generated public WebApiSkill setDegreeOfParallelism(Integer degreeOfParallelism) { this.degreeOfParallelism = degreeOfParallelism; return this; @@ -206,27 +231,33 @@ public WebApiSkill setDegreeOfParallelism(Integer degreeOfParallelism) { /** * Get the authResourceId property: 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. + * 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. * * @return the authResourceId value. */ + @Generated public String getAuthResourceId() { return this.authResourceId; } /** * Set the authResourceId property: 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. + * 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. * * @param authResourceId the authResourceId value to set. * @return the WebApiSkill object itself. */ + @Generated public WebApiSkill setAuthResourceId(String authResourceId) { this.authResourceId = authResourceId; return this; @@ -234,25 +265,29 @@ public WebApiSkill setAuthResourceId(String authResourceId) { /** * Get the authIdentity property: 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. + * 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. * * @return the authIdentity value. */ + @Generated public SearchIndexerDataIdentity getAuthIdentity() { return this.authIdentity; } /** * Set the authIdentity property: 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. + * 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. * * @param authIdentity the authIdentity value to set. * @return the WebApiSkill object itself. */ + @Generated public WebApiSkill setAuthIdentity(SearchIndexerDataIdentity authIdentity) { this.authIdentity = authIdentity; return this; @@ -261,6 +296,7 @@ public WebApiSkill setAuthIdentity(SearchIndexerDataIdentity authIdentity) { /** * {@inheritDoc} */ + @Generated @Override public WebApiSkill setName(String name) { super.setName(name); @@ -270,6 +306,7 @@ public WebApiSkill setName(String name) { /** * {@inheritDoc} */ + @Generated @Override public WebApiSkill setDescription(String description) { super.setDescription(description); @@ -279,6 +316,7 @@ public WebApiSkill setDescription(String description) { /** * {@inheritDoc} */ + @Generated @Override public WebApiSkill setContext(String context) { super.setContext(context); @@ -288,6 +326,7 @@ public WebApiSkill setContext(String context) { /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); @@ -317,16 +356,14 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { * @throws IllegalStateException If the deserialized JSON object was missing any required properties. * @throws IOException If an error occurs while reading the WebApiSkill. */ + @Generated public static WebApiSkill fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { - boolean inputsFound = false; List inputs = null; - boolean outputsFound = false; List outputs = null; String name = null; String description = null; String context = null; - boolean uriFound = false; String uri = null; String odataType = "#Microsoft.Skills.Custom.WebApiSkill"; Map httpHeaders = null; @@ -342,10 +379,8 @@ public static WebApiSkill fromJson(JsonReader jsonReader) throws IOException { if ("inputs".equals(fieldName)) { inputs = reader.readArray(reader1 -> InputFieldMappingEntry.fromJson(reader1)); - inputsFound = true; } else if ("outputs".equals(fieldName)) { outputs = reader.readArray(reader1 -> OutputFieldMappingEntry.fromJson(reader1)); - outputsFound = true; } else if ("name".equals(fieldName)) { name = reader.getString(); } else if ("description".equals(fieldName)) { @@ -354,7 +389,6 @@ public static WebApiSkill fromJson(JsonReader jsonReader) throws IOException { context = reader.getString(); } else if ("uri".equals(fieldName)) { uri = reader.getString(); - uriFound = true; } else if ("@odata.type".equals(fieldName)) { odataType = reader.getString(); } else if ("httpHeaders".equals(fieldName)) { @@ -375,35 +409,20 @@ public static WebApiSkill fromJson(JsonReader jsonReader) throws IOException { reader.skipChildren(); } } - if (inputsFound && outputsFound && uriFound) { - WebApiSkill deserializedWebApiSkill = new WebApiSkill(inputs, outputs, uri); - deserializedWebApiSkill.setName(name); - deserializedWebApiSkill.setDescription(description); - deserializedWebApiSkill.setContext(context); - deserializedWebApiSkill.odataType = odataType; - deserializedWebApiSkill.httpHeaders = httpHeaders; - deserializedWebApiSkill.httpMethod = httpMethod; - deserializedWebApiSkill.timeout = timeout; - deserializedWebApiSkill.batchSize = batchSize; - deserializedWebApiSkill.degreeOfParallelism = degreeOfParallelism; - deserializedWebApiSkill.authResourceId = authResourceId; - deserializedWebApiSkill.authIdentity = authIdentity; - - return deserializedWebApiSkill; - } - List missingProperties = new ArrayList<>(); - if (!inputsFound) { - missingProperties.add("inputs"); - } - if (!outputsFound) { - missingProperties.add("outputs"); - } - if (!uriFound) { - missingProperties.add("uri"); - } - - throw new IllegalStateException( - "Missing required property/properties: " + String.join(", ", missingProperties)); + WebApiSkill deserializedWebApiSkill = new WebApiSkill(inputs, outputs, uri); + deserializedWebApiSkill.setName(name); + deserializedWebApiSkill.setDescription(description); + deserializedWebApiSkill.setContext(context); + deserializedWebApiSkill.odataType = odataType; + deserializedWebApiSkill.httpHeaders = httpHeaders; + deserializedWebApiSkill.httpMethod = httpMethod; + deserializedWebApiSkill.timeout = timeout; + deserializedWebApiSkill.batchSize = batchSize; + deserializedWebApiSkill.degreeOfParallelism = degreeOfParallelism; + deserializedWebApiSkill.authResourceId = authResourceId; + deserializedWebApiSkill.authIdentity = authIdentity; + + return deserializedWebApiSkill; }); } } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/WebApiVectorizer.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/WebApiVectorizer.java similarity index 77% rename from sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/WebApiVectorizer.java rename to sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/WebApiVectorizer.java index 70dc18e466b9..fcc39b77986a 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/WebApiVectorizer.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/WebApiVectorizer.java @@ -1,31 +1,33 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) TypeSpec Code Generator. -package com.azure.search.documents.indexes.models; +package com.azure.search.documents.models; import com.azure.core.annotation.Fluent; +import com.azure.core.annotation.Generated; import com.azure.json.JsonReader; import com.azure.json.JsonToken; import com.azure.json.JsonWriter; import java.io.IOException; /** - * 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. + * 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. */ @Fluent public final class WebApiVectorizer extends VectorSearchVectorizer { /* - * The name of the kind of vectorization method being configured for use with vector search. + * Type of VectorSearchVectorizer. */ + @Generated private VectorSearchVectorizerKind kind = VectorSearchVectorizerKind.CUSTOM_WEB_API; /* * Specifies the properties of the user-defined vectorizer. */ + @Generated private WebApiVectorizerParameters webApiParameters; /** @@ -33,15 +35,17 @@ public final class WebApiVectorizer extends VectorSearchVectorizer { * * @param vectorizerName the vectorizerName value to set. */ + @Generated public WebApiVectorizer(String vectorizerName) { super(vectorizerName); } /** - * Get the kind property: The name of the kind of vectorization method being configured for use with vector search. + * Get the kind property: Type of VectorSearchVectorizer. * * @return the kind value. */ + @Generated @Override public VectorSearchVectorizerKind getKind() { return this.kind; @@ -52,6 +56,7 @@ public VectorSearchVectorizerKind getKind() { * * @return the webApiParameters value. */ + @Generated public WebApiVectorizerParameters getWebApiParameters() { return this.webApiParameters; } @@ -62,6 +67,7 @@ public WebApiVectorizerParameters getWebApiParameters() { * @param webApiParameters the webApiParameters value to set. * @return the WebApiVectorizer object itself. */ + @Generated public WebApiVectorizer setWebApiParameters(WebApiVectorizerParameters webApiParameters) { this.webApiParameters = webApiParameters; return this; @@ -70,6 +76,7 @@ public WebApiVectorizer setWebApiParameters(WebApiVectorizerParameters webApiPar /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); @@ -88,9 +95,9 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { * @throws IllegalStateException If the deserialized JSON object was missing any required properties. * @throws IOException If an error occurs while reading the WebApiVectorizer. */ + @Generated public static WebApiVectorizer fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { - boolean vectorizerNameFound = false; String vectorizerName = null; VectorSearchVectorizerKind kind = VectorSearchVectorizerKind.CUSTOM_WEB_API; WebApiVectorizerParameters webApiParameters = null; @@ -100,7 +107,6 @@ public static WebApiVectorizer fromJson(JsonReader jsonReader) throws IOExceptio if ("name".equals(fieldName)) { vectorizerName = reader.getString(); - vectorizerNameFound = true; } else if ("kind".equals(fieldName)) { kind = VectorSearchVectorizerKind.fromString(reader.getString()); } else if ("customWebApiParameters".equals(fieldName)) { @@ -109,14 +115,11 @@ public static WebApiVectorizer fromJson(JsonReader jsonReader) throws IOExceptio reader.skipChildren(); } } - if (vectorizerNameFound) { - WebApiVectorizer deserializedWebApiVectorizer = new WebApiVectorizer(vectorizerName); - deserializedWebApiVectorizer.kind = kind; - deserializedWebApiVectorizer.webApiParameters = webApiParameters; + WebApiVectorizer deserializedWebApiVectorizer = new WebApiVectorizer(vectorizerName); + deserializedWebApiVectorizer.kind = kind; + deserializedWebApiVectorizer.webApiParameters = webApiParameters; - return deserializedWebApiVectorizer; - } - throw new IllegalStateException("Missing required property: name"); + return deserializedWebApiVectorizer; }); } } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/WebApiVectorizerParameters.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/WebApiVectorizerParameters.java similarity index 76% rename from sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/WebApiVectorizerParameters.java rename to sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/WebApiVectorizerParameters.java index 4b30fdc37fdc..b19156b1ccbb 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/WebApiVectorizerParameters.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/WebApiVectorizerParameters.java @@ -1,12 +1,11 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) TypeSpec Code Generator. -package com.azure.search.documents.indexes.models; +package com.azure.search.documents.models; import com.azure.core.annotation.Fluent; +import com.azure.core.annotation.Generated; import com.azure.core.util.CoreUtils; import com.azure.json.JsonReader; import com.azure.json.JsonSerializable; @@ -24,42 +23,53 @@ public final class WebApiVectorizerParameters implements JsonSerializable httpHeaders; /* * The method for the HTTP request. */ + @Generated private String httpMethod; /* * The desired timeout for the request. Default is 30 seconds. */ + @Generated private Duration timeout; /* - * 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. + * 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. */ + @Generated private String authResourceId; /* - * 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. + * 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. */ + @Generated private SearchIndexerDataIdentity authIdentity; /** * Creates an instance of WebApiVectorizerParameters class. */ + @Generated public WebApiVectorizerParameters() { } @@ -68,6 +78,7 @@ public WebApiVectorizerParameters() { * * @return the url value. */ + @Generated public String getUrl() { return this.url; } @@ -78,6 +89,7 @@ public String getUrl() { * @param url the url value to set. * @return the WebApiVectorizerParameters object itself. */ + @Generated public WebApiVectorizerParameters setUrl(String url) { this.url = url; return this; @@ -88,6 +100,7 @@ public WebApiVectorizerParameters setUrl(String url) { * * @return the httpHeaders value. */ + @Generated public Map getHttpHeaders() { return this.httpHeaders; } @@ -98,6 +111,7 @@ public Map getHttpHeaders() { * @param httpHeaders the httpHeaders value to set. * @return the WebApiVectorizerParameters object itself. */ + @Generated public WebApiVectorizerParameters setHttpHeaders(Map httpHeaders) { this.httpHeaders = httpHeaders; return this; @@ -108,6 +122,7 @@ public WebApiVectorizerParameters setHttpHeaders(Map httpHeaders * * @return the httpMethod value. */ + @Generated public String getHttpMethod() { return this.httpMethod; } @@ -118,6 +133,7 @@ public String getHttpMethod() { * @param httpMethod the httpMethod value to set. * @return the WebApiVectorizerParameters object itself. */ + @Generated public WebApiVectorizerParameters setHttpMethod(String httpMethod) { this.httpMethod = httpMethod; return this; @@ -128,6 +144,7 @@ public WebApiVectorizerParameters setHttpMethod(String httpMethod) { * * @return the timeout value. */ + @Generated public Duration getTimeout() { return this.timeout; } @@ -138,6 +155,7 @@ public Duration getTimeout() { * @param timeout the timeout value to set. * @return the WebApiVectorizerParameters object itself. */ + @Generated public WebApiVectorizerParameters setTimeout(Duration timeout) { this.timeout = timeout; return this; @@ -145,29 +163,33 @@ public WebApiVectorizerParameters setTimeout(Duration timeout) { /** * Get the authResourceId property: 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. + * 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. * * @return the authResourceId value. */ + @Generated public String getAuthResourceId() { return this.authResourceId; } /** * Set the authResourceId property: 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. + * 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. * * @param authResourceId the authResourceId value to set. * @return the WebApiVectorizerParameters object itself. */ + @Generated public WebApiVectorizerParameters setAuthResourceId(String authResourceId) { this.authResourceId = authResourceId; return this; @@ -175,25 +197,29 @@ public WebApiVectorizerParameters setAuthResourceId(String authResourceId) { /** * Get the authIdentity property: 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. + * 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. * * @return the authIdentity value. */ + @Generated public SearchIndexerDataIdentity getAuthIdentity() { return this.authIdentity; } /** * Set the authIdentity property: 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. + * 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. * * @param authIdentity the authIdentity value to set. * @return the WebApiVectorizerParameters object itself. */ + @Generated public WebApiVectorizerParameters setAuthIdentity(SearchIndexerDataIdentity authIdentity) { this.authIdentity = authIdentity; return this; @@ -202,6 +228,7 @@ public WebApiVectorizerParameters setAuthIdentity(SearchIndexerDataIdentity auth /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); @@ -222,6 +249,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { * it was pointing to JSON null. * @throws IOException If an error occurs while reading the WebApiVectorizerParameters. */ + @Generated public static WebApiVectorizerParameters fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { WebApiVectorizerParameters deserializedWebApiVectorizerParameters = new WebApiVectorizerParameters(); diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/WordDelimiterTokenFilter.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/WordDelimiterTokenFilter.java similarity index 71% rename from sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/WordDelimiterTokenFilter.java rename to sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/WordDelimiterTokenFilter.java index bedeb4242f7c..b8d382b679cb 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/WordDelimiterTokenFilter.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/WordDelimiterTokenFilter.java @@ -1,100 +1,115 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. -package com.azure.search.documents.indexes.models; +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.search.documents.models; import com.azure.core.annotation.Fluent; +import com.azure.core.annotation.Generated; import com.azure.json.JsonReader; import com.azure.json.JsonToken; import com.azure.json.JsonWriter; import java.io.IOException; -import java.util.Arrays; import java.util.List; /** - * Splits words into subwords and performs optional transformations on subword groups. This token filter is implemented - * using Apache Lucene. + * Splits words into subwords and performs optional transformations on subword + * groups. This token filter is implemented using Apache Lucene. */ @Fluent public final class WordDelimiterTokenFilter extends TokenFilter { - /* - * A URI fragment specifying the type of token filter. + * The discriminator for derived types. */ + @Generated private String odataType = "#Microsoft.Azure.Search.WordDelimiterTokenFilter"; /* - * 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. + * 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. */ + @Generated private Boolean generateWordParts; /* * A value indicating whether to generate number subwords. Default is true. */ + @Generated private Boolean generateNumberParts; /* - * 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. + * 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. */ - private Boolean wordsCatenated; + @Generated + private Boolean catenateWords; /* - * 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. + * 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. */ - private Boolean numbersCatenated; + @Generated + private Boolean catenateNumbers; /* - * 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. + * 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. */ + @Generated private Boolean catenateAll; /* - * A value indicating whether to split words on caseChange. For example, if this is set to true, "AzureSearch" - * becomes "Azure" "Search". Default is true. + * A value indicating whether to split words on caseChange. For example, if this + * is set to true, "AzureSearch" becomes "Azure" "Search". Default is true. */ + @Generated private Boolean splitOnCaseChange; /* - * A value indicating whether original words will be preserved and added to the subword list. Default is false. + * A value indicating whether original words will be preserved and added to the + * subword list. Default is false. */ + @Generated private Boolean preserveOriginal; /* - * A value indicating whether to split on numbers. For example, if this is set to true, "Azure1Search" becomes - * "Azure" "1" "Search". Default is true. + * A value indicating whether to split on numbers. For example, if this is set to + * true, "Azure1Search" becomes "Azure" "1" "Search". Default is true. */ + @Generated private Boolean splitOnNumerics; /* - * A value indicating whether to remove trailing "'s" for each subword. Default is true. + * A value indicating whether to remove trailing "'s" for each subword. Default is + * true. */ + @Generated private Boolean stemEnglishPossessive; /* * A list of tokens to protect from being delimited. */ + @Generated private List protectedWords; /** * Creates an instance of WordDelimiterTokenFilter class. - * + * * @param name the name value to set. */ + @Generated public WordDelimiterTokenFilter(String name) { super(name); } /** - * Get the odataType property: A URI fragment specifying the type of token filter. - * + * Get the odataType property: The discriminator for derived types. + * * @return the odataType value. */ + @Generated @Override public String getOdataType() { return this.odataType; @@ -102,21 +117,25 @@ public String getOdataType() { /** * Get the generateWordParts property: 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. - * + * words to be generated; for example "AzureSearch" becomes "Azure" "Search". + * Default is true. + * * @return the generateWordParts value. */ - public Boolean generateWordParts() { + @Generated + public Boolean isGenerateWordParts() { return this.generateWordParts; } /** * Set the generateWordParts property: 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. - * + * words to be generated; for example "AzureSearch" becomes "Azure" "Search". + * Default is true. + * * @param generateWordParts the generateWordParts value to set. * @return the WordDelimiterTokenFilter object itself. */ + @Generated public WordDelimiterTokenFilter setGenerateWordParts(Boolean generateWordParts) { this.generateWordParts = generateWordParts; return this; @@ -124,85 +143,95 @@ public WordDelimiterTokenFilter setGenerateWordParts(Boolean generateWordParts) /** * Get the generateNumberParts property: A value indicating whether to generate number subwords. Default is true. - * + * * @return the generateNumberParts value. */ - public Boolean generateNumberParts() { + @Generated + public Boolean isGenerateNumberParts() { return this.generateNumberParts; } /** * Set the generateNumberParts property: A value indicating whether to generate number subwords. Default is true. - * + * * @param generateNumberParts the generateNumberParts value to set. * @return the WordDelimiterTokenFilter object itself. */ + @Generated public WordDelimiterTokenFilter setGenerateNumberParts(Boolean generateNumberParts) { this.generateNumberParts = generateNumberParts; return this; } /** - * Get the wordsCatenated property: 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. - * - * @return the wordsCatenated value. - */ - public Boolean areWordsCatenated() { - return this.wordsCatenated; + * Get the catenateWords property: 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. + * + * @return the catenateWords value. + */ + @Generated + public Boolean isCatenateWords() { + return this.catenateWords; } /** - * Set the wordsCatenated property: 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. - * - * @param wordsCatenated the wordsCatenated value to set. + * Set the catenateWords property: 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. + * + * @param catenateWords the catenateWords value to set. * @return the WordDelimiterTokenFilter object itself. */ - public WordDelimiterTokenFilter setWordsCatenated(Boolean wordsCatenated) { - this.wordsCatenated = wordsCatenated; + @Generated + public WordDelimiterTokenFilter setCatenateWords(Boolean catenateWords) { + this.catenateWords = catenateWords; return this; } /** - * Get the numbersCatenated property: A value indicating whether maximum runs of number parts will be catenated. For + * Get the catenateNumbers property: 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. - * - * @return the numbersCatenated value. + * + * @return the catenateNumbers value. */ - public Boolean areNumbersCatenated() { - return this.numbersCatenated; + @Generated + public Boolean isCatenateNumbers() { + return this.catenateNumbers; } /** - * Set the numbersCatenated property: A value indicating whether maximum runs of number parts will be catenated. For + * Set the catenateNumbers property: 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. - * - * @param numbersCatenated the numbersCatenated value to set. + * + * @param catenateNumbers the catenateNumbers value to set. * @return the WordDelimiterTokenFilter object itself. */ - public WordDelimiterTokenFilter setNumbersCatenated(Boolean numbersCatenated) { - this.numbersCatenated = numbersCatenated; + @Generated + public WordDelimiterTokenFilter setCatenateNumbers(Boolean catenateNumbers) { + this.catenateNumbers = catenateNumbers; return this; } /** * Get the catenateAll property: 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. - * + * * @return the catenateAll value. */ - public Boolean catenateAll() { + @Generated + public Boolean isCatenateAll() { return this.catenateAll; } /** * Set the catenateAll property: 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. - * + * * @param catenateAll the catenateAll value to set. * @return the WordDelimiterTokenFilter object itself. */ + @Generated public WordDelimiterTokenFilter setCatenateAll(Boolean catenateAll) { this.catenateAll = catenateAll; return this; @@ -211,20 +240,22 @@ public WordDelimiterTokenFilter setCatenateAll(Boolean catenateAll) { /** * Get the splitOnCaseChange property: A value indicating whether to split words on caseChange. For example, if this * is set to true, "AzureSearch" becomes "Azure" "Search". Default is true. - * + * * @return the splitOnCaseChange value. */ - public Boolean splitOnCaseChange() { + @Generated + public Boolean isSplitOnCaseChange() { return this.splitOnCaseChange; } /** * Set the splitOnCaseChange property: A value indicating whether to split words on caseChange. For example, if this * is set to true, "AzureSearch" becomes "Azure" "Search". Default is true. - * + * * @param splitOnCaseChange the splitOnCaseChange value to set. * @return the WordDelimiterTokenFilter object itself. */ + @Generated public WordDelimiterTokenFilter setSplitOnCaseChange(Boolean splitOnCaseChange) { this.splitOnCaseChange = splitOnCaseChange; return this; @@ -233,9 +264,10 @@ public WordDelimiterTokenFilter setSplitOnCaseChange(Boolean splitOnCaseChange) /** * Get the preserveOriginal property: A value indicating whether original words will be preserved and added to the * subword list. Default is false. - * + * * @return the preserveOriginal value. */ + @Generated public Boolean isPreserveOriginal() { return this.preserveOriginal; } @@ -243,10 +275,11 @@ public Boolean isPreserveOriginal() { /** * Set the preserveOriginal property: A value indicating whether original words will be preserved and added to the * subword list. Default is false. - * + * * @param preserveOriginal the preserveOriginal value to set. * @return the WordDelimiterTokenFilter object itself. */ + @Generated public WordDelimiterTokenFilter setPreserveOriginal(Boolean preserveOriginal) { this.preserveOriginal = preserveOriginal; return this; @@ -255,20 +288,22 @@ public WordDelimiterTokenFilter setPreserveOriginal(Boolean preserveOriginal) { /** * Get the splitOnNumerics property: A value indicating whether to split on numbers. For example, if this is set to * true, "Azure1Search" becomes "Azure" "1" "Search". Default is true. - * + * * @return the splitOnNumerics value. */ - public Boolean splitOnNumerics() { + @Generated + public Boolean isSplitOnNumerics() { return this.splitOnNumerics; } /** * Set the splitOnNumerics property: A value indicating whether to split on numbers. For example, if this is set to * true, "Azure1Search" becomes "Azure" "1" "Search". Default is true. - * + * * @param splitOnNumerics the splitOnNumerics value to set. * @return the WordDelimiterTokenFilter object itself. */ + @Generated public WordDelimiterTokenFilter setSplitOnNumerics(Boolean splitOnNumerics) { this.splitOnNumerics = splitOnNumerics; return this; @@ -276,21 +311,25 @@ public WordDelimiterTokenFilter setSplitOnNumerics(Boolean splitOnNumerics) { /** * Get the stemEnglishPossessive property: A value indicating whether to remove trailing "'s" for each subword. - * Default is true. - * + * Default is + * true. + * * @return the stemEnglishPossessive value. */ + @Generated public Boolean isStemEnglishPossessive() { return this.stemEnglishPossessive; } /** * Set the stemEnglishPossessive property: A value indicating whether to remove trailing "'s" for each subword. - * Default is true. - * + * Default is + * true. + * * @param stemEnglishPossessive the stemEnglishPossessive value to set. * @return the WordDelimiterTokenFilter object itself. */ + @Generated public WordDelimiterTokenFilter setStemEnglishPossessive(Boolean stemEnglishPossessive) { this.stemEnglishPossessive = stemEnglishPossessive; return this; @@ -298,19 +337,21 @@ public WordDelimiterTokenFilter setStemEnglishPossessive(Boolean stemEnglishPoss /** * Get the protectedWords property: A list of tokens to protect from being delimited. - * + * * @return the protectedWords value. */ + @Generated public List getProtectedWords() { return this.protectedWords; } /** * Set the protectedWords property: A list of tokens to protect from being delimited. - * + * * @param protectedWords the protectedWords value to set. * @return the WordDelimiterTokenFilter object itself. */ + @Generated public WordDelimiterTokenFilter setProtectedWords(List protectedWords) { this.protectedWords = protectedWords; return this; @@ -319,6 +360,7 @@ public WordDelimiterTokenFilter setProtectedWords(List protectedWords) { /** * {@inheritDoc} */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); @@ -326,8 +368,8 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStringField("@odata.type", this.odataType); jsonWriter.writeBooleanField("generateWordParts", this.generateWordParts); jsonWriter.writeBooleanField("generateNumberParts", this.generateNumberParts); - jsonWriter.writeBooleanField("catenateWords", this.wordsCatenated); - jsonWriter.writeBooleanField("catenateNumbers", this.numbersCatenated); + jsonWriter.writeBooleanField("catenateWords", this.catenateWords); + jsonWriter.writeBooleanField("catenateNumbers", this.catenateNumbers); jsonWriter.writeBooleanField("catenateAll", this.catenateAll); jsonWriter.writeBooleanField("splitOnCaseChange", this.splitOnCaseChange); jsonWriter.writeBooleanField("preserveOriginal", this.preserveOriginal); @@ -340,22 +382,22 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of WordDelimiterTokenFilter from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of WordDelimiterTokenFilter if the JsonReader was pointing to an instance of it, or null if * it was pointing to JSON null. * @throws IllegalStateException If the deserialized JSON object was missing any required properties. * @throws IOException If an error occurs while reading the WordDelimiterTokenFilter. */ + @Generated public static WordDelimiterTokenFilter fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { - boolean nameFound = false; String name = null; String odataType = "#Microsoft.Azure.Search.WordDelimiterTokenFilter"; Boolean generateWordParts = null; Boolean generateNumberParts = null; - Boolean wordsCatenated = null; - Boolean numbersCatenated = null; + Boolean catenateWords = null; + Boolean catenateNumbers = null; Boolean catenateAll = null; Boolean splitOnCaseChange = null; Boolean preserveOriginal = null; @@ -365,9 +407,9 @@ public static WordDelimiterTokenFilter fromJson(JsonReader jsonReader) throws IO while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); + if ("name".equals(fieldName)) { name = reader.getString(); - nameFound = true; } else if ("@odata.type".equals(fieldName)) { odataType = reader.getString(); } else if ("generateWordParts".equals(fieldName)) { @@ -375,9 +417,9 @@ public static WordDelimiterTokenFilter fromJson(JsonReader jsonReader) throws IO } else if ("generateNumberParts".equals(fieldName)) { generateNumberParts = reader.getNullable(JsonReader::getBoolean); } else if ("catenateWords".equals(fieldName)) { - wordsCatenated = reader.getNullable(JsonReader::getBoolean); + catenateWords = reader.getNullable(JsonReader::getBoolean); } else if ("catenateNumbers".equals(fieldName)) { - numbersCatenated = reader.getNullable(JsonReader::getBoolean); + catenateNumbers = reader.getNullable(JsonReader::getBoolean); } else if ("catenateAll".equals(fieldName)) { catenateAll = reader.getNullable(JsonReader::getBoolean); } else if ("splitOnCaseChange".equals(fieldName)) { @@ -394,33 +436,20 @@ public static WordDelimiterTokenFilter fromJson(JsonReader jsonReader) throws IO reader.skipChildren(); } } - if (nameFound) { - WordDelimiterTokenFilter deserializedWordDelimiterTokenFilter = new WordDelimiterTokenFilter(name); - deserializedWordDelimiterTokenFilter.odataType = odataType; - deserializedWordDelimiterTokenFilter.generateWordParts = generateWordParts; - deserializedWordDelimiterTokenFilter.generateNumberParts = generateNumberParts; - deserializedWordDelimiterTokenFilter.wordsCatenated = wordsCatenated; - deserializedWordDelimiterTokenFilter.numbersCatenated = numbersCatenated; - deserializedWordDelimiterTokenFilter.catenateAll = catenateAll; - deserializedWordDelimiterTokenFilter.splitOnCaseChange = splitOnCaseChange; - deserializedWordDelimiterTokenFilter.preserveOriginal = preserveOriginal; - deserializedWordDelimiterTokenFilter.splitOnNumerics = splitOnNumerics; - deserializedWordDelimiterTokenFilter.stemEnglishPossessive = stemEnglishPossessive; - deserializedWordDelimiterTokenFilter.protectedWords = protectedWords; - return deserializedWordDelimiterTokenFilter; - } - throw new IllegalStateException("Missing required property: name"); + WordDelimiterTokenFilter deserializedWordDelimiterTokenFilter = new WordDelimiterTokenFilter(name); + deserializedWordDelimiterTokenFilter.odataType = odataType; + deserializedWordDelimiterTokenFilter.generateWordParts = generateWordParts; + deserializedWordDelimiterTokenFilter.generateNumberParts = generateNumberParts; + deserializedWordDelimiterTokenFilter.catenateWords = catenateWords; + deserializedWordDelimiterTokenFilter.catenateNumbers = catenateNumbers; + deserializedWordDelimiterTokenFilter.catenateAll = catenateAll; + deserializedWordDelimiterTokenFilter.splitOnCaseChange = splitOnCaseChange; + deserializedWordDelimiterTokenFilter.preserveOriginal = preserveOriginal; + deserializedWordDelimiterTokenFilter.splitOnNumerics = splitOnNumerics; + deserializedWordDelimiterTokenFilter.stemEnglishPossessive = stemEnglishPossessive; + deserializedWordDelimiterTokenFilter.protectedWords = protectedWords; + + return deserializedWordDelimiterTokenFilter; }); } - - /** - * Set the protectedWords property: A list of tokens to protect from being delimited. - * - * @param protectedWords the protectedWords value to set. - * @return the WordDelimiterTokenFilter object itself. - */ - public WordDelimiterTokenFilter setProtectedWords(String... protectedWords) { - this.protectedWords = (protectedWords == null) ? null : Arrays.asList(protectedWords); - return this; - } } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/package-info.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/package-info.java index 470911af53b9..34541bb52276 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/package-info.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/package-info.java @@ -1,11 +1,10 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. +// Code generated by Microsoft (R) TypeSpec Code Generator. /** - * Package containing the data models for SearchIndexClient. - * Client that can be used to query an index and upload, merge, or delete documents. + * Package containing the data models for Search. + * Client that can be used to manage and query indexes and documents, as well as + * manage other resources, on a search service. */ package com.azure.search.documents.models; diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/options/OnActionAddedOptions.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/options/OnActionAddedOptions.java deleted file mode 100644 index 4857b7fabaaf..000000000000 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/options/OnActionAddedOptions.java +++ /dev/null @@ -1,37 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.search.documents.options; - -import com.azure.search.documents.SearchClientBuilder; -import com.azure.search.documents.models.IndexAction; - -import java.util.function.Consumer; - -/** - * Options passed when {@link SearchClientBuilder.SearchIndexingBufferedSenderBuilder#onActionAdded(Consumer)} is - * called. - * - * @param Type of the document in the action. - */ -public final class OnActionAddedOptions { - private final IndexAction action; - - /** - * Creates a new OnActionAddedOptions object. - * - * @param action Action being added. - */ - public OnActionAddedOptions(IndexAction action) { - this.action = action; - } - - /** - * Gets the action. - * - * @return The action. - */ - public IndexAction getAction() { - return action; - } -} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/options/OnActionErrorOptions.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/options/OnActionErrorOptions.java deleted file mode 100644 index 07432de04725..000000000000 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/options/OnActionErrorOptions.java +++ /dev/null @@ -1,81 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.search.documents.options; - -import com.azure.search.documents.SearchClientBuilder; -import com.azure.search.documents.models.IndexAction; -import com.azure.search.documents.models.IndexingResult; - -import java.util.function.Consumer; - -/** - * Options passed when {@link SearchClientBuilder.SearchIndexingBufferedSenderBuilder#onActionError(Consumer)} is - * called. - * - * @param Type of the document in the action. - */ -public final class OnActionErrorOptions { - private final IndexAction action; - - private Throwable throwable; - private IndexingResult indexingResult; - - /** - * Creates a new OnActionErrorOptions object. - * - * @param action Action that failed with an error. - */ - public OnActionErrorOptions(IndexAction action) { - this.action = action; - } - - /** - * Gets the action. - * - * @return The action. - */ - public IndexAction getAction() { - return action; - } - - /** - * Sets the throwable that caused the action failed. - * - * @param throwable Throwable that caused the action to fail. - * @return The updated OnActionErrorOptions object. - */ - public OnActionErrorOptions setThrowable(Throwable throwable) { - this.throwable = throwable; - return this; - } - - /** - * Gets the throwable that caused the action to fail. - * - * @return The throwable that caused the action to fail. - */ - public Throwable getThrowable() { - return throwable; - } - - /** - * Sets the indexing result of the action with a non-retryable status code. - * - * @param indexingResult The indexing result for the action. - * @return The updated OnActionErrorOptions object. - */ - public OnActionErrorOptions setIndexingResult(IndexingResult indexingResult) { - this.indexingResult = indexingResult; - return this; - } - - /** - * Gets the indexing result of the action. - * - * @return The indexing result of the action. - */ - public IndexingResult getIndexingResult() { - return indexingResult; - } -} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/options/OnActionSentOptions.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/options/OnActionSentOptions.java deleted file mode 100644 index 2049dc3353f9..000000000000 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/options/OnActionSentOptions.java +++ /dev/null @@ -1,36 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.search.documents.options; - -import com.azure.search.documents.SearchClientBuilder; -import com.azure.search.documents.models.IndexAction; - -import java.util.function.Consumer; - -/** - * Options passed when {@link SearchClientBuilder.SearchIndexingBufferedSenderBuilder#onActionSent(Consumer)} is called. - * - * @param Type of the document in the action. - */ -public final class OnActionSentOptions { - private final IndexAction indexAction; - - /** - * Creates a new OnActionSentOptions object. - * - * @param indexAction Action that was sent. - */ - public OnActionSentOptions(IndexAction indexAction) { - this.indexAction = indexAction; - } - - /** - * Gets the action. - * - * @return The action. - */ - public IndexAction getIndexAction() { - return indexAction; - } -} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/options/OnActionSucceededOptions.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/options/OnActionSucceededOptions.java deleted file mode 100644 index 84099d43751a..000000000000 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/options/OnActionSucceededOptions.java +++ /dev/null @@ -1,37 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.search.documents.options; - -import com.azure.search.documents.SearchClientBuilder; -import com.azure.search.documents.models.IndexAction; - -import java.util.function.Consumer; - -/** - * Options passed when {@link SearchClientBuilder.SearchIndexingBufferedSenderBuilder#onActionSucceeded(Consumer)} is - * called. - * - * @param Type of the document in the action. - */ -public final class OnActionSucceededOptions { - private final IndexAction indexAction; - - /** - * Creates a new OnActionSucceededOptions object. - * - * @param indexAction The action that successfully completed indexing. - */ - public OnActionSucceededOptions(IndexAction indexAction) { - this.indexAction = indexAction; - } - - /** - * Gets the action. - * - * @return The action. - */ - public IndexAction getIndexAction() { - return indexAction; - } -} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/options/package-info.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/options/package-info.java deleted file mode 100644 index e8b912eff905..000000000000 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/options/package-info.java +++ /dev/null @@ -1,7 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -/** - * Package containing options model classes used by Azure Search Documents. - */ -package com.azure.search.documents.options; diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/package-info.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/package-info.java index 18f18d3ead34..660f710ade84 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/package-info.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/package-info.java @@ -1,470 +1,10 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. /** - *

Azure AI Search, formerly known as "Azure AI Search", provides secure information retrieval at scale over - * user-owned content in traditional and conversational search applications.

- * - *

The Azure AI Search service provides:/p> - * - *

    - *
  • A search engine for vector search, full text, and hybrid search over a search index.
  • - *
  • Rich indexing with integrated data chunking and vectorization (preview), lexical analysis for text, and - * optional AI enrichment for content extraction and transformation.
  • - *
  • Rich query syntax for vector queries, text search, hybrid queries, fuzzy search, autocomplete, geo-search and others.
  • - *
  • Azure scale, security, and reach.
  • - *
  • Azure integration at the data layer, machine learning layer, Azure AI services and Azure OpenAI
  • - *
- * - *

The Azure AI Search service is well suited for the following application scenarios:

- * - *
    - *
  • Consolidate varied content types into a single searchable index. To populate an index, you can push JSON - * documents that contain your content, or if your data is already in Azure, create an indexer to pull in data - * automatically.
  • - *
  • Attach skillsets to an indexer to create searchable content from images and large text documents. A skillset - * leverages AI from Cognitive Services for built-in OCR, entity recognition, key phrase extraction, language - * detection, text translation, and sentiment analysis. You can also add custom skills to integrate external - * processing of your content during data ingestion.
  • - *
  • In a search client application, implement query logic and user experiences similar to commercial web search engines.
  • - *
- * - *

This is the Java client library for Azure AI Search. Azure AI Search service is a search-as-a-service - * cloud solution that gives developers APIs and tools for adding a rich search experience over private, heterogeneous - * content in web, mobile, and enterprise applications.

- * - *

The Azure Search Documents client library allows for Java developers to easily interact with the Azure AI Search - * service from their Java applications. This library provides a set of APIs that abstract the low-level details of working - * with the Azure AI Search service and allows developers to perform common operations such as:

- * - *
    - *
  • Submit queries for simple and advanced query forms that include fuzzy search, wildcard search, regular expressions..
  • - *
  • Implement filtered queries for faceted navigation, geospatial search, or to narrow results based on filter criteria.
  • - *
  • Create and manage search indexes.
  • - *
  • Upload and update documents in the search index.
  • - *
  • Create and manage indexers that pull data from Azure into an index.
  • - *
  • Create and manage skillsets that add AI enrichment to data ingestion.
  • - *
  • Create and manage analyzers for advanced text analysis or multi-lingual content.
  • - *
  • Optimize results through scoring profiles to factor in business logic or freshness.
  • - *
- * - *

Getting Started

- * - *

Prerequisites

- * - *

The client library package requires the following:

- * - * - * - *

To create a new Search service, you can use the - * Azure portal, - * Azure Powershell, - * or the Azure CLI.

- * - * - *

Authenticate the client

- * - *

To interact with the Search service, you'll need to create an instance of the appropriate client class: - * SearchClient for searching indexed documents, SearchIndexClient for managing indexes, or SearchIndexerClient for - * crawling data sources and loading search documents into an index. To instantiate a client object, you'll need an - * endpoint and API key. You can refer to the documentation for more information on - * supported authenticating approaches - * with the Search service.

- * - *

Get an API Key

- * - *

You can get the endpoint and an API key from the Search service in the Azure Portal. - * Please refer the - * documentation for instructions on how to get an API key.

- * - *

The SDK provides three clients.

- * - *
    - *
  • SearchIndexClient for CRUD operations on indexes and synonym maps.
  • - *
  • SearchIndexerClient for CRUD operations on indexers, data sources, and skillsets.
  • - *
  • SearchClient for all document operations.
  • - *
- * - *

Create a SearchIndexClient

- * - *

To create a SearchIndexClient, you will need the values of the Azure AI Search service URL endpoint and - * admin key. The following snippet shows how to create a SearchIndexClient.

- * - * The following sample creates a SearchIndexClient using the endpoint and Azure Key Credential (API Key). - * - * - *
- * SearchIndexClient searchIndexClient = new SearchIndexClientBuilder()
- *     .endpoint("{endpoint}")
- *     .credential(new AzureKeyCredential("{key}"))
- *     .buildClient();
- * 
- * - * - *

Create a SearchIndexerClient

- * - *

To create a SearchIndexerClient, you will need the values of the Azure AI Search - * service URL endpoint and admin key. The following snippet shows how to create a SearchIndexerClient.

- * - *

The following sample creates SearchIndexerClient using an endpoint and Azure Key Credential (API Key).

- * - * - *
- * SearchIndexerClient searchIndexerClient = new SearchIndexerClientBuilder()
- *     .endpoint("{endpoint}")
- *     .credential(new AzureKeyCredential("{key}"))
- *     .buildClient();
- * 
- * - * - * - *

Create a SearchClient

- * - *

To create a SearchClient, you will need the values of the Azure AI Search - * service URL endpoint, admin key, and an index name. The following snippet shows how to create a SearchIndexerClient.

- * - *

The following sample creates a SearchClient

- * - * - *
- * SearchClient searchClient = new SearchClientBuilder()
- *     .endpoint("{endpoint}")
- *     .credential(new AzureKeyCredential("{key}"))
- *     .indexName("{indexName}")
- *     .buildClient();
- * 
- * - * - *

Key Concepts

- * - *

An Azure AI Search service contains one or more indexes that provide persistent storage of searchable data - * in the form of JSON documents. (If you're new to search, you can make a very rough analogy between indexes and - * database tables.) The azure-search-documents client library exposes operations on these resources through two main - * client types.

- * - *

SearchClient helps with:

- * - *

SearchIndexClient allows you to:

- *
    - *
  • Create, delete, update, or configure a search index
  • - *
  • Declare custom synonym maps to expand or rewrite queries
  • - *
  • Most of the SearchServiceClient functionality is not yet available in our current preview
  • - *
- *

SearchIndexerClient allows you to:

- *
    - *
  • Start indexers to automatically crawl data sources
  • - *
  • Define AI powered Skillsets to transform and enrich your data
  • - *
- * - *

Azure AI Search provides two powerful features:

- * - *

Semantic Search

- * - *

Semantic search enhances the quality of search results for text-based queries. By enabling Semantic Search on - * your search service, you can improve the relevance of search results in two ways:

- * - *
    - *
  • It applies secondary ranking to the initial result set, promoting the most semantically relevant results to the top.
  • - *
  • It extracts and returns captions and answers in the response, which can be displayed on a search page to enhance the user's search experience.
  • - *
- * - *

To learn more about Semantic Search, you can refer to the documentation.

- * - *

Vector Search

- * - *

Vector Search is an information retrieval technique that overcomes the limitations of traditional keyword-based - * search. Instead of relying solely on lexical analysis and matching individual query terms, Vector Search utilizes - * machine learning models to capture the contextual meaning of words and phrases. It represents documents and queries - * as vectors in a high-dimensional space called an embedding. By understanding the intent behind the query, - * Vector Search can deliver more relevant results that align with the user's requirements, even if the exact terms are - * not present in the document. Moreover, Vector Search can be applied to various types of content, including images - * and videos, not just text.

- * - *

To learn how to index vector fields and perform vector search, you can refer to the sample. - * This sample provides detailed guidance on indexing vector fields and demonstrates how to perform vector search.

- * - *

Additionally, for more comprehensive information about Vector Search, including its concepts and usage, you can - * refer to the documentation. The documentation provides in-depth explanations and guidance on leveraging the power of - * Vector Search in Azure AI Search.

- * - *

Examples

- * - *

The following examples all use a sample Hotel data set that you can import into your own index from the Azure - * portal. These are just a few of the basics - please check out our Samples for much more.

- * - *

Querying

- * - *

There are two ways to interact with the data returned from a search query.

- * - *
Use SearchDocument like a dictionary for search results
- * - *

SearchDocument is the default type returned from queries when you don't provide your own. The following sample performs the - * search, enumerates over the results, and extracts data using SearchDocument's dictionary indexer.

- * - * - *
- * for (SearchResult result : searchClient.search("luxury")) {
- *     SearchDocument document = result.getDocument(SearchDocument.class);
- *     System.out.printf("Hotel ID: %s%n", document.get("hotelId"));
- *     System.out.printf("Hotel Name: %s%n", document.get("hotelName"));
- * }
- * 
- * - * - *
Use Java model class for search results
- * - *

Define a `Hotel` class.

- * - * - *
- * public static class Hotel {
- *     private String hotelId;
- *     private String hotelName;
- *
- *     @SimpleField(isKey = true)
- *     public String getHotelId() {
- *         return this.hotelId;
- *     }
- *
- *     public String getHotelName() {
- *         return this.hotelName;
- *     }
- *
- *     public Hotel setHotelId(String number) {
- *         this.hotelId = number;
- *         return this;
- *     }
- *
- *     public Hotel setHotelName(String secretPointMotel) {
- *         this.hotelName = secretPointMotel;
- *         return this;
- *     }
- * }
- * 
- * - * - *

Use it in place of SearchDocument when querying.

- * - * - *
- * for (SearchResult result : searchClient.search("luxury")) {
- *     Hotel hotel = result.getDocument(Hotel.class);
- *     System.out.printf("Hotel ID: %s%n", hotel.getHotelId());
- *     System.out.printf("Hotel Name: %s%n", hotel.getHotelName());
- * }
- * 
- * - * - *
Search Options
- * - *

The SearchOptions provide powerful control over the behavior of our queries.

- * - *

The following sample uses SearchOptions to search for the top 5 luxury hotel with a good rating (4 or above).

- * - * - *
- * SearchOptions options = new SearchOptions()
- *     .setFilter("rating gt 4")
- *     .setOrderBy("rating desc")
- *     .setTop(5);
- * SearchPagedIterable searchResultsIterable = searchClient.search("luxury", options, Context.NONE);
- * searchResultsIterable.forEach(result -> {
- *     System.out.printf("Hotel ID: %s%n", result.getDocument(Hotel.class).getHotelId());
- *     System.out.printf("Hotel Name: %s%n", result.getDocument(Hotel.class).getHotelName());
- * });
- * 
- * - * - *

Creating an index

- * - *

You can use the SearchIndexClient to create a search index. Indexes can also define suggesters, lexical analyzers, - * and more.

- * - *

There are multiple ways of preparing search fields for a search index. For basic needs, there is a static helper - * method buildSearchFields in SearchIndexClient and SearchIndexAsyncClient. There are three annotations - * SimpleFieldProperty, SearchFieldProperty and FieldBuilderIgnore to configure the field of model class.

- * - * - *
- * // Create a new search index structure that matches the properties of the Hotel class.
- * List<SearchField> searchFields = SearchIndexClient.buildSearchFields(Hotel.class, null);
- * searchIndexClient.createIndex(new SearchIndex("hotels", searchFields));
- * 
- * - * - *

For advanced scenarios, you can build search fields using SearchField directly. The following sample shows how to - * build search fields with SearchField.

- * - * - *
- * // Create a new search index structure that matches the properties of the Hotel class.
- * List<SearchField> searchFieldList = new ArrayList<>();
- * searchFieldList.add(new SearchField("hotelId", SearchFieldDataType.STRING)
- *         .setKey(true)
- *         .setFilterable(true)
- *         .setSortable(true));
- *
- * searchFieldList.add(new SearchField("hotelName", SearchFieldDataType.STRING)
- *         .setSearchable(true)
- *         .setFilterable(true)
- *         .setSortable(true));
- * searchFieldList.add(new SearchField("description", SearchFieldDataType.STRING)
- *     .setSearchable(true)
- *     .setAnalyzerName(LexicalAnalyzerName.EU_LUCENE));
- * searchFieldList.add(new SearchField("tags", SearchFieldDataType.collection(SearchFieldDataType.STRING))
- *     .setSearchable(true)
- *     .setFilterable(true)
- *     .setFacetable(true));
- * searchFieldList.add(new SearchField("address", SearchFieldDataType.COMPLEX)
- *     .setFields(new SearchField("streetAddress", SearchFieldDataType.STRING).setSearchable(true),
- *         new SearchField("city", SearchFieldDataType.STRING)
- *             .setSearchable(true)
- *             .setFilterable(true)
- *             .setFacetable(true)
- *             .setSortable(true),
- *         new SearchField("stateProvince", SearchFieldDataType.STRING)
- *             .setSearchable(true)
- *             .setFilterable(true)
- *             .setFacetable(true)
- *             .setSortable(true),
- *         new SearchField("country", SearchFieldDataType.STRING)
- *             .setSearchable(true)
- *             .setFilterable(true)
- *             .setFacetable(true)
- *             .setSortable(true),
- *         new SearchField("postalCode", SearchFieldDataType.STRING)
- *             .setSearchable(true)
- *             .setFilterable(true)
- *             .setFacetable(true)
- *             .setSortable(true)
- *     ));
- *
- * // Prepare suggester.
- * SearchSuggester suggester = new SearchSuggester("sg", Collections.singletonList("hotelName"));
- * // Prepare SearchIndex with index name and search fields.
- * SearchIndex index = new SearchIndex("hotels").setFields(searchFieldList).setSuggesters(suggester);
- * // Create an index
- * searchIndexClient.createIndex(index);
- * 
- * - * - *

Retrieving a specific document from your index

- * - *

In addition to querying for documents using keywords and optional filters, you can retrieve a specific document from your index if you already know the key.

- * - *

The following example retrieves a document using the document's key.

- * - * - *
- * Hotel hotel = searchClient.getDocument("1", Hotel.class);
- * System.out.printf("Hotel ID: %s%n", hotel.getHotelId());
- * System.out.printf("Hotel Name: %s%n", hotel.getHotelName());
- * 
- * - * - *

Adding documents to your index

- * - *

You can Upload, Merge, MergeOrUpload, and Delete multiple documents from an index in a single batched request. - * There are a few special rules for merging to be aware of.

- * - *

The following sample shows using a single batch request to perform a document upload and merge in a single request.

- * - * - *
- * IndexDocumentsBatch<Hotel> batch = new IndexDocumentsBatch<Hotel>();
- * batch.addUploadActions(Collections.singletonList(
- *         new Hotel().setHotelId("783").setHotelName("Upload Inn")));
- * batch.addMergeActions(Collections.singletonList(
- *         new Hotel().setHotelId("12").setHotelName("Renovated Ranch")));
- * searchClient.indexDocuments(batch);
- * 
- * - * - *

Async APIs

- * - *

The examples so far have been using synchronous APIs. For asynchronous support and examples, please see our asynchronous clients:

- * - *
    - *
  • SearchIndexAsyncClient
  • - *
  • SearchIndexerAsyncClient
  • - *
  • SearchAsyncClient
  • - *
- * - *

Authenticate in a National Cloud

- * - *

To authenticate a National Cloud, you will need to make the following additions to your client configuration:

- * - *
    - *
  • Set `AuthorityHost` in the credential potions or via the `AZURE_AUTHORITY_HOST` environment variable
  • - *
  • Set the `audience` in SearchClientBuilder, SearchIndexClientBuilder, SearchIndexerClientBuilder
  • - *
- * - * - *
- * SearchClient searchClient = new SearchClientBuilder()
- *     .endpoint("{endpoint}")
- *     .credential(new DefaultAzureCredentialBuilder()
- *         .authorityHost("{national cloud endpoint}")
- *         .build())
- *     .audience(SearchAudience.AZURE_PUBLIC_CLOUD) //set the audience of your cloud
- *     .buildClient();
- * 
- * - * - *

Troubleshooting

- * - *

See our troubleshooting guide for details on how to diagnose various failure scenarios.

- * - *

General

- * - *

When you interact with Azure AI Search using this Java client library, errors returned by the service - * correspond to the same HTTP status codes returned for REST API requests. For example, the service will return a 404 - * error if you try to retrieve a document that doesn't exist in your index.

- * - *

Handling Search Error Response

- * - *

Any Search API operation that fails will throw an HttpResponseException with helpful Status codes. Many of these errors are recoverable.

- * - * - *
- * try {
- *     Iterable<SearchResult> results = searchClient.search("hotel");
- *     results.forEach(result -> {
- *         System.out.println(result.getDocument(Hotel.class).getHotelName());
- *     });
- * } catch (HttpResponseException ex) {
- *     // The exception contains the HTTP status code and the detailed message
- *     // returned from the search service
- *     HttpResponse response = ex.getResponse();
- *     System.out.println("Status Code: " + response.getStatusCode());
- *     System.out.println("Message: " + ex.getMessage());
- * }
- * 
- * - * - * - * @see com.azure.search.documents.SearchClient - * @see com.azure.search.documents.SearchAsyncClient - * @see com.azure.search.documents.SearchClientBuilder - * @see com.azure.search.documents.indexes.SearchIndexClient - * @see com.azure.search.documents.indexes.SearchIndexAsyncClient - * @see com.azure.search.documents.indexes.SearchIndexClientBuilder - * @see com.azure.search.documents.indexes.SearchIndexerClient - * @see com.azure.search.documents.indexes.SearchIndexerAsyncClient - * @see com.azure.search.documents.indexes.SearchIndexerClientBuilder - * @see com.azure.search.documents.models.SearchOptions - * @see com.azure.search.documents.indexes.models.SearchField - * + * Package containing the classes for Search. + * Client that can be used to manage and query indexes and documents, as well as + * manage other resources, on a search service. */ package com.azure.search.documents; diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/util/AutocompletePagedFlux.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/util/AutocompletePagedFlux.java deleted file mode 100644 index ebe3559570a1..000000000000 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/util/AutocompletePagedFlux.java +++ /dev/null @@ -1,25 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.search.documents.util; - -import com.azure.core.http.rest.PagedFluxBase; -import com.azure.search.documents.models.AutocompleteItem; -import reactor.core.publisher.Mono; - -import java.util.function.Supplier; - -/** - * Implementation of {@link PagedFluxBase} where the element type is {@link AutocompleteItem} and the page type is - * {@link AutocompletePagedResponse}. - */ -public final class AutocompletePagedFlux extends PagedFluxBase { - /** - * Creates an instance of {@link AutocompletePagedFlux} that retrieves a single page. - * - * @param firstPageRetriever Supplier that handles retrieving the first page. - */ - public AutocompletePagedFlux(Supplier> firstPageRetriever) { - super(firstPageRetriever); - } -} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/util/AutocompletePagedIterable.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/util/AutocompletePagedIterable.java deleted file mode 100644 index 141b78e873e9..000000000000 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/util/AutocompletePagedIterable.java +++ /dev/null @@ -1,50 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.search.documents.util; - -import com.azure.core.http.rest.PagedIterableBase; -import com.azure.search.documents.models.AutocompleteItem; - -import java.util.function.Function; -import java.util.function.Supplier; - -/** - * Implementation of {@link PagedIterableBase} where the element type is {@link AutocompleteItem} and the page type is - * {@link AutocompletePagedResponse}. - */ -public final class AutocompletePagedIterable extends PagedIterableBase { - /** - * Creates instance given {@link AutocompletePagedIterable}. - * - * @param pagedFluxBase The {@link AutocompletePagedFlux} that will be consumed as an iterable. - */ - public AutocompletePagedIterable(AutocompletePagedFlux pagedFluxBase) { - super(pagedFluxBase); - } - - /** - * Creates an instance of {@link AutocompletePagedIterable}. The constructor takes a {@code Supplier} and {@code Function}. The - * {@code Supplier} returns the first page of {@code AutocompletePagedResponse}. - * - * @param firstPageRetriever Supplier that retrieves the first page - */ - public AutocompletePagedIterable(Supplier firstPageRetriever) { - this(firstPageRetriever, null); - } - - /** - * Creates an instance of {@link AutocompletePagedIterable}. The constructor takes a {@code Supplier} and {@code Function}. The - * {@code Supplier} returns the first page of {@code AutocompletePagedResponse}, the {@code Function} retrieves subsequent pages of {@code - * AutocompletePagedResponse}. - * - * @param firstPageRetriever Supplier that retrieves the first page - * @param nextPageRetriever Function that retrieves the next page given a continuation token - */ - public AutocompletePagedIterable(Supplier firstPageRetriever, - Function nextPageRetriever) { - super(() -> (continuationToken, pageSize) -> continuationToken == null - ? firstPageRetriever.get() - : nextPageRetriever.apply(continuationToken)); - } -} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/util/AutocompletePagedResponse.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/util/AutocompletePagedResponse.java deleted file mode 100644 index 9de8193dd9c8..000000000000 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/util/AutocompletePagedResponse.java +++ /dev/null @@ -1,44 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.search.documents.util; - -import com.azure.core.annotation.Immutable; -import com.azure.core.http.rest.PagedResponseBase; -import com.azure.core.http.rest.Response; -import com.azure.core.http.rest.SimpleResponse; -import com.azure.search.documents.models.AutocompleteItem; -import com.azure.search.documents.models.AutocompleteResult; - -/** - * This class represents a response from the autocomplete API. It contains the {@link AutocompleteItem - * AutocompleteItems} returned from the service. - */ -@Immutable -public final class AutocompletePagedResponse extends PagedResponseBase { - private final Double coverage; - - /** - * Creates an {@link AutocompletePagedResponse} from the returned {@link Response}. - * - * @param autocompleteResponse Autocomplete response returned from the service. - */ - public AutocompletePagedResponse(SimpleResponse autocompleteResponse) { - super(autocompleteResponse.getRequest(), autocompleteResponse.getStatusCode(), - autocompleteResponse.getHeaders(), autocompleteResponse.getValue().getResults(), null, null); - - this.coverage = autocompleteResponse.getValue().getCoverage(); - } - - /** - * The percentage of the index covered in the autocomplete request. - *

- * If {@code minimumCoverage} wasn't supplied in the request this will be {@code null}. - * - * @return The percentage of the index covered in the suggest request if {@code minimumCoverage} was set in the - * request, otherwise {@code null}. - */ - public Double getCoverage() { - return coverage; - } -} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/util/SearchPagedFlux.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/util/SearchPagedFlux.java deleted file mode 100644 index d6e7964c1a3a..000000000000 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/util/SearchPagedFlux.java +++ /dev/null @@ -1,130 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.search.documents.util; - -import com.azure.core.http.rest.PagedFluxBase; -import com.azure.core.util.paging.ContinuablePagedFlux; -import com.azure.search.documents.implementation.models.SearchFirstPageResponseWrapper; -import com.azure.search.documents.implementation.models.SearchRequest; -import com.azure.search.documents.implementation.util.SemanticSearchResultsAccessHelper; -import com.azure.search.documents.models.DebugInfo; -import com.azure.search.documents.models.FacetResult; -import com.azure.search.documents.models.SearchResult; -import com.azure.search.documents.models.SemanticSearchResults; -import reactor.core.publisher.Mono; - -import java.util.List; -import java.util.Map; -import java.util.function.Function; -import java.util.function.Supplier; - -/** - * Implementation of {@link ContinuablePagedFlux} where the continuation token type is {@link SearchRequest}, the - * element type is {@link SearchResult}, and the page type is {@link SearchPagedResponse}. - */ -public final class SearchPagedFlux extends PagedFluxBase { - private final Supplier> metadataSupplier; - - /** - * Creates an instance of {@link SearchPagedFlux}. - * - * @param firstPageRetriever Supplied that handles retrieving {@link SearchPagedResponse SearchPagedResponses}. - */ - public SearchPagedFlux(Supplier> firstPageRetriever) { - super(firstPageRetriever); - metadataSupplier = () -> firstPageRetriever.get() - .map(response -> new SearchFirstPageResponseWrapper().setFirstPageResponse(response)); - } - - /** - * Creates an instance of {@link SearchPagedFlux}. - * - * @param firstPageRetriever Supplied that handles retrieving {@link SearchPagedResponse SearchPagedResponses}. - * @param nextPageRetriever Function that retrieves the next {@link SearchPagedResponse SearchPagedResponses} given - * a continuation token. - */ - public SearchPagedFlux(Supplier> firstPageRetriever, - Function> nextPageRetriever) { - super(firstPageRetriever, nextPageRetriever); - metadataSupplier = () -> firstPageRetriever.get() - .map(response -> new SearchFirstPageResponseWrapper().setFirstPageResponse(response)); - } - - /** - * The approximate number of documents that matched the search and filter parameters in the request. - *

- * If {@code count} is set to {@code false} in the request this will be {@code null}. - * - * @return The approximate number of documents that match the request if {@code count} is {@code true}, otherwise - * {@code null}. - */ - public Mono getTotalCount() { - return metadataSupplier.get().flatMap(metaData -> { - if (metaData.getFirstPageResponse().getCount() == null) { - return Mono.empty(); - } - return Mono.just(metaData.getFirstPageResponse().getCount()); - }); - } - - /** - * The percentage of the index covered in the search request. - *

- * If {@code minimumCoverage} wasn't supplied in the request this will be {@code null}. - * - * @return The percentage of the index covered in the search request if {@code minimumCoverage} was set in the - * request, otherwise {@code null}. - */ - public Mono getCoverage() { - return metadataSupplier.get().flatMap(metaData -> { - if (metaData.getFirstPageResponse().getCoverage() == null) { - return Mono.empty(); - } - return Mono.just(metaData.getFirstPageResponse().getCoverage()); - }); - } - - /** - * The facet query results based on the search request. - *

- * If {@code facets} weren't supplied in the request this will be {@code null}. - * - * @return The facet query results if {@code facets} were supplied in the request, otherwise {@code null}. - */ - public Mono>> getFacets() { - return metadataSupplier.get().flatMap(metaData -> { - if (metaData.getFirstPageResponse().getFacets() == null) { - return Mono.empty(); - } - return Mono.just(metaData.getFirstPageResponse().getFacets()); - }); - } - - /** - * The semantic search results based on the search request. - *

- * If semantic search wasn't requested this will return a {@link SemanticSearchResults} with no values. - * - * @return The semantic search results if semantic search was requested, otherwise an empty - * {@link SemanticSearchResults}. - */ - public Mono getSemanticResults() { - return metadataSupplier.get() - .map(metadata -> SemanticSearchResultsAccessHelper.create(metadata.getFirstPageResponse())); - } - - /** - * The debug information that can be used to further explore your search results. - * - * @return The debug information that can be used to further explore your search results. - */ - public Mono getDebugInfo() { - return metadataSupplier.get().flatMap(metaData -> { - if (metaData.getFirstPageResponse().getDebugInfo() == null) { - return Mono.empty(); - } - return Mono.just(metaData.getFirstPageResponse().getDebugInfo()); - }); - } -} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/util/SearchPagedIterable.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/util/SearchPagedIterable.java deleted file mode 100644 index e94b97d60374..000000000000 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/util/SearchPagedIterable.java +++ /dev/null @@ -1,147 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.search.documents.util; - -import com.azure.core.http.rest.PagedIterableBase; -import com.azure.core.util.paging.ContinuablePagedIterable; -import com.azure.core.util.paging.PageRetrieverSync; -import com.azure.search.documents.implementation.models.SearchFirstPageResponseWrapper; -import com.azure.search.documents.implementation.models.SearchRequest; -import com.azure.search.documents.implementation.util.SemanticSearchResultsAccessHelper; -import com.azure.search.documents.models.DebugInfo; -import com.azure.search.documents.models.FacetResult; -import com.azure.search.documents.models.SearchResult; -import com.azure.search.documents.models.SemanticSearchResults; - -import java.util.List; -import java.util.Map; -import java.util.function.Function; -import java.util.function.Supplier; - -/** - * Implementation of {@link ContinuablePagedIterable} where the continuation token type is {@link SearchRequest}, the - * element type is {@link SearchResult}, and the page type is {@link SearchPagedResponse}. - */ -public final class SearchPagedIterable extends PagedIterableBase { - private final SearchPagedFlux pagedFlux; - private final Supplier metadataSupplier; - - /** - * Creates an instance of {@link SearchPagedIterable}. - * - * @param pagedFlux The {@link SearchPagedFlux} that will be consumed as an iterable. - */ - public SearchPagedIterable(SearchPagedFlux pagedFlux) { - super(pagedFlux); - this.pagedFlux = pagedFlux; - this.metadataSupplier = null; - } - - /** - * Creates an instance of {@link SearchPagedIterable}. The constructor takes a {@code Supplier}. The - * {@code Supplier} returns the first page of {@code SearchPagedResponse}. - * - * @param firstPageRetriever Supplier that retrieves the first page - */ - public SearchPagedIterable(Supplier firstPageRetriever) { - this(firstPageRetriever, null); - } - - /** - * Creates an instance of {@link SearchPagedIterable}. The constructor takes a {@code Supplier} and {@code Function}. The - * {@code Supplier} returns the first page of {@code SearchPagedResponse}, the {@code Function} retrieves subsequent pages of {@code - * SearchPagedResponse}. - * - * @param firstPageRetriever Supplier that retrieves the first page - * @param nextPageRetriever Function that retrieves the next page given a continuation token - */ - public SearchPagedIterable(Supplier firstPageRetriever, - Function nextPageRetriever) { - this(() -> (continuationToken, pageSize) -> continuationToken == null - ? firstPageRetriever.get() - : nextPageRetriever.apply(continuationToken), true, () -> { - SearchPagedResponse response = firstPageRetriever.get(); - return new SearchFirstPageResponseWrapper().setFirstPageResponse(response); - }); - } - - /** - * Create SearchPagedIterable backed by Page Retriever Function Supplier. - * - * @param provider the Page Retrieval Provider - * @param ignored param is ignored, exists in signature only to avoid conflict with first ctr - */ - private SearchPagedIterable(Supplier> provider, boolean ignored, - Supplier metadataSupplier) { - super(provider); - this.pagedFlux = null; - this.metadataSupplier = metadataSupplier; - } - - /** - * The percentage of the index covered in the search request. - *

- * If {@code minimumCoverage} wasn't supplied in the request this will be {@code null}. - * - * @return The percentage of the index covered in the search request if {@code minimumCoverage} was set in the - * request, otherwise {@code null}. - */ - public Double getCoverage() { - return metadataSupplier != null - ? metadataSupplier.get().getFirstPageResponse().getCoverage() - : pagedFlux.getCoverage().block(); - } - - /** - * The facet query results based on the search request. - *

- * If {@code facets} weren't supplied in the request this will be {@code null}. - * - * @return The facet query results if {@code facets} were supplied in the request, otherwise {@code null}. - */ - public Map> getFacets() { - return metadataSupplier != null - ? metadataSupplier.get().getFirstPageResponse().getFacets() - : pagedFlux.getFacets().block(); - } - - /** - * The approximate number of documents that matched the search and filter parameters in the request. - *

- * If {@code count} is set to {@code false} in the request this will be {@code null}. - * - * @return The approximate number of documents that match the request if {@code count} is {@code true}, otherwise - * {@code null}. - */ - public Long getTotalCount() { - return metadataSupplier != null - ? metadataSupplier.get().getFirstPageResponse().getCount() - : pagedFlux.getTotalCount().block(); - } - - /** - * The semantic search results based on the search request. - *

- * If semantic search wasn't requested this will return a {@link SemanticSearchResults} with no values. - * - * @return The semantic search results if semantic search was requested, otherwise an empty - * {@link SemanticSearchResults}. - */ - public SemanticSearchResults getSemanticResults() { - return metadataSupplier != null - ? SemanticSearchResultsAccessHelper.create(metadataSupplier.get().getFirstPageResponse()) - : pagedFlux.getSemanticResults().block(); - } - - /** - * The debug information that can be used to further explore your search results. - * - * @return The debug information that can be used to further explore your search results. - */ - public DebugInfo getDebugInfo() { - return metadataSupplier != null - ? metadataSupplier.get().getFirstPageResponse().getDebugInfo() - : pagedFlux.getDebugInfo().block(); - } -} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/util/SearchPagedResponse.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/util/SearchPagedResponse.java deleted file mode 100644 index 068c66f6655d..000000000000 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/util/SearchPagedResponse.java +++ /dev/null @@ -1,237 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.search.documents.util; - -import com.azure.core.annotation.Immutable; -import com.azure.core.http.rest.Page; -import com.azure.core.http.rest.PagedResponseBase; -import com.azure.core.http.rest.Response; -import com.azure.search.documents.implementation.util.SearchPagedResponseAccessHelper; -import com.azure.search.documents.models.DebugInfo; -import com.azure.search.documents.models.FacetResult; -import com.azure.search.documents.models.QueryAnswerResult; -import com.azure.search.documents.models.SearchResult; -import com.azure.search.documents.models.SemanticErrorReason; -import com.azure.search.documents.models.SemanticQueryRewritesResultType; -import com.azure.search.documents.models.SemanticSearchResultsType; - -import java.util.List; -import java.util.Map; - -/** - * Represents an HTTP response from the search API request that contains a list of items deserialized into a {@link - * Page}. Each page contains additional information returned by the API request. In the Search API case the additional - * information is: count - number of total documents returned. Will be returned only if isIncludeTotalResultCount is set - * to true coverage - coverage value. - */ -@Immutable -public final class SearchPagedResponse extends PagedResponseBase { - private final List value; - - private final Long count; - private final Double coverage; - private final Map> facets; - private final List queryAnswers; - private final DebugInfo debugInfo; - private final SemanticErrorReason semanticErrorReason; - private final SemanticSearchResultsType semanticSearchResultsType; - private final SemanticQueryRewritesResultType semanticQueryRewritesResultType; - - static { - SearchPagedResponseAccessHelper.setAccessor(new SearchPagedResponseAccessHelper.SearchPagedResponseAccessor() { - @Override - public Double getCoverage(SearchPagedResponse response) { - return response.getCoverage(); - } - - @Override - public Map> getFacets(SearchPagedResponse response) { - return response.getFacets(); - } - - @Override - public Long getCount(SearchPagedResponse response) { - return response.getCount(); - } - - @Override - public List getQueryAnswers(SearchPagedResponse response) { - return response.getQueryAnswers(); - } - - @Override - public SemanticErrorReason getSemanticErrorReason(SearchPagedResponse response) { - return response.getSemanticErrorReason(); - } - - @Override - public SemanticSearchResultsType getSemanticSearchResultsType(SearchPagedResponse response) { - return response.getSemanticSearchResultsType(); - } - - @Override - public DebugInfo getDebugInfo(SearchPagedResponse response) { - return response.getDebugInfo(); - } - - @Override - public SemanticQueryRewritesResultType getSemanticQueryRewritesResultType(SearchPagedResponse response) { - return response.getSemanticQueryRewritesResultType(); - } - - }); - } - - /** - * Constructor - * - * @param response The response containing information such as the request, status code, headers, and values. - * @param continuationToken Continuation token for the next operation. - * @param facets Facets contained in the search. - * @param count Total number of documents available as a result for the search. - * @param coverage Percent of the index used in the search operation. - */ - public SearchPagedResponse(Response> response, String continuationToken, - Map> facets, Long count, Double coverage) { - this(response, continuationToken, facets, count, coverage, null, null, null); - } - - /** - * Constructor - * - * @param response The response containing information such as the request, status code, headers, and values. - * @param continuationToken Continuation token for the next operation. - * @param facets Facets contained in the search. - * @param count Total number of documents available as a result for the search. - * @param coverage Percent of the index used in the search operation. - * @param queryAnswers Answers contained in the search. - * @param semanticErrorReason Reason that a partial response was returned for a semantic search request. - * @param semanticSearchResultsType Type of the partial response returned for a semantic search request. - */ - public SearchPagedResponse(Response> response, String continuationToken, - Map> facets, Long count, Double coverage, List queryAnswers, - SemanticErrorReason semanticErrorReason, SemanticSearchResultsType semanticSearchResultsType) { - this(response, continuationToken, facets, count, coverage, queryAnswers, semanticErrorReason, - semanticSearchResultsType, null, null); - } - - /** - * Constructor - * - * @param response The response containing information such as the request, status code, headers, and values. - * @param continuationToken Continuation token for the next operation. - * @param facets Facets contained in the search. - * @param count Total number of documents available as a result for the search. - * @param coverage Percent of the index used in the search operation. - * @param queryAnswers Answers contained in the search. - * @param semanticErrorReason Reason that a partial response was returned for a semantic search request. - * @param semanticSearchResultsType Type of the partial response returned for a semantic search request. - * @param debugInfo Debug information that applies to the search results as a whole. - * @param semanticQueryRewritesResultType Type of the partial response returned for a semantic query rewrites request. - */ - public SearchPagedResponse(Response> response, String continuationToken, - Map> facets, Long count, Double coverage, List queryAnswers, - SemanticErrorReason semanticErrorReason, SemanticSearchResultsType semanticSearchResultsType, - DebugInfo debugInfo, SemanticQueryRewritesResultType semanticQueryRewritesResultType) { - super(response.getRequest(), response.getStatusCode(), response.getHeaders(), response.getValue(), - continuationToken, null); - - this.value = response.getValue(); - this.facets = facets; - this.count = count; - this.coverage = coverage; - this.queryAnswers = queryAnswers; - this.semanticErrorReason = semanticErrorReason; - this.semanticSearchResultsType = semanticSearchResultsType; - this.debugInfo = debugInfo; - this.semanticQueryRewritesResultType = semanticQueryRewritesResultType; - } - - /** - * The percentage of the index covered in the search request. - *

- * If {@code minimumCoverage} wasn't supplied in the request this will be null. - * - * @return The percentage of the index covered in the search request if {@code minimumCoverage} was set in the - * request, otherwise null. - */ - Double getCoverage() { - return coverage; - } - - /** - * The facet query results based on the search request. - *

- * If {@code facets} weren't supplied in the request this will be null. - * - * @return The facet query results if {@code facets} were supplied in the request, otherwise null. - */ - Map> getFacets() { - return facets; - } - - /** - * The approximate number of documents that matched the search and filter parameters in the request. - *

- * If {@code count} is set to {@code false} in the request this will be null. - * - * @return The approximate number of documents that match the request if {@code count} is {@code true}, otherwise - * null. - */ - Long getCount() { - return count; - } - - /** - * The answer results based on the search request. - *

- * If {@code answers} wasn't supplied in the request this will be null. - * - * @return The answer results if {@code answers} were supplied in the request, otherwise null. - */ - List getQueryAnswers() { - return queryAnswers; - } - - /** - * The reason that a partial response was returned for a semantic search request. - * - * @return Reason that a partial response was returned for a semantic search request if response was partial. - */ - SemanticErrorReason getSemanticErrorReason() { - return semanticErrorReason; - } - - /** - * The type of the partial response returned for a semantic search request. - * - * @return Type of the partial response returned for a semantic search request if response was partial. - */ - SemanticSearchResultsType getSemanticSearchResultsType() { - return semanticSearchResultsType; - } - - /** - * The debug information that can be used to further explore your search results. - * - * @return The debug information that can be used to further explore your search results. - */ - DebugInfo getDebugInfo() { - return debugInfo; - } - - /** - * The type of the partial response returned for a semantic query rewrites request. - * - * @return Type of the partial response returned for a semantic query rewrites request if response was partial. - */ - SemanticQueryRewritesResultType getSemanticQueryRewritesResultType() { - return semanticQueryRewritesResultType; - } - - @Override - public List getValue() { - return value; - } -} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/util/SuggestPagedFlux.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/util/SuggestPagedFlux.java deleted file mode 100644 index 58ea4ca2275a..000000000000 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/util/SuggestPagedFlux.java +++ /dev/null @@ -1,25 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.search.documents.util; - -import com.azure.core.http.rest.PagedFluxBase; -import com.azure.search.documents.models.SuggestResult; -import reactor.core.publisher.Mono; - -import java.util.function.Supplier; - -/** - * Implementation of {@link PagedFluxBase} where the element type is {@link SuggestResult} and the page type is {@link - * SuggestPagedResponse}. - */ -public final class SuggestPagedFlux extends PagedFluxBase { - /** - * Creates an instance of {@link SuggestPagedFlux} that retrieves a single page. - * - * @param firstPageRetriever Supplier that handles retrieving the first page. - */ - public SuggestPagedFlux(Supplier> firstPageRetriever) { - super(firstPageRetriever); - } -} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/util/SuggestPagedIterable.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/util/SuggestPagedIterable.java deleted file mode 100644 index 08d6d2b45984..000000000000 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/util/SuggestPagedIterable.java +++ /dev/null @@ -1,50 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.search.documents.util; - -import com.azure.core.http.rest.PagedIterableBase; -import com.azure.search.documents.models.SuggestResult; - -import java.util.function.Function; -import java.util.function.Supplier; - -/** - * Implementation of {@link PagedIterableBase} where the element type is {@link SuggestResult} and the page type is - * {@link SuggestPagedResponse}. - */ -public final class SuggestPagedIterable extends PagedIterableBase { - /** - * Creates instance given {@link SuggestPagedIterable}. - * - * @param pagedFluxBase The {@link SuggestPagedIterable} that will be consumed as an iterable. - */ - public SuggestPagedIterable(SuggestPagedFlux pagedFluxBase) { - super(pagedFluxBase); - } - - /** - * Creates an instance of {@link SuggestPagedIterable}. The constructor takes a {@code Supplier}. The - * {@code Supplier} returns the first page of {@code SuggestPagedResponse}. - * - * @param firstPageRetriever Supplier that retrieves the first page - */ - public SuggestPagedIterable(Supplier firstPageRetriever) { - this(firstPageRetriever, null); - } - - /** - * Creates an instance of {@link SuggestPagedIterable}. The constructor takes a {@code Supplier} and {@code Function}. The - * {@code Supplier} returns the first page of {@code SuggestPagedResponse}, the {@code Function} retrieves subsequent pages of {@code - * SuggestPagedResponse}. - * - * @param firstPageRetriever Supplier that retrieves the first page - * @param nextPageRetriever Function that retrieves the next page given a continuation token - */ - public SuggestPagedIterable(Supplier firstPageRetriever, - Function nextPageRetriever) { - super(() -> (continuationToken, pageSize) -> continuationToken == null - ? firstPageRetriever.get() - : nextPageRetriever.apply(continuationToken)); - } -} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/util/SuggestPagedResponse.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/util/SuggestPagedResponse.java deleted file mode 100644 index a4dbd33a06b0..000000000000 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/util/SuggestPagedResponse.java +++ /dev/null @@ -1,47 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.search.documents.util; - -import com.azure.core.annotation.Immutable; -import com.azure.core.http.rest.Page; -import com.azure.core.http.rest.PagedResponseBase; -import com.azure.core.http.rest.Response; -import com.azure.search.documents.models.SuggestResult; - -import java.util.List; - -/** - * Represents an HTTP response from the suggest API request that contains a list of items deserialized into a {@link - * Page}. Each page contains additional information returned by the API request. In the Suggest API case the additional - * information is: coverage - coverage value. - */ -@Immutable -public final class SuggestPagedResponse extends PagedResponseBase { - - /** - * The percentage of the index covered in the suggest request. - *

- * If {@code minimumCoverage} wasn't supplied in the request this will be {@code null}. - * - * @return The percentage of the index covered in the suggest request if {@code minimumCoverage} was set in the - * request, otherwise {@code null}. - */ - public Double getCoverage() { - return coverage; - } - - private final Double coverage; - - /** - * Constructor - * - * @param response The response containing information such as the request, status code, headers, and values. - * @param coverage Percent of the index used in the suggest operation. - */ - public SuggestPagedResponse(Response> response, Double coverage) { - super(response.getRequest(), response.getStatusCode(), response.getHeaders(), response.getValue(), null, null); - - this.coverage = coverage; - } -} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/util/package-info.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/util/package-info.java deleted file mode 100644 index 2f6640d1d7bd..000000000000 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/util/package-info.java +++ /dev/null @@ -1,7 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -/** - * Package containing Azure AI Search paged response classes. - */ -package com.azure.search.documents.util; diff --git a/sdk/search/azure-search-documents/src/main/java/module-info.java b/sdk/search/azure-search-documents/src/main/java/module-info.java index f135df68137d..bce0d8f6cc4a 100644 --- a/sdk/search/azure-search-documents/src/main/java/module-info.java +++ b/sdk/search/azure-search-documents/src/main/java/module-info.java @@ -1,20 +1,12 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. module com.azure.search.documents { - requires transitive com.azure.json; requires transitive com.azure.core; - opens com.azure.search.documents.models to com.azure.core; - opens com.azure.search.documents.implementation.models to com.azure.core; - - opens com.azure.search.documents.indexes.models to com.azure.core; - opens com.azure.search.documents.indexes.implementation.models to com.azure.core; - exports com.azure.search.documents; - exports com.azure.search.documents.indexes; - exports com.azure.search.documents.indexes.models; exports com.azure.search.documents.models; - exports com.azure.search.documents.options; - exports com.azure.search.documents.util; + + opens com.azure.search.documents.models to com.azure.core; } diff --git a/sdk/search/azure-search-documents/src/main/resources/META-INF/azure-search-documents_apiview_properties.json b/sdk/search/azure-search-documents/src/main/resources/META-INF/azure-search-documents_apiview_properties.json new file mode 100644 index 000000000000..3c905cf88db8 --- /dev/null +++ b/sdk/search/azure-search-documents/src/main/resources/META-INF/azure-search-documents_apiview_properties.json @@ -0,0 +1,500 @@ +{ + "flavor": "azure", + "CrossLanguageDefinitionId": { + "com.azure.search.documents.AliasesAsyncClient": "Search.Aliases", + "com.azure.search.documents.AliasesAsyncClient.create": "Search.Aliases.create", + "com.azure.search.documents.AliasesAsyncClient.createOrUpdate": "Search.Aliases.createOrUpdate", + "com.azure.search.documents.AliasesAsyncClient.createOrUpdateWithResponse": "Search.Aliases.createOrUpdate", + "com.azure.search.documents.AliasesAsyncClient.createWithResponse": "Search.Aliases.create", + "com.azure.search.documents.AliasesAsyncClient.delete": "Search.Aliases.delete", + "com.azure.search.documents.AliasesAsyncClient.deleteWithResponse": "Search.Aliases.delete", + "com.azure.search.documents.AliasesAsyncClient.get": "Search.Aliases.get", + "com.azure.search.documents.AliasesAsyncClient.getWithResponse": "Search.Aliases.get", + "com.azure.search.documents.AliasesAsyncClient.list": "Search.Aliases.list", + "com.azure.search.documents.AliasesClient": "Search.Aliases", + "com.azure.search.documents.AliasesClient.create": "Search.Aliases.create", + "com.azure.search.documents.AliasesClient.createOrUpdate": "Search.Aliases.createOrUpdate", + "com.azure.search.documents.AliasesClient.createOrUpdateWithResponse": "Search.Aliases.createOrUpdate", + "com.azure.search.documents.AliasesClient.createWithResponse": "Search.Aliases.create", + "com.azure.search.documents.AliasesClient.delete": "Search.Aliases.delete", + "com.azure.search.documents.AliasesClient.deleteWithResponse": "Search.Aliases.delete", + "com.azure.search.documents.AliasesClient.get": "Search.Aliases.get", + "com.azure.search.documents.AliasesClient.getWithResponse": "Search.Aliases.get", + "com.azure.search.documents.AliasesClient.list": "Search.Aliases.list", + "com.azure.search.documents.DataSourcesAsyncClient": "Search.DataSources", + "com.azure.search.documents.DataSourcesAsyncClient.create": "Search.DataSources.create", + "com.azure.search.documents.DataSourcesAsyncClient.createOrUpdate": "Search.DataSources.createOrUpdate", + "com.azure.search.documents.DataSourcesAsyncClient.createOrUpdateWithResponse": "Search.DataSources.createOrUpdate", + "com.azure.search.documents.DataSourcesAsyncClient.createWithResponse": "Search.DataSources.create", + "com.azure.search.documents.DataSourcesAsyncClient.delete": "Search.DataSources.delete", + "com.azure.search.documents.DataSourcesAsyncClient.deleteWithResponse": "Search.DataSources.delete", + "com.azure.search.documents.DataSourcesAsyncClient.get": "Search.DataSources.get", + "com.azure.search.documents.DataSourcesAsyncClient.getWithResponse": "Search.DataSources.get", + "com.azure.search.documents.DataSourcesAsyncClient.list": "Search.DataSources.list", + "com.azure.search.documents.DataSourcesAsyncClient.listWithResponse": "Search.DataSources.list", + "com.azure.search.documents.DataSourcesClient": "Search.DataSources", + "com.azure.search.documents.DataSourcesClient.create": "Search.DataSources.create", + "com.azure.search.documents.DataSourcesClient.createOrUpdate": "Search.DataSources.createOrUpdate", + "com.azure.search.documents.DataSourcesClient.createOrUpdateWithResponse": "Search.DataSources.createOrUpdate", + "com.azure.search.documents.DataSourcesClient.createWithResponse": "Search.DataSources.create", + "com.azure.search.documents.DataSourcesClient.delete": "Search.DataSources.delete", + "com.azure.search.documents.DataSourcesClient.deleteWithResponse": "Search.DataSources.delete", + "com.azure.search.documents.DataSourcesClient.get": "Search.DataSources.get", + "com.azure.search.documents.DataSourcesClient.getWithResponse": "Search.DataSources.get", + "com.azure.search.documents.DataSourcesClient.list": "Search.DataSources.list", + "com.azure.search.documents.DataSourcesClient.listWithResponse": "Search.DataSources.list", + "com.azure.search.documents.DocumentsAsyncClient": "Search.Documents", + "com.azure.search.documents.DocumentsAsyncClient.autocompleteGet": "Search.Documents.autocompleteGet", + "com.azure.search.documents.DocumentsAsyncClient.autocompleteGetWithResponse": "Search.Documents.autocompleteGet", + "com.azure.search.documents.DocumentsAsyncClient.autocompletePost": "Search.Documents.autocompletePost", + "com.azure.search.documents.DocumentsAsyncClient.autocompletePostWithResponse": "Search.Documents.autocompletePost", + "com.azure.search.documents.DocumentsAsyncClient.count": "Search.Documents.count", + "com.azure.search.documents.DocumentsAsyncClient.countWithResponse": "Search.Documents.count", + "com.azure.search.documents.DocumentsAsyncClient.get": "Search.Documents.get", + "com.azure.search.documents.DocumentsAsyncClient.getWithResponse": "Search.Documents.get", + "com.azure.search.documents.DocumentsAsyncClient.index": "Search.Documents.index", + "com.azure.search.documents.DocumentsAsyncClient.indexWithResponse": "Search.Documents.index", + "com.azure.search.documents.DocumentsAsyncClient.searchGet": "Search.Documents.searchGet", + "com.azure.search.documents.DocumentsAsyncClient.searchGetWithResponse": "Search.Documents.searchGet", + "com.azure.search.documents.DocumentsAsyncClient.searchPost": "Search.Documents.searchPost", + "com.azure.search.documents.DocumentsAsyncClient.searchPostWithResponse": "Search.Documents.searchPost", + "com.azure.search.documents.DocumentsAsyncClient.suggestGet": "Search.Documents.suggestGet", + "com.azure.search.documents.DocumentsAsyncClient.suggestGetWithResponse": "Search.Documents.suggestGet", + "com.azure.search.documents.DocumentsAsyncClient.suggestPost": "Search.Documents.suggestPost", + "com.azure.search.documents.DocumentsAsyncClient.suggestPostWithResponse": "Search.Documents.suggestPost", + "com.azure.search.documents.DocumentsClient": "Search.Documents", + "com.azure.search.documents.DocumentsClient.autocompleteGet": "Search.Documents.autocompleteGet", + "com.azure.search.documents.DocumentsClient.autocompleteGetWithResponse": "Search.Documents.autocompleteGet", + "com.azure.search.documents.DocumentsClient.autocompletePost": "Search.Documents.autocompletePost", + "com.azure.search.documents.DocumentsClient.autocompletePostWithResponse": "Search.Documents.autocompletePost", + "com.azure.search.documents.DocumentsClient.count": "Search.Documents.count", + "com.azure.search.documents.DocumentsClient.countWithResponse": "Search.Documents.count", + "com.azure.search.documents.DocumentsClient.get": "Search.Documents.get", + "com.azure.search.documents.DocumentsClient.getWithResponse": "Search.Documents.get", + "com.azure.search.documents.DocumentsClient.index": "Search.Documents.index", + "com.azure.search.documents.DocumentsClient.indexWithResponse": "Search.Documents.index", + "com.azure.search.documents.DocumentsClient.searchGet": "Search.Documents.searchGet", + "com.azure.search.documents.DocumentsClient.searchGetWithResponse": "Search.Documents.searchGet", + "com.azure.search.documents.DocumentsClient.searchPost": "Search.Documents.searchPost", + "com.azure.search.documents.DocumentsClient.searchPostWithResponse": "Search.Documents.searchPost", + "com.azure.search.documents.DocumentsClient.suggestGet": "Search.Documents.suggestGet", + "com.azure.search.documents.DocumentsClient.suggestGetWithResponse": "Search.Documents.suggestGet", + "com.azure.search.documents.DocumentsClient.suggestPost": "Search.Documents.suggestPost", + "com.azure.search.documents.DocumentsClient.suggestPostWithResponse": "Search.Documents.suggestPost", + "com.azure.search.documents.IndexersAsyncClient": "Search.Indexers", + "com.azure.search.documents.IndexersAsyncClient.create": "Search.Indexers.create", + "com.azure.search.documents.IndexersAsyncClient.createOrUpdate": "Search.Indexers.createOrUpdate", + "com.azure.search.documents.IndexersAsyncClient.createOrUpdateWithResponse": "Search.Indexers.createOrUpdate", + "com.azure.search.documents.IndexersAsyncClient.createWithResponse": "Search.Indexers.create", + "com.azure.search.documents.IndexersAsyncClient.delete": "Search.Indexers.delete", + "com.azure.search.documents.IndexersAsyncClient.deleteWithResponse": "Search.Indexers.delete", + "com.azure.search.documents.IndexersAsyncClient.get": "Search.Indexers.get", + "com.azure.search.documents.IndexersAsyncClient.getStatus": "Search.Indexers.getStatus", + "com.azure.search.documents.IndexersAsyncClient.getStatusWithResponse": "Search.Indexers.getStatus", + "com.azure.search.documents.IndexersAsyncClient.getWithResponse": "Search.Indexers.get", + "com.azure.search.documents.IndexersAsyncClient.list": "Search.Indexers.list", + "com.azure.search.documents.IndexersAsyncClient.listWithResponse": "Search.Indexers.list", + "com.azure.search.documents.IndexersAsyncClient.reset": "Search.Indexers.reset", + "com.azure.search.documents.IndexersAsyncClient.resetDocs": "Search.Indexers.resetDocs", + "com.azure.search.documents.IndexersAsyncClient.resetDocsWithResponse": "Search.Indexers.resetDocs", + "com.azure.search.documents.IndexersAsyncClient.resetWithResponse": "Search.Indexers.reset", + "com.azure.search.documents.IndexersAsyncClient.run": "Search.Indexers.run", + "com.azure.search.documents.IndexersAsyncClient.runWithResponse": "Search.Indexers.run", + "com.azure.search.documents.IndexersClient": "Search.Indexers", + "com.azure.search.documents.IndexersClient.create": "Search.Indexers.create", + "com.azure.search.documents.IndexersClient.createOrUpdate": "Search.Indexers.createOrUpdate", + "com.azure.search.documents.IndexersClient.createOrUpdateWithResponse": "Search.Indexers.createOrUpdate", + "com.azure.search.documents.IndexersClient.createWithResponse": "Search.Indexers.create", + "com.azure.search.documents.IndexersClient.delete": "Search.Indexers.delete", + "com.azure.search.documents.IndexersClient.deleteWithResponse": "Search.Indexers.delete", + "com.azure.search.documents.IndexersClient.get": "Search.Indexers.get", + "com.azure.search.documents.IndexersClient.getStatus": "Search.Indexers.getStatus", + "com.azure.search.documents.IndexersClient.getStatusWithResponse": "Search.Indexers.getStatus", + "com.azure.search.documents.IndexersClient.getWithResponse": "Search.Indexers.get", + "com.azure.search.documents.IndexersClient.list": "Search.Indexers.list", + "com.azure.search.documents.IndexersClient.listWithResponse": "Search.Indexers.list", + "com.azure.search.documents.IndexersClient.reset": "Search.Indexers.reset", + "com.azure.search.documents.IndexersClient.resetDocs": "Search.Indexers.resetDocs", + "com.azure.search.documents.IndexersClient.resetDocsWithResponse": "Search.Indexers.resetDocs", + "com.azure.search.documents.IndexersClient.resetWithResponse": "Search.Indexers.reset", + "com.azure.search.documents.IndexersClient.run": "Search.Indexers.run", + "com.azure.search.documents.IndexersClient.runWithResponse": "Search.Indexers.run", + "com.azure.search.documents.IndexesAsyncClient": "Search.Indexes", + "com.azure.search.documents.IndexesAsyncClient.analyze": "Search.Indexes.analyze", + "com.azure.search.documents.IndexesAsyncClient.analyzeWithResponse": "Search.Indexes.analyze", + "com.azure.search.documents.IndexesAsyncClient.create": "Search.Indexes.create", + "com.azure.search.documents.IndexesAsyncClient.createOrUpdate": "Search.Indexes.createOrUpdate", + "com.azure.search.documents.IndexesAsyncClient.createOrUpdateWithResponse": "Search.Indexes.createOrUpdate", + "com.azure.search.documents.IndexesAsyncClient.createWithResponse": "Search.Indexes.create", + "com.azure.search.documents.IndexesAsyncClient.delete": "Search.Indexes.delete", + "com.azure.search.documents.IndexesAsyncClient.deleteWithResponse": "Search.Indexes.delete", + "com.azure.search.documents.IndexesAsyncClient.get": "Search.Indexes.get", + "com.azure.search.documents.IndexesAsyncClient.getStatistics": "Search.Indexes.getStatistics", + "com.azure.search.documents.IndexesAsyncClient.getStatisticsWithResponse": "Search.Indexes.getStatistics", + "com.azure.search.documents.IndexesAsyncClient.getWithResponse": "Search.Indexes.get", + "com.azure.search.documents.IndexesAsyncClient.list": "Search.Indexes.list", + "com.azure.search.documents.IndexesClient": "Search.Indexes", + "com.azure.search.documents.IndexesClient.analyze": "Search.Indexes.analyze", + "com.azure.search.documents.IndexesClient.analyzeWithResponse": "Search.Indexes.analyze", + "com.azure.search.documents.IndexesClient.create": "Search.Indexes.create", + "com.azure.search.documents.IndexesClient.createOrUpdate": "Search.Indexes.createOrUpdate", + "com.azure.search.documents.IndexesClient.createOrUpdateWithResponse": "Search.Indexes.createOrUpdate", + "com.azure.search.documents.IndexesClient.createWithResponse": "Search.Indexes.create", + "com.azure.search.documents.IndexesClient.delete": "Search.Indexes.delete", + "com.azure.search.documents.IndexesClient.deleteWithResponse": "Search.Indexes.delete", + "com.azure.search.documents.IndexesClient.get": "Search.Indexes.get", + "com.azure.search.documents.IndexesClient.getStatistics": "Search.Indexes.getStatistics", + "com.azure.search.documents.IndexesClient.getStatisticsWithResponse": "Search.Indexes.getStatistics", + "com.azure.search.documents.IndexesClient.getWithResponse": "Search.Indexes.get", + "com.azure.search.documents.IndexesClient.list": "Search.Indexes.list", + "com.azure.search.documents.SearchAsyncClient": "Search", + "com.azure.search.documents.SearchAsyncClient.getIndexStatsSummary": "Search.getIndexStatsSummary", + "com.azure.search.documents.SearchAsyncClient.getServiceStatistics": "Search.getServiceStatistics", + "com.azure.search.documents.SearchAsyncClient.getServiceStatisticsWithResponse": "Search.getServiceStatistics", + "com.azure.search.documents.SearchClient": "Search", + "com.azure.search.documents.SearchClient.getIndexStatsSummary": "Search.getIndexStatsSummary", + "com.azure.search.documents.SearchClient.getServiceStatistics": "Search.getServiceStatistics", + "com.azure.search.documents.SearchClient.getServiceStatisticsWithResponse": "Search.getServiceStatistics", + "com.azure.search.documents.SearchClientBuilder": "Search", + "com.azure.search.documents.SkillsetsAsyncClient": "Search.Skillsets", + "com.azure.search.documents.SkillsetsAsyncClient.create": "Search.Skillsets.create", + "com.azure.search.documents.SkillsetsAsyncClient.createOrUpdate": "Search.Skillsets.createOrUpdate", + "com.azure.search.documents.SkillsetsAsyncClient.createOrUpdateWithResponse": "Search.Skillsets.createOrUpdate", + "com.azure.search.documents.SkillsetsAsyncClient.createWithResponse": "Search.Skillsets.create", + "com.azure.search.documents.SkillsetsAsyncClient.delete": "Search.Skillsets.delete", + "com.azure.search.documents.SkillsetsAsyncClient.deleteWithResponse": "Search.Skillsets.delete", + "com.azure.search.documents.SkillsetsAsyncClient.get": "Search.Skillsets.get", + "com.azure.search.documents.SkillsetsAsyncClient.getWithResponse": "Search.Skillsets.get", + "com.azure.search.documents.SkillsetsAsyncClient.list": "Search.Skillsets.list", + "com.azure.search.documents.SkillsetsAsyncClient.listWithResponse": "Search.Skillsets.list", + "com.azure.search.documents.SkillsetsAsyncClient.resetSkills": "Search.Skillsets.resetSkills", + "com.azure.search.documents.SkillsetsAsyncClient.resetSkillsWithResponse": "Search.Skillsets.resetSkills", + "com.azure.search.documents.SkillsetsClient": "Search.Skillsets", + "com.azure.search.documents.SkillsetsClient.create": "Search.Skillsets.create", + "com.azure.search.documents.SkillsetsClient.createOrUpdate": "Search.Skillsets.createOrUpdate", + "com.azure.search.documents.SkillsetsClient.createOrUpdateWithResponse": "Search.Skillsets.createOrUpdate", + "com.azure.search.documents.SkillsetsClient.createWithResponse": "Search.Skillsets.create", + "com.azure.search.documents.SkillsetsClient.delete": "Search.Skillsets.delete", + "com.azure.search.documents.SkillsetsClient.deleteWithResponse": "Search.Skillsets.delete", + "com.azure.search.documents.SkillsetsClient.get": "Search.Skillsets.get", + "com.azure.search.documents.SkillsetsClient.getWithResponse": "Search.Skillsets.get", + "com.azure.search.documents.SkillsetsClient.list": "Search.Skillsets.list", + "com.azure.search.documents.SkillsetsClient.listWithResponse": "Search.Skillsets.list", + "com.azure.search.documents.SkillsetsClient.resetSkills": "Search.Skillsets.resetSkills", + "com.azure.search.documents.SkillsetsClient.resetSkillsWithResponse": "Search.Skillsets.resetSkills", + "com.azure.search.documents.SynonymMapsAsyncClient": "Search.SynonymMaps", + "com.azure.search.documents.SynonymMapsAsyncClient.create": "Search.SynonymMaps.create", + "com.azure.search.documents.SynonymMapsAsyncClient.createOrUpdate": "Search.SynonymMaps.createOrUpdate", + "com.azure.search.documents.SynonymMapsAsyncClient.createOrUpdateWithResponse": "Search.SynonymMaps.createOrUpdate", + "com.azure.search.documents.SynonymMapsAsyncClient.createWithResponse": "Search.SynonymMaps.create", + "com.azure.search.documents.SynonymMapsAsyncClient.delete": "Search.SynonymMaps.delete", + "com.azure.search.documents.SynonymMapsAsyncClient.deleteWithResponse": "Search.SynonymMaps.delete", + "com.azure.search.documents.SynonymMapsAsyncClient.get": "Search.SynonymMaps.get", + "com.azure.search.documents.SynonymMapsAsyncClient.getWithResponse": "Search.SynonymMaps.get", + "com.azure.search.documents.SynonymMapsAsyncClient.list": "Search.SynonymMaps.list", + "com.azure.search.documents.SynonymMapsAsyncClient.listWithResponse": "Search.SynonymMaps.list", + "com.azure.search.documents.SynonymMapsClient": "Search.SynonymMaps", + "com.azure.search.documents.SynonymMapsClient.create": "Search.SynonymMaps.create", + "com.azure.search.documents.SynonymMapsClient.createOrUpdate": "Search.SynonymMaps.createOrUpdate", + "com.azure.search.documents.SynonymMapsClient.createOrUpdateWithResponse": "Search.SynonymMaps.createOrUpdate", + "com.azure.search.documents.SynonymMapsClient.createWithResponse": "Search.SynonymMaps.create", + "com.azure.search.documents.SynonymMapsClient.delete": "Search.SynonymMaps.delete", + "com.azure.search.documents.SynonymMapsClient.deleteWithResponse": "Search.SynonymMaps.delete", + "com.azure.search.documents.SynonymMapsClient.get": "Search.SynonymMaps.get", + "com.azure.search.documents.SynonymMapsClient.getWithResponse": "Search.SynonymMaps.get", + "com.azure.search.documents.SynonymMapsClient.list": "Search.SynonymMaps.list", + "com.azure.search.documents.SynonymMapsClient.listWithResponse": "Search.SynonymMaps.list", + "com.azure.search.documents.models.AIFoundryModelCatalogName": "Search.AIFoundryModelCatalogName", + "com.azure.search.documents.models.AIServicesAccountIdentity": "Search.AIServicesAccountIdentity", + "com.azure.search.documents.models.AIServicesAccountKey": "Search.AIServicesAccountKey", + "com.azure.search.documents.models.AIServicesVisionParameters": "Search.AIServicesVisionParameters", + "com.azure.search.documents.models.AIServicesVisionVectorizer": "Search.AIServicesVisionVectorizer", + "com.azure.search.documents.models.AnalyzeRequest": "Search.AnalyzeRequest", + "com.azure.search.documents.models.AnalyzeResult": "Search.AnalyzeResult", + "com.azure.search.documents.models.AnalyzedTokenInfo": "Search.AnalyzedTokenInfo", + "com.azure.search.documents.models.AsciiFoldingTokenFilter": "Search.AsciiFoldingTokenFilter", + "com.azure.search.documents.models.AutocompleteItem": "Search.AutocompleteItem", + "com.azure.search.documents.models.AutocompleteMode": "Search.AutocompleteMode", + "com.azure.search.documents.models.AutocompleteRequest": "Search.AutocompleteRequest", + "com.azure.search.documents.models.AutocompleteResult": "Search.AutocompleteResult", + "com.azure.search.documents.models.AzureActiveDirectoryApplicationCredentials": "Search.AzureActiveDirectoryApplicationCredentials", + "com.azure.search.documents.models.AzureMachineLearningParameters": "Search.AMLParameters", + "com.azure.search.documents.models.AzureMachineLearningSkill": "Search.AzureMachineLearningSkill", + "com.azure.search.documents.models.AzureMachineLearningVectorizer": "Search.AMLVectorizer", + "com.azure.search.documents.models.AzureOpenAIEmbeddingSkill": "Search.AzureOpenAIEmbeddingSkill", + "com.azure.search.documents.models.AzureOpenAIModelName": "Search.AzureOpenAIModelName", + "com.azure.search.documents.models.AzureOpenAITokenizerParameters": "Search.AzureOpenAITokenizerParameters", + "com.azure.search.documents.models.AzureOpenAIVectorizer": "Search.AzureOpenAIVectorizer", + "com.azure.search.documents.models.AzureOpenAIVectorizerParameters": "Search.AzureOpenAIVectorizerParameters", + "com.azure.search.documents.models.BM25SimilarityAlgorithm": "Search.BM25SimilarityAlgorithm", + "com.azure.search.documents.models.BinaryQuantizationCompression": "Search.BinaryQuantizationCompression", + "com.azure.search.documents.models.BlobIndexerDataToExtract": "Search.BlobIndexerDataToExtract", + "com.azure.search.documents.models.BlobIndexerImageAction": "Search.BlobIndexerImageAction", + "com.azure.search.documents.models.BlobIndexerPDFTextRotationAlgorithm": "Search.BlobIndexerPDFTextRotationAlgorithm", + "com.azure.search.documents.models.BlobIndexerParsingMode": "Search.BlobIndexerParsingMode", + "com.azure.search.documents.models.CharFilter": "Search.CharFilter", + "com.azure.search.documents.models.CharFilterName": "Search.CharFilterName", + "com.azure.search.documents.models.CjkBigramTokenFilter": "Search.CjkBigramTokenFilter", + "com.azure.search.documents.models.CjkBigramTokenFilterScripts": "Search.CjkBigramTokenFilterScripts", + "com.azure.search.documents.models.ClassicSimilarityAlgorithm": "Search.ClassicSimilarityAlgorithm", + "com.azure.search.documents.models.ClassicTokenizer": "Search.ClassicTokenizer", + "com.azure.search.documents.models.CognitiveServicesAccount": "Search.CognitiveServicesAccount", + "com.azure.search.documents.models.CognitiveServicesAccountKey": "Search.CognitiveServicesAccountKey", + "com.azure.search.documents.models.CommonGramTokenFilter": "Search.CommonGramTokenFilter", + "com.azure.search.documents.models.ConditionalSkill": "Search.ConditionalSkill", + "com.azure.search.documents.models.CorsOptions": "Search.CorsOptions", + "com.azure.search.documents.models.CustomAnalyzer": "Search.CustomAnalyzer", + "com.azure.search.documents.models.CustomEntity": "Search.CustomEntity", + "com.azure.search.documents.models.CustomEntityAlias": "Search.CustomEntityAlias", + "com.azure.search.documents.models.CustomEntityLookupSkill": "Search.CustomEntityLookupSkill", + "com.azure.search.documents.models.CustomEntityLookupSkillLanguage": "Search.CustomEntityLookupSkillLanguage", + "com.azure.search.documents.models.CustomNormalizer": "Search.CustomNormalizer", + "com.azure.search.documents.models.DataChangeDetectionPolicy": "Search.DataChangeDetectionPolicy", + "com.azure.search.documents.models.DataDeletionDetectionPolicy": "Search.DataDeletionDetectionPolicy", + "com.azure.search.documents.models.DataSourceCredentials": "Search.DataSourceCredentials", + "com.azure.search.documents.models.DebugInfo": "Search.DebugInfo", + "com.azure.search.documents.models.DefaultCognitiveServicesAccount": "Search.DefaultCognitiveServicesAccount", + "com.azure.search.documents.models.DictionaryDecompounderTokenFilter": "Search.DictionaryDecompounderTokenFilter", + "com.azure.search.documents.models.DistanceScoringFunction": "Search.DistanceScoringFunction", + "com.azure.search.documents.models.DistanceScoringParameters": "Search.DistanceScoringParameters", + "com.azure.search.documents.models.DocumentDebugInfo": "Search.DocumentDebugInfo", + "com.azure.search.documents.models.DocumentExtractionSkill": "Search.DocumentExtractionSkill", + "com.azure.search.documents.models.DocumentIntelligenceLayoutSkill": "Search.DocumentIntelligenceLayoutSkill", + "com.azure.search.documents.models.DocumentIntelligenceLayoutSkillMarkdownHeaderDepth": "Search.DocumentIntelligenceLayoutSkillMarkdownHeaderDepth", + "com.azure.search.documents.models.DocumentIntelligenceLayoutSkillOutputMode": "Search.DocumentIntelligenceLayoutSkillOutputMode", + "com.azure.search.documents.models.DocumentKeysOrIds": "Search.DocumentKeysOrIds", + "com.azure.search.documents.models.EdgeNGramTokenFilterSide": "Search.EdgeNGramTokenFilterSide", + "com.azure.search.documents.models.EdgeNGramTokenFilterV2": "Search.EdgeNGramTokenFilterV2", + "com.azure.search.documents.models.EdgeNGramTokenizer": "Search.EdgeNGramTokenizer", + "com.azure.search.documents.models.ElisionTokenFilter": "Search.ElisionTokenFilter", + "com.azure.search.documents.models.EntityCategory": "Search.EntityCategory", + "com.azure.search.documents.models.EntityLinkingSkill": "Search.EntityLinkingSkill", + "com.azure.search.documents.models.EntityRecognitionSkill": "Search.EntityRecognitionSkill", + "com.azure.search.documents.models.EntityRecognitionSkillLanguage": "Search.EntityRecognitionSkillLanguage", + "com.azure.search.documents.models.EntityRecognitionSkillV3": "Search.EntityRecognitionSkillV3", + "com.azure.search.documents.models.ExhaustiveKnnAlgorithmConfiguration": "Search.ExhaustiveKnnAlgorithmConfiguration", + "com.azure.search.documents.models.ExhaustiveKnnParameters": "Search.ExhaustiveKnnParameters", + "com.azure.search.documents.models.FacetResult": "Search.FacetResult", + "com.azure.search.documents.models.FieldMapping": "Search.FieldMapping", + "com.azure.search.documents.models.FieldMappingFunction": "Search.FieldMappingFunction", + "com.azure.search.documents.models.FreshnessScoringFunction": "Search.FreshnessScoringFunction", + "com.azure.search.documents.models.FreshnessScoringParameters": "Search.FreshnessScoringParameters", + "com.azure.search.documents.models.GetIndexStatisticsResult": "Search.GetIndexStatisticsResult", + "com.azure.search.documents.models.HighWaterMarkChangeDetectionPolicy": "Search.HighWaterMarkChangeDetectionPolicy", + "com.azure.search.documents.models.HnswAlgorithmConfiguration": "Search.HnswAlgorithmConfiguration", + "com.azure.search.documents.models.HnswParameters": "Search.HnswParameters", + "com.azure.search.documents.models.HybridCountAndFacetMode": "Search.HybridCountAndFacetMode", + "com.azure.search.documents.models.HybridSearch": "Search.HybridSearch", + "com.azure.search.documents.models.ImageAnalysisSkill": "Search.ImageAnalysisSkill", + "com.azure.search.documents.models.ImageAnalysisSkillLanguage": "Search.ImageAnalysisSkillLanguage", + "com.azure.search.documents.models.ImageDetail": "Search.ImageDetail", + "com.azure.search.documents.models.IndexAction": "Search.IndexAction", + "com.azure.search.documents.models.IndexActionType": "Search.IndexActionType", + "com.azure.search.documents.models.IndexBatch": "Search.IndexBatch", + "com.azure.search.documents.models.IndexDocumentsResult": "Search.IndexDocumentsResult", + "com.azure.search.documents.models.IndexProjectionMode": "Search.IndexProjectionMode", + "com.azure.search.documents.models.IndexStatisticsSummary": "Search.IndexStatisticsSummary", + "com.azure.search.documents.models.IndexerCurrentState": "Search.IndexerCurrentState", + "com.azure.search.documents.models.IndexerExecutionEnvironment": "Search.IndexerExecutionEnvironment", + "com.azure.search.documents.models.IndexerExecutionResult": "Search.IndexerExecutionResult", + "com.azure.search.documents.models.IndexerExecutionStatus": "Search.IndexerExecutionStatus", + "com.azure.search.documents.models.IndexerExecutionStatusDetail": "Search.IndexerExecutionStatusDetail", + "com.azure.search.documents.models.IndexerStatus": "Search.IndexerStatus", + "com.azure.search.documents.models.IndexingMode": "Search.IndexingMode", + "com.azure.search.documents.models.IndexingParameters": "Search.IndexingParameters", + "com.azure.search.documents.models.IndexingParametersConfiguration": "Search.IndexingParametersConfiguration", + "com.azure.search.documents.models.IndexingResult": "Search.IndexingResult", + "com.azure.search.documents.models.IndexingSchedule": "Search.IndexingSchedule", + "com.azure.search.documents.models.InputFieldMappingEntry": "Search.InputFieldMappingEntry", + "com.azure.search.documents.models.KeepTokenFilter": "Search.KeepTokenFilter", + "com.azure.search.documents.models.KeyPhraseExtractionSkill": "Search.KeyPhraseExtractionSkill", + "com.azure.search.documents.models.KeyPhraseExtractionSkillLanguage": "Search.KeyPhraseExtractionSkillLanguage", + "com.azure.search.documents.models.KeywordMarkerTokenFilter": "Search.KeywordMarkerTokenFilter", + "com.azure.search.documents.models.KeywordTokenizerV2": "Search.KeywordTokenizerV2", + "com.azure.search.documents.models.LanguageDetectionSkill": "Search.LanguageDetectionSkill", + "com.azure.search.documents.models.LengthTokenFilter": "Search.LengthTokenFilter", + "com.azure.search.documents.models.LexicalAnalyzer": "Search.LexicalAnalyzer", + "com.azure.search.documents.models.LexicalAnalyzerName": "Search.LexicalAnalyzerName", + "com.azure.search.documents.models.LexicalNormalizer": "Search.LexicalNormalizer", + "com.azure.search.documents.models.LexicalNormalizerName": "Search.LexicalNormalizerName", + "com.azure.search.documents.models.LexicalTokenizer": "Search.LexicalTokenizer", + "com.azure.search.documents.models.LexicalTokenizerName": "Search.LexicalTokenizerName", + "com.azure.search.documents.models.LimitTokenFilter": "Search.LimitTokenFilter", + "com.azure.search.documents.models.ListDataSourcesResult": "Search.ListDataSourcesResult", + "com.azure.search.documents.models.ListIndexersResult": "Search.ListIndexersResult", + "com.azure.search.documents.models.ListSkillsetsResult": "Search.ListSkillsetsResult", + "com.azure.search.documents.models.ListSynonymMapsResult": "Search.ListSynonymMapsResult", + "com.azure.search.documents.models.LookupDocument": "Search.LookupDocument", + "com.azure.search.documents.models.LuceneStandardAnalyzer": "Search.LuceneStandardAnalyzer", + "com.azure.search.documents.models.LuceneStandardTokenizerV2": "Search.LuceneStandardTokenizerV2", + "com.azure.search.documents.models.MagnitudeScoringFunction": "Search.MagnitudeScoringFunction", + "com.azure.search.documents.models.MagnitudeScoringParameters": "Search.MagnitudeScoringParameters", + "com.azure.search.documents.models.MappingCharFilter": "Search.MappingCharFilter", + "com.azure.search.documents.models.MarkdownHeaderDepth": "Search.MarkdownHeaderDepth", + "com.azure.search.documents.models.MarkdownParsingSubmode": "Search.MarkdownParsingSubmode", + "com.azure.search.documents.models.MergeSkill": "Search.MergeSkill", + "com.azure.search.documents.models.MicrosoftLanguageStemmingTokenizer": "Search.MicrosoftLanguageStemmingTokenizer", + "com.azure.search.documents.models.MicrosoftLanguageTokenizer": "Search.MicrosoftLanguageTokenizer", + "com.azure.search.documents.models.MicrosoftStemmingTokenizerLanguage": "Search.MicrosoftStemmingTokenizerLanguage", + "com.azure.search.documents.models.MicrosoftTokenizerLanguage": "Search.MicrosoftTokenizerLanguage", + "com.azure.search.documents.models.NGramTokenFilterV2": "Search.NGramTokenFilterV2", + "com.azure.search.documents.models.NGramTokenizer": "Search.NGramTokenizer", + "com.azure.search.documents.models.NativeBlobSoftDeleteDeletionDetectionPolicy": "Search.NativeBlobSoftDeleteDeletionDetectionPolicy", + "com.azure.search.documents.models.OcrLineEnding": "Search.OcrLineEnding", + "com.azure.search.documents.models.OcrSkill": "Search.OcrSkill", + "com.azure.search.documents.models.OcrSkillLanguage": "Search.OcrSkillLanguage", + "com.azure.search.documents.models.OutputFieldMappingEntry": "Search.OutputFieldMappingEntry", + "com.azure.search.documents.models.PIIDetectionSkill": "Search.PIIDetectionSkill", + "com.azure.search.documents.models.PIIDetectionSkillMaskingMode": "Search.PIIDetectionSkillMaskingMode", + "com.azure.search.documents.models.PathHierarchyTokenizerV2": "Search.PathHierarchyTokenizerV2", + "com.azure.search.documents.models.PatternAnalyzer": "Search.PatternAnalyzer", + "com.azure.search.documents.models.PatternCaptureTokenFilter": "Search.PatternCaptureTokenFilter", + "com.azure.search.documents.models.PatternReplaceCharFilter": "Search.PatternReplaceCharFilter", + "com.azure.search.documents.models.PatternReplaceTokenFilter": "Search.PatternReplaceTokenFilter", + "com.azure.search.documents.models.PatternTokenizer": "Search.PatternTokenizer", + "com.azure.search.documents.models.PhoneticEncoder": "Search.PhoneticEncoder", + "com.azure.search.documents.models.PhoneticTokenFilter": "Search.PhoneticTokenFilter", + "com.azure.search.documents.models.QueryAnswerResult": "Search.QueryAnswerResult", + "com.azure.search.documents.models.QueryAnswerType": "Search.QueryAnswerType", + "com.azure.search.documents.models.QueryCaptionResult": "Search.QueryCaptionResult", + "com.azure.search.documents.models.QueryCaptionType": "Search.QueryCaptionType", + "com.azure.search.documents.models.QueryDebugMode": "Search.QueryDebugMode", + "com.azure.search.documents.models.QueryLanguage": "Search.QueryLanguage", + "com.azure.search.documents.models.QueryResultDocumentRerankerInput": "Search.QueryResultDocumentRerankerInput", + "com.azure.search.documents.models.QueryResultDocumentSemanticField": "Search.QueryResultDocumentSemanticField", + "com.azure.search.documents.models.QueryResultDocumentSubscores": "Search.QueryResultDocumentSubscores", + "com.azure.search.documents.models.QueryRewritesDebugInfo": "Search.QueryRewritesDebugInfo", + "com.azure.search.documents.models.QueryRewritesType": "Search.QueryRewritesType", + "com.azure.search.documents.models.QueryRewritesValuesDebugInfo": "Search.QueryRewritesValuesDebugInfo", + "com.azure.search.documents.models.QuerySpellerType": "Search.QuerySpellerType", + "com.azure.search.documents.models.QueryType": "Search.QueryType", + "com.azure.search.documents.models.RegexFlags": "Search.RegexFlags", + "com.azure.search.documents.models.RescoringOptions": "Search.RescoringOptions", + "com.azure.search.documents.models.ResourceCounter": "Search.ResourceCounter", + "com.azure.search.documents.models.ScalarQuantizationCompression": "Search.ScalarQuantizationCompression", + "com.azure.search.documents.models.ScalarQuantizationParameters": "Search.ScalarQuantizationParameters", + "com.azure.search.documents.models.ScoringFunction": "Search.ScoringFunction", + "com.azure.search.documents.models.ScoringFunctionAggregation": "Search.ScoringFunctionAggregation", + "com.azure.search.documents.models.ScoringFunctionInterpolation": "Search.ScoringFunctionInterpolation", + "com.azure.search.documents.models.ScoringProfile": "Search.ScoringProfile", + "com.azure.search.documents.models.ScoringStatistics": "Search.ScoringStatistics", + "com.azure.search.documents.models.SearchAlias": "Search.SearchAlias", + "com.azure.search.documents.models.SearchDocumentsResult": "Search.SearchDocumentsResult", + "com.azure.search.documents.models.SearchField": "Search.SearchField", + "com.azure.search.documents.models.SearchFieldDataType": "Search.SearchFieldDataType", + "com.azure.search.documents.models.SearchIndex": "Search.SearchIndex", + "com.azure.search.documents.models.SearchIndexer": "Search.SearchIndexer", + "com.azure.search.documents.models.SearchIndexerCache": "Search.SearchIndexerCache", + "com.azure.search.documents.models.SearchIndexerDataContainer": "Search.SearchIndexerDataContainer", + "com.azure.search.documents.models.SearchIndexerDataIdentity": "Search.SearchIndexerDataIdentity", + "com.azure.search.documents.models.SearchIndexerDataNoneIdentity": "Search.SearchIndexerDataNoneIdentity", + "com.azure.search.documents.models.SearchIndexerDataSource": "Search.SearchIndexerDataSource", + "com.azure.search.documents.models.SearchIndexerDataSourceType": "Search.SearchIndexerDataSourceType", + "com.azure.search.documents.models.SearchIndexerDataUserAssignedIdentity": "Search.SearchIndexerDataUserAssignedIdentity", + "com.azure.search.documents.models.SearchIndexerError": "Search.SearchIndexerError", + "com.azure.search.documents.models.SearchIndexerIndexProjection": "Search.SearchIndexerIndexProjection", + "com.azure.search.documents.models.SearchIndexerIndexProjectionSelector": "Search.SearchIndexerIndexProjectionSelector", + "com.azure.search.documents.models.SearchIndexerIndexProjectionsParameters": "Search.SearchIndexerIndexProjectionsParameters", + "com.azure.search.documents.models.SearchIndexerKnowledgeStore": "Search.SearchIndexerKnowledgeStore", + "com.azure.search.documents.models.SearchIndexerKnowledgeStoreBlobProjectionSelector": "Search.SearchIndexerKnowledgeStoreBlobProjectionSelector", + "com.azure.search.documents.models.SearchIndexerKnowledgeStoreFileProjectionSelector": "Search.SearchIndexerKnowledgeStoreFileProjectionSelector", + "com.azure.search.documents.models.SearchIndexerKnowledgeStoreObjectProjectionSelector": "Search.SearchIndexerKnowledgeStoreObjectProjectionSelector", + "com.azure.search.documents.models.SearchIndexerKnowledgeStoreParameters": "Search.SearchIndexerKnowledgeStoreParameters", + "com.azure.search.documents.models.SearchIndexerKnowledgeStoreProjection": "Search.SearchIndexerKnowledgeStoreProjection", + "com.azure.search.documents.models.SearchIndexerKnowledgeStoreProjectionSelector": "Search.SearchIndexerKnowledgeStoreProjectionSelector", + "com.azure.search.documents.models.SearchIndexerKnowledgeStoreTableProjectionSelector": "Search.SearchIndexerKnowledgeStoreTableProjectionSelector", + "com.azure.search.documents.models.SearchIndexerLimits": "Search.SearchIndexerLimits", + "com.azure.search.documents.models.SearchIndexerSkill": "Search.SearchIndexerSkill", + "com.azure.search.documents.models.SearchIndexerSkillset": "Search.SearchIndexerSkillset", + "com.azure.search.documents.models.SearchIndexerStatus": "Search.SearchIndexerStatus", + "com.azure.search.documents.models.SearchIndexerWarning": "Search.SearchIndexerWarning", + "com.azure.search.documents.models.SearchMode": "Search.SearchMode", + "com.azure.search.documents.models.SearchRequest": "Search.SearchRequest", + "com.azure.search.documents.models.SearchResourceEncryptionKey": "Search.SearchResourceEncryptionKey", + "com.azure.search.documents.models.SearchResult": "Search.SearchResult", + "com.azure.search.documents.models.SearchScoreThreshold": "Search.SearchScoreThreshold", + "com.azure.search.documents.models.SearchServiceCounters": "Search.SearchServiceCounters", + "com.azure.search.documents.models.SearchServiceLimits": "Search.SearchServiceLimits", + "com.azure.search.documents.models.SearchServiceStatistics": "Search.SearchServiceStatistics", + "com.azure.search.documents.models.SearchSuggester": "Search.SearchSuggester", + "com.azure.search.documents.models.SemanticConfiguration": "Search.SemanticConfiguration", + "com.azure.search.documents.models.SemanticDebugInfo": "Search.SemanticDebugInfo", + "com.azure.search.documents.models.SemanticErrorMode": "Search.SemanticErrorMode", + "com.azure.search.documents.models.SemanticErrorReason": "Search.SemanticErrorReason", + "com.azure.search.documents.models.SemanticField": "Search.SemanticField", + "com.azure.search.documents.models.SemanticFieldState": "Search.SemanticFieldState", + "com.azure.search.documents.models.SemanticPrioritizedFields": "Search.SemanticPrioritizedFields", + "com.azure.search.documents.models.SemanticQueryRewritesResultType": "Search.SemanticQueryRewritesResultType", + "com.azure.search.documents.models.SemanticSearch": "Search.SemanticSearch", + "com.azure.search.documents.models.SemanticSearchResultsType": "Search.SemanticSearchResultsType", + "com.azure.search.documents.models.SentimentSkill": "Search.SentimentSkill", + "com.azure.search.documents.models.SentimentSkillLanguage": "Search.SentimentSkillLanguage", + "com.azure.search.documents.models.SentimentSkillV3": "Search.SentimentSkillV3", + "com.azure.search.documents.models.ShaperSkill": "Search.ShaperSkill", + "com.azure.search.documents.models.ShingleTokenFilter": "Search.ShingleTokenFilter", + "com.azure.search.documents.models.SimilarityAlgorithm": "Search.SimilarityAlgorithm", + "com.azure.search.documents.models.SingleVectorFieldResult": "Search.SingleVectorFieldResult", + "com.azure.search.documents.models.SkillNames": "Search.SkillNames", + "com.azure.search.documents.models.SnowballTokenFilter": "Search.SnowballTokenFilter", + "com.azure.search.documents.models.SnowballTokenFilterLanguage": "Search.SnowballTokenFilterLanguage", + "com.azure.search.documents.models.SoftDeleteColumnDeletionDetectionPolicy": "Search.SoftDeleteColumnDeletionDetectionPolicy", + "com.azure.search.documents.models.SplitSkill": "Search.SplitSkill", + "com.azure.search.documents.models.SplitSkillEncoderModelName": "Search.SplitSkillEncoderModelName", + "com.azure.search.documents.models.SplitSkillLanguage": "Search.SplitSkillLanguage", + "com.azure.search.documents.models.SplitSkillUnit": "Search.SplitSkillUnit", + "com.azure.search.documents.models.SqlIntegratedChangeTrackingPolicy": "Search.SqlIntegratedChangeTrackingPolicy", + "com.azure.search.documents.models.StemmerOverrideTokenFilter": "Search.StemmerOverrideTokenFilter", + "com.azure.search.documents.models.StemmerTokenFilter": "Search.StemmerTokenFilter", + "com.azure.search.documents.models.StemmerTokenFilterLanguage": "Search.StemmerTokenFilterLanguage", + "com.azure.search.documents.models.StopAnalyzer": "Search.StopAnalyzer", + "com.azure.search.documents.models.StopwordsList": "Search.StopwordsList", + "com.azure.search.documents.models.StopwordsTokenFilter": "Search.StopwordsTokenFilter", + "com.azure.search.documents.models.SuggestDocumentsResult": "Search.SuggestDocumentsResult", + "com.azure.search.documents.models.SuggestRequest": "Search.SuggestRequest", + "com.azure.search.documents.models.SuggestResult": "Search.SuggestResult", + "com.azure.search.documents.models.SynonymMap": "Search.SynonymMap", + "com.azure.search.documents.models.SynonymTokenFilter": "Search.SynonymTokenFilter", + "com.azure.search.documents.models.TagScoringFunction": "Search.TagScoringFunction", + "com.azure.search.documents.models.TagScoringParameters": "Search.TagScoringParameters", + "com.azure.search.documents.models.TextResult": "Search.TextResult", + "com.azure.search.documents.models.TextSplitMode": "Search.TextSplitMode", + "com.azure.search.documents.models.TextTranslationSkill": "Search.TextTranslationSkill", + "com.azure.search.documents.models.TextTranslationSkillLanguage": "Search.TextTranslationSkillLanguage", + "com.azure.search.documents.models.TextWeights": "Search.TextWeights", + "com.azure.search.documents.models.TokenCharacterKind": "Search.TokenCharacterKind", + "com.azure.search.documents.models.TokenFilter": "Search.TokenFilter", + "com.azure.search.documents.models.TokenFilterName": "Search.TokenFilterName", + "com.azure.search.documents.models.TruncateTokenFilter": "Search.TruncateTokenFilter", + "com.azure.search.documents.models.UaxUrlEmailTokenizer": "Search.UaxUrlEmailTokenizer", + "com.azure.search.documents.models.UniqueTokenFilter": "Search.UniqueTokenFilter", + "com.azure.search.documents.models.VectorEncodingFormat": "Search.VectorEncodingFormat", + "com.azure.search.documents.models.VectorFilterMode": "Search.VectorFilterMode", + "com.azure.search.documents.models.VectorQuery": "Search.VectorQuery", + "com.azure.search.documents.models.VectorQueryKind": "Search.VectorQueryKind", + "com.azure.search.documents.models.VectorSearch": "Search.VectorSearch", + "com.azure.search.documents.models.VectorSearchAlgorithmConfiguration": "Search.VectorSearchAlgorithmConfiguration", + "com.azure.search.documents.models.VectorSearchAlgorithmKind": "Search.VectorSearchAlgorithmKind", + "com.azure.search.documents.models.VectorSearchAlgorithmMetric": "Search.VectorSearchAlgorithmMetric", + "com.azure.search.documents.models.VectorSearchCompression": "Search.VectorSearchCompression", + "com.azure.search.documents.models.VectorSearchCompressionKind": "Search.VectorSearchCompressionKind", + "com.azure.search.documents.models.VectorSearchCompressionRescoreStorageMethod": "Search.VectorSearchCompressionRescoreStorageMethod", + "com.azure.search.documents.models.VectorSearchCompressionTarget": "Search.VectorSearchCompressionTarget", + "com.azure.search.documents.models.VectorSearchProfile": "Search.VectorSearchProfile", + "com.azure.search.documents.models.VectorSearchVectorizer": "Search.VectorSearchVectorizer", + "com.azure.search.documents.models.VectorSearchVectorizerKind": "Search.VectorSearchVectorizerKind", + "com.azure.search.documents.models.VectorSimilarityThreshold": "Search.VectorSimilarityThreshold", + "com.azure.search.documents.models.VectorThreshold": "Search.VectorThreshold", + "com.azure.search.documents.models.VectorThresholdKind": "Search.VectorThresholdKind", + "com.azure.search.documents.models.VectorizableImageBinaryQuery": "Search.VectorizableImageBinaryQuery", + "com.azure.search.documents.models.VectorizableImageUrlQuery": "Search.VectorizableImageUrlQuery", + "com.azure.search.documents.models.VectorizableTextQuery": "Search.VectorizableTextQuery", + "com.azure.search.documents.models.VectorizedQuery": "Search.VectorizedQuery", + "com.azure.search.documents.models.VectorsDebugInfo": "Search.VectorsDebugInfo", + "com.azure.search.documents.models.VisionVectorizeSkill": "Search.VisionVectorizeSkill", + "com.azure.search.documents.models.VisualFeature": "Search.VisualFeature", + "com.azure.search.documents.models.WebApiSkill": "Search.WebApiSkill", + "com.azure.search.documents.models.WebApiVectorizer": "Search.WebApiVectorizer", + "com.azure.search.documents.models.WebApiVectorizerParameters": "Search.WebApiVectorizerParameters", + "com.azure.search.documents.models.WordDelimiterTokenFilter": "Search.WordDelimiterTokenFilter" + } +} diff --git a/sdk/search/azure-search-documents/src/samples/README.md b/sdk/search/azure-search-documents/src/samples/README.md deleted file mode 100644 index 6cdcb06c0a0d..000000000000 --- a/sdk/search/azure-search-documents/src/samples/README.md +++ /dev/null @@ -1,120 +0,0 @@ ---- -page_type: sample -languages: java -products: - - azure - - azure-cognitive-search -urlFragment: search-samples ---- - -# Azure AI Search Samples client library for Java -This document explains samples and how to use them. - -## Key concepts -Key concepts are explained in detail [here][SDK_README_KEY_CONCEPTS]. - -# Samples Azure AI Search APIs -This document describes how to use samples and what is done in each sample. - -## Getting started -Getting started explained in detail [here][SDK_README_GETTING_STARTED]. - -### Include the package - -#### Include the BOM file - -Please include the azure-sdk-bom to your project to take dependency on the General Availability (GA) version of the library. In the following snippet, replace the {bom_version_to_target} placeholder with the version number. -To learn more about the BOM, see the [AZURE SDK BOM README](https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/boms/azure-sdk-bom/README.md). - -```xml - - - - com.azure - azure-sdk-bom - {bom_version_to_target} - pom - import - - - -``` -and then include the direct dependency in the dependencies section without the version tag. - -```xml - - - com.azure - azure-search-documents - - -``` - -#### Include direct dependency - -If you want to take dependency on a particular version of the library that is not present in the BOM, -add the direct dependency to your project as follows. - - -[//]: # ({x-version-update-start;com.azure:azure-search-documents;current}) -```xml - - com.azure - azure-search-documents - 11.8.0-beta.6 - -``` -[//]: # ({x-version-update-end}) - -## How to run -These sample can be run in your IDE with default JDK. - -## Examples -The following sections provide several code snippets covering some of the most common service tasks, including: - -- [Using autocomplete to expand a query from index contents](https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/AutoCompleteExample.java) -- [Creating a new index](https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/indexes/CreateIndexExample.java) -- [Creating a new index using field builder](https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/indexes/CreateIndexWithFieldBuilderExample.java) -- [Create a new indexer](https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/indexes/CreateIndexerExample.java) -- [Creating, listing and deleting data sources](https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/indexes/DataSourceExample.java) -- [Retrieving a document by key](https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/GetSingleDocumentExample.java) -- [How to handle HttpResponseException errors](https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/HttpResponseExceptionExample.java) -- [Using IndexClient configuration options](https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/IndexClientConfigurationExample.java) -- [Uploading, merging, and deleting documents in indexes](https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/IndexContentManagementExample.java) -- [Search for documents of unknown type](https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/SearchForDynamicDocumentsExample.java) -- [Using count, coverage, and facets](https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/SearchOptionsExample.java) -- [Using suggestions](https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/SearchSuggestionExample.java) -- [Searching for documents of known type](https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/SearchAsyncWithFullyTypedDocumentsExample.java) -- [Creating a synonym map for an index](https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/SynonymMapsCreateExample.java) -- [Creating skillsets](https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/indexes/CreateSkillsetExample.java) -- [Search queries options with async client](https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/SearchOptionsAsyncExample.java) -- [Search queries options with sync client](https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/SearchOptionsExample.java) -- [Retrieving Index and Service statistics](https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/IndexAndServiceStatisticsExample.java) -- [Setup datasource, indexer, index and skillset](https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/indexes/LifecycleSetupExample.java) -- [List indexers](https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/indexes/ListIndexersExample.java) -- [Add Synonym and custom skillset](https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/RefineSearchCapabilitiesExample.java) -- [Execute a search solution - run indexer and issue search queries](https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/RunningSearchSolutionExample.java) -- [Setting customer x-ms-client-request-id per API call](https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/PerCallRequestIdExample.java) -- [Index vector fields and perform vector search](https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/VectorSearchExample.java). -- [Rewrite Request URL to replace OData URL syntax with standard syntax](https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/SearchRequestUrlRewriterPolicy.java) -- [Vector search using reduced embeddings](https://github.com/Azure/azure-sdk-for-java/blob/40261403b3a75aa56a3eeaf18c2ba0fd071c87a6/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/VectorSearchReducedEmbeddings.java) - -## Troubleshooting -Troubleshooting steps can be found [here][SDK_README_TROUBLESHOOTING]. - -## Next steps -Start using Cognitive Search Java SDK in your solutions. Our SDK documentation could be found at [SDK Documentation][azsearch_docs]. - -## Contributing -This project welcomes contributions and suggestions. Find [more contributing][SDK_README_CONTRIBUTING] details here. - - -[KEYS_SDK_README]: ../../README.md -[SDK_README_CONTRIBUTING]: https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/search/azure-search-documents/README.md#contributing -[SDK_README_GETTING_STARTED]: https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/search/azure-search-documents/README.md#getting-started -[SDK_README_TROUBLESHOOTING]: https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/search/azure-search-documents/README.md#troubleshooting -[SDK_README_KEY_CONCEPTS]: https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/search/azure-search-documents/README.md#key-concepts -[SDK_README_DEPENDENCY]: ../../README.md#adding-the-package-to-your-product -[azsearch_docs]: https://learn.microsoft.com/azure/search - - diff --git a/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/AutoCompleteExample.java b/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/AutoCompleteExample.java deleted file mode 100644 index 6ce09f5b6bba..000000000000 --- a/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/AutoCompleteExample.java +++ /dev/null @@ -1,94 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.search.documents; - -import com.azure.core.credential.AzureKeyCredential; -import com.azure.core.http.rest.PagedIterableBase; -import com.azure.core.util.Configuration; -import com.azure.core.util.Context; -import com.azure.search.documents.models.AutocompleteItem; -import com.azure.search.documents.models.AutocompleteMode; -import com.azure.search.documents.models.AutocompleteOptions; -import com.azure.search.documents.util.AutocompletePagedResponse; - -/** - * This sample is based on the hotels-sample index available to install from the portal. - * See https://docs.microsoft.com/azure/search/search-get-started-portal - */ -public class AutoCompleteExample { - - /** - * From the Azure portal, get your Azure AI Search service URL and API key, - * and set the values of these environment variables: - */ - private static final String ENDPOINT = Configuration.getGlobalConfiguration().get("AZURE_COGNITIVE_SEARCH_ENDPOINT"); - private static final String API_KEY = Configuration.getGlobalConfiguration().get("AZURE_COGNITIVE_SEARCH_API_KEY"); - - public static void main(String[] args) { - - SearchClient searchClient = new SearchClientBuilder() - .endpoint(ENDPOINT) - .credential(new AzureKeyCredential(API_KEY)) - .indexName("hotels-sample-index") - .buildClient(); - - autoCompleteWithOneTermContext(searchClient); - autoCompleteWithHighlighting(searchClient); - autoCompleteWithFilterAndFuzzy(searchClient); - } - - private static void autoCompleteWithOneTermContext(SearchClient searchClient) { - - AutocompleteOptions params = new AutocompleteOptions().setAutocompleteMode( - AutocompleteMode.ONE_TERM_WITH_CONTEXT); - - PagedIterableBase results = searchClient.autocomplete("coffee m", - "sg", params, Context.NONE); - - System.out.println("Received results with one term context:"); - results.forEach(result -> System.out.println(result.getText())); - - /* Output: - * Received results with one term context: - * coffee maker - */ - } - - private static void autoCompleteWithHighlighting(SearchClient searchClient) { - AutocompleteOptions params = new AutocompleteOptions() - .setAutocompleteMode(AutocompleteMode.ONE_TERM) - .setFilter("Address/City eq 'San Diego' or Address/City eq 'Hartford'") - .setHighlightPreTag("") - .setHighlightPostTag(""); - - PagedIterableBase results = searchClient.autocomplete("co", "sg", params, - Context.NONE); - - System.out.println("Received results with highlighting:"); - results.forEach(result -> System.out.println(result.getText())); - - /* Output: - * Received results with highlighting: - * coffee - */ - } - - private static void autoCompleteWithFilterAndFuzzy(SearchClient searchClient) { - AutocompleteOptions params = new AutocompleteOptions() - .setAutocompleteMode(AutocompleteMode.ONE_TERM) - .setUseFuzzyMatching(true) - .setFilter("HotelId ne '6' and Category eq 'Budget'"); - - PagedIterableBase results = searchClient.autocomplete("su", "sg", params, - Context.NONE); - - System.out.println("Received results with filter and fuzzy:"); - results.forEach(result -> System.out.println(result.getText())); - - /* Output: - * Received results with filter and fuzzy: - * suite - */ - } -} diff --git a/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/ConsistentSessionId.java b/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/ConsistentSessionId.java deleted file mode 100644 index 1d9cd06f7cd8..000000000000 --- a/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/ConsistentSessionId.java +++ /dev/null @@ -1,35 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.search.documents; - -import com.azure.core.credential.AzureKeyCredential; -import com.azure.core.util.Configuration; - - -import com.azure.search.documents.models.Hotel; -import com.azure.search.documents.models.SearchOptions; -import com.azure.search.documents.util.SearchPagedIterable; - -public class ConsistentSessionId { - - private static final String ENDPOINT = Configuration.getGlobalConfiguration().get("AZURE_COGNITIVE_SEARCH_ENDPOINT"); - private static final String API_KEY = Configuration.getGlobalConfiguration().get("AZURE_COGNITIVE_SEARCH_API_KEY"); - - public static void main(String[] args) { - SearchClient searchClient = new SearchClientBuilder() - .endpoint(ENDPOINT) - .credential(new AzureKeyCredential(API_KEY)) - .buildClient(); - - // To ensure more consistent and unique search results within a user's session, you can use session id. - // Simply include the sessionId parameter in your queries to create a unique identifier for each user session. - // This ensures a uniform experience for users throughout their "query session". By consistently using the same - // sessionId, the system makes a best-effort attempt to target the same replica, improving the overall - // consistency of search results for users within the specified session. - SearchOptions searchOptions = new SearchOptions().setSessionId("Session-1").setFilter("Rating gt 3"); - - SearchPagedIterable results = searchClient.search("hotel", searchOptions, null); - results.forEach(result -> System.out.println("Hotel Id: " + result.getDocument(Hotel.class).getHotelId())); - } -} diff --git a/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/FieldBuilderExample.java b/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/FieldBuilderExample.java deleted file mode 100644 index 635643e8fbcd..000000000000 --- a/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/FieldBuilderExample.java +++ /dev/null @@ -1,38 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.search.documents; - -import com.azure.core.credential.AzureKeyCredential; -import com.azure.core.serializer.json.jackson.JacksonJsonSerializer; -import com.azure.core.serializer.json.jackson.JacksonJsonSerializerProvider; -import com.azure.core.util.Configuration; -import com.azure.search.documents.indexes.SearchIndexClient; -import com.azure.search.documents.indexes.SearchIndexClientBuilder; -import com.azure.search.documents.indexes.models.FieldBuilderOptions; -import com.azure.search.documents.indexes.models.SearchField; -import com.azure.search.documents.indexes.models.SearchIndex; -import com.azure.search.documents.models.Hotel; - -import java.util.List; - -public class FieldBuilderExample { - - private static final String ENDPOINT = Configuration.getGlobalConfiguration().get("AZURE_COGNITIVE_SEARCH_ENDPOINT"); - private static final String API_KEY = Configuration.getGlobalConfiguration().get("AZURE_COGNITIVE_SEARCH_API_KEY"); - - public static void main(String[] args) { - SearchIndexClient searchIndexClient = new SearchIndexClientBuilder() - .endpoint(ENDPOINT) - .credential(new AzureKeyCredential(API_KEY)) - .buildClient(); - - JacksonJsonSerializer serializer = new JacksonJsonSerializerProvider().createInstance(); - FieldBuilderOptions options = new FieldBuilderOptions().setJsonSerializer(serializer); - // Prepare the hotel index schema. The schema pull from Hotel.java. - // If you don't want to use the default Jackson serializer, pass null for serializer param. - List searchFields = SearchIndexClient.buildSearchFields(Hotel.class, options); - - searchIndexClient.createIndex(new SearchIndex("hotel", searchFields)); - } -} diff --git a/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/GetSingleDocumentExample.java b/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/GetSingleDocumentExample.java deleted file mode 100644 index ba5db7792750..000000000000 --- a/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/GetSingleDocumentExample.java +++ /dev/null @@ -1,36 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -package com.azure.search.documents; - -import com.azure.core.credential.AzureKeyCredential; -import com.azure.core.util.Configuration; - -/** - * Get a single document based on its key - * This sample is based on the hotels-sample index available to install from the portal. - * See Search getting started portal - */ -public class GetSingleDocumentExample { - - /** - * From the Azure portal, get your Azure AI Search service URL and API key, - * and set the values of these environment variables: - */ - private static final String ENDPOINT = Configuration.getGlobalConfiguration().get("AZURE_COGNITIVE_SEARCH_ENDPOINT"); - private static final String API_KEY = Configuration.getGlobalConfiguration().get("AZURE_COGNITIVE_SEARCH_API_KEY"); - - private static final String INDEX_NAME = "hotels-sample-index"; - - public static void main(String[] args) { - SearchClient client = new SearchClientBuilder() - .endpoint(ENDPOINT) - .credential(new AzureKeyCredential(API_KEY)) - .indexName(INDEX_NAME) - .buildClient(); - - // Retrieve a single document by key - SearchDocument document = client.getDocument("3", SearchDocument.class); - - document.forEach((key, value) -> System.out.println(key + ":" + value)); - } -} diff --git a/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/HotelsData.json b/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/HotelsData.json deleted file mode 100644 index 183f69b7c99f..000000000000 --- a/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/HotelsData.json +++ /dev/null @@ -1,242 +0,0 @@ -[ - { - "HotelId": "1", - "HotelName": "Fancy Stay", - "Description": "Best hotel in town if you like luxury hotels. They have an amazing infinity pool, a spa, and a really helpful concierge. The location is perfect -- right downtown, close to all the tourist attractions. We highly recommend this hotel.", - "Description_fr": "Meilleur hôtel en ville si vous aimez les hôtels de luxe. Ils ont une magnifique piscine à débordement, un spa et un concierge très utile. L'emplacement est parfait – en plein centre, à proximité de toutes les attractions touristiques. Nous recommandons fortement cet hôtel.", - "Category": "Luxury", - "Tags": [ - "pool", - "view", - "wifi", - "concierge" - ], - "ParkingIncluded": false, - "SmokingAllowed": false, - "LastRenovationDate": "2010-06-27T00:00:00Z", - "Rating": 5, - "Location": { - "type": "Point", - "coordinates": [ - -122.131577, - 47.678581 - ] - } - }, - { - "HotelId": "2", - "HotelName": "Roach Motel", - "Description": "Cheapest hotel in town. Infact, a motel.", - "Description_fr": "Hôtel le moins cher en ville. Infact, un motel.", - "Category": "Budget", - "Tags": [ - "motel", - "budget" - ], - "ParkingIncluded": true, - "SmokingAllowed": true, - "LastRenovationDate": "1982-04-28T00:00:00Z", - "Rating": 1, - "Location": { - "type": "Point", - "coordinates": [ - -122.131577, - 49.678581 - ] - } - }, - { - "HotelId": "3", - "HotelName": "EconoStay", - "Description": "Very popular hotel in town", - "Description_fr": "Hôtel le plus populaire en ville", - "Category": "Budget", - "Tags": [ - "wifi", - "budget" - ], - "ParkingIncluded": true, - "SmokingAllowed": false, - "LastRenovationDate": "1995-07-01T00:00:00Z", - "Rating": 4, - "Location": { - "type": "Point", - "coordinates": [ - -122.131577, - 49.678581 - ] - } - }, - { - "HotelId": "4", - "HotelName": "Express Rooms", - "Description": "Pretty good hotel", - "Description_fr": "Assez bon hôtel", - "Category": "Budget", - "Tags": [ - "wifi", - "budget" - ], - "ParkingIncluded": true, - "SmokingAllowed": false, - "LastRenovationDate": "1995-07-01T00:00:00Z", - "Rating": 4, - "Location": { - "type": "Point", - "coordinates": [ - -122.131577, - 48.678581 - ] - } - }, - { - "HotelId": "5", - "HotelName": "Comfy Place", - "Description": "Another good hotel", - "Description_fr": "Un autre bon hôtel", - "Category": "Budget", - "Tags": [ - "wifi", - "budget" - ], - "ParkingIncluded": true, - "SmokingAllowed": false, - "LastRenovationDate": "2012-08-12T00:00:00Z", - "Rating": 4, - "Location": { - "type": "Point", - "coordinates": [ - -122.131577, - 48.678581 - ] - } - }, - { - "HotelId": "6", - "Description": "Surprisingly expensive. Model suites have an ocean-view.", - "LastRenovationDate": null - }, - { - "HotelId": "7", - "HotelName": "Modern Stay", - "Description": "Modern architecture, very polite staff and very clean. Also very affordable.", - "Description_fr": "Architecture moderne, personnel poli et très propre. Aussi très abordable." - }, - { - "HotelId": "8", - "Description": "Has some road noise and is next to the very police station. Bathrooms had morel coverings.", - "Description_fr": "Il y a du bruit de la route et se trouve à côté de la station de police. Les salles de bain avaient des revêtements de morilles." - }, - { - "HotelId": "9", - "HotelName": "Secret Point Motel", - "Description": "The hotel is ideally located on the main commercial artery of the city in the heart of New York. A few minutes away is Time's Square and the historic centre of the city, as well as other places of interest that make New York one of America's most attractive and cosmopolitan cities.", - "Description_fr": "L'hôtel est idéalement situé sur la principale artère commerciale de la ville en plein cœur de New York. A quelques minutes se trouve la place du temps et le centre historique de la ville, ainsi que d'autres lieux d'intérêt qui font de New York l'une des villes les plus attractives et cosmopolites de l'Amérique.", - "Category": "Boutique", - "Tags": [ - "pool", - "air conditioning", - "concierge" - ], - "ParkingIncluded": false, - "LastRenovationDate": "1970-01-18T00:00:00Z", - "Rating": 4, - "Address": { - "StreetAddress": "677 5th Ave", - "City": "New York", - "StateProvince": "NY", - "PostalCode": "10022", - "Country": "USA" - }, - "Location": { - "type": "Point", - "coordinates": [ - -73.975403, - 40.760586 - ] - }, - "Rooms": [ - { - "Description": "Budget Room, 1 Queen Bed (Cityside)", - "Description_fr": "Chambre Économique, 1 grand lit (côté ville)", - "Type": "Budget Room", - "BaseRate": 9.69, - "BedOptions": "1 Queen Bed", - "SleepsCount": 2, - "SmokingAllowed": true, - "Tags": [ - "vcr/dvd" - ] - }, - { - "Description": "Budget Room, 1 King Bed (Mountain View)", - "Description_fr": "Chambre Économique, 1 très grand lit (Mountain View)", - "Type": "Budget Room", - "BaseRate": 8.09, - "BedOptions": "1 King Bed", - "SleepsCount": 2, - "SmokingAllowed": true, - "Tags": [ - "vcr/dvd", - "jacuzzi tub" - ] - } - ] - }, - { - "HotelId": "10", - "HotelName": "Countryside Hotel", - "Description": "Save up to 50% off traditional hotels. Free WiFi, great location near downtown, full kitchen, washer & dryer, 24\/7 support, bowling alley, fitness center and more.", - "Description_fr": "Économisez jusqu'à 50% sur les hôtels traditionnels. WiFi gratuit, très bien situé près du centre-ville, cuisine complète, laveuse & sécheuse, support 24\/7, bowling, centre de fitness et plus encore.", - "Category": "Budget", - "Tags": [ - "24-hour front desk service", - "coffee in lobby", - "restaurant" - ], - "ParkingIncluded": false, - "SmokingAllowed": true, - "LastRenovationDate": "1999-09-06T00:00:00Z", - "Rating": 3, - "Address": { - "StreetAddress": "6910 Fayetteville Rd", - "City": "Durham", - "StateProvince": "NC", - "PostalCode": "27713", - "Country": "USA" - }, - "Location": { - "type": "Point", - "coordinates": [ - -78.940483, - 35.904160 - ] - }, - "Rooms": [ - { - "Description": "Suite, 1 King Bed (Amenities)", - "Description_fr": "Suite, 1 très grand lit (Services)", - "Type": "Suite", - "BaseRate": 2.44, - "BedOptions": "1 King Bed", - "SleepsCount": 2, - "SmokingAllowed": true, - "Tags": [ - "coffee maker" - ] - }, - { - "Description": "Budget Room, 1 Queen Bed (Amenities)", - "Description_fr": "Chambre Économique, 1 grand lit (Services)", - "Type": "Budget Room", - "BaseRate": 7.69, - "BedOptions": "1 Queen Bed", - "SleepsCount": 2, - "SmokingAllowed": false, - "Tags": [ - "coffee maker" - ] - } - ] - } -] diff --git a/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/HotelsIndex.json b/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/HotelsIndex.json deleted file mode 100644 index 1c49c61a6606..000000000000 --- a/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/HotelsIndex.json +++ /dev/null @@ -1,220 +0,0 @@ -{ - "name": "hotels", - "fields": [ - { - "name": "HotelId", - "type": "Edm.String", - "key": true, - "filterable": true, - "sortable": true, - "facetable": true - }, - { - "name": "HotelName", - "type": "Edm.String", - "searchable": true, - "filterable": true, - "sortable": true, - "facetable": false - }, - { - "name": "Description", - "type": "Edm.String", - "searchable": true, - "filterable": false, - "sortable": false, - "facetable": false, - "analyzer": "en.lucene" - }, - { - "name": "Description_fr", - "type": "Edm.String", - "searchable": true, - "filterable": false, - "sortable": false, - "facetable": false, - "analyzer": "fr.lucene" - }, - { - "name": "Category", - "type": "Edm.String", - "searchable": true, - "filterable": true, - "sortable": true, - "facetable": true - }, - { - "name": "Tags", - "type": "Collection(Edm.String)", - "searchable": true, - "filterable": true, - "facetable": true - }, - { - "name": "ParkingIncluded", - "type": "Edm.Boolean", - "filterable": true, - "sortable": true, - "facetable": true - }, - { - "name": "SmokingAllowed", - "type": "Edm.Boolean", - "filterable": true, - "sortable": true, - "facetable": true - }, - { - "name": "LastRenovationDate", - "type": "Edm.DateTimeOffset", - "filterable": true, - "sortable": true, - "facetable": true - }, - { - "name": "Rating", - "type": "Edm.Int32", - "filterable": true, - "sortable": true, - "facetable": true - }, - { - "name": "Address", - "type": "Edm.ComplexType", - "fields": [ - { - "name": "StreetAddress", - "type": "Edm.String", - "searchable": true - }, - { - "name": "City", - "type": "Edm.String", - "searchable": true, - "filterable": true, - "sortable": true, - "facetable": true - }, - { - "name": "StateProvince", - "type": "Edm.String", - "searchable": true, - "filterable": true, - "sortable": true, - "facetable": true - }, - { - "name": "PostalCode", - "type": "Edm.String", - "searchable": true, - "filterable": true, - "sortable": true, - "facetable": true - }, - { - "name": "Country", - "type": "Edm.String", - "searchable": true, - "filterable": true, - "sortable": true, - "facetable": true - } - ] - }, - { - "name": "Location", - "type": "Edm.GeographyPoint", - "filterable": true, - "sortable": true - }, - { - "name": "Rooms", - "type": "Collection(Edm.ComplexType)", - "fields": [ - { - "name": "Description", - "type": "Edm.String", - "searchable": true, - "filterable": false, - "sortable": false, - "facetable": false, - "analyzer": "en.lucene" - }, - { - "name": "Description_fr", - "type": "Edm.String", - "searchable": true, - "filterable": false, - "sortable": false, - "facetable": false, - "analyzer": "fr.lucene" - }, - { - "name": "Type", - "type": "Edm.String", - "searchable": true, - "filterable": false, - "facetable": false - }, - { - "name": "BaseRate", - "type": "Edm.Double", - "filterable": true, - "facetable": true - }, - { - "name": "BedOptions", - "type": "Edm.String", - "searchable": true, - "filterable": true, - "facetable": true - }, - { - "name": "SleepsCount", - "type": "Edm.Int32", - "filterable": true, - "facetable": true - }, - { - "name": "SmokingAllowed", - "type": "Edm.Boolean", - "filterable": true, - "facetable": true - }, - { - "name": "Tags", - "type": "Collection(Edm.String)", - "searchable": true, - "filterable": true, - "facetable": true - } - ] - } - ], - "suggesters": [ - { - "name": "sg", - "sourceFields": [ - "Description", - "HotelName" - ] - } - ], - "scoringProfiles": [ - { - "name": "nearest", - "functions": [ - { - "type": "distance", - "fieldName": "Location", - "boost": 2.0, - "distance": { - "referencePointParameter": "myloc", - "boostingDistance": 100.0 - } - } - ], - "functionAggregation": "sum" - } - ] -} diff --git a/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/HttpResponseExceptionExample.java b/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/HttpResponseExceptionExample.java deleted file mode 100644 index 030ec1b7fe75..000000000000 --- a/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/HttpResponseExceptionExample.java +++ /dev/null @@ -1,113 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.search.documents; - -import com.azure.core.credential.AzureKeyCredential; -import com.azure.core.exception.HttpResponseException; -import com.azure.core.http.HttpResponse; -import com.azure.core.util.Configuration; -import com.azure.core.util.Context; -import com.azure.search.documents.models.SearchOptions; -import com.azure.search.documents.models.SearchResult; -import com.azure.search.documents.util.SearchPagedFlux; - -/** - * This example shows how to handle errors when the Azure AI Search service - * returns a non-successful response - *

- * This sample is based on the hotels-sample index available to install from the portal. - * See https://docs.microsoft.com/azure/search/search-get-started-portal - *

- */ -public class HttpResponseExceptionExample { - - /** - * From the Azure portal, get your Azure AI Search service URL and API key, - * and set the values of these environment variables: - */ - private static final String ENDPOINT = Configuration.getGlobalConfiguration().get("AZURE_COGNITIVE_SEARCH_ENDPOINT"); - private static final String API_KEY = Configuration.getGlobalConfiguration().get("AZURE_COGNITIVE_SEARCH_API_KEY"); - - private static final String INDEX_NAME = "hotels-sample-index"; - - public static void main(String[] args) { - handleErrorsWithSyncClient(); - handleErrorsWithAsyncClient(); - } - - /** - * With the sync client, HttpResponseExceptions are raised on failure - */ - private static void handleErrorsWithSyncClient() { - SearchClient client = new SearchClientBuilder() - .endpoint(ENDPOINT) - .credential(new AzureKeyCredential(API_KEY)) - .indexName(INDEX_NAME) - .buildClient(); - - try { - // Perform a search on a non-existent field - SearchOptions searchOptions = new SearchOptions() - .setFilter("Non_Existent_Field eq 'Luxury'"); - - Iterable results = client.search("hotel", - searchOptions, Context.NONE); - - for (SearchResult result : results) { - // normal results processing - System.out.printf("Found hotel: %s%n", result.getDocument(SearchDocument.class).get("HotelName")); - } - } catch (HttpResponseException ex) { - // The exception contains the HTTP status code and the detailed message - // returned from the search service - HttpResponse response = ex.getResponse(); - System.out.println("Status Code: " + response.getStatusCode()); - System.out.println("Message: " + ex.getMessage()); - } - } - - /** - * With the async client, errors need to be handled when subscribing to the stream - */ - private static void handleErrorsWithAsyncClient() { - SearchAsyncClient client = new SearchClientBuilder() - .endpoint(ENDPOINT) - .credential(new AzureKeyCredential(API_KEY)) - .indexName(INDEX_NAME) - .buildAsyncClient(); - - SearchOptions searchOptions = new SearchOptions() - .setFilter("Non_Existent_Field eq 'Luxury'"); - - SearchPagedFlux results = client.search("hotel", searchOptions); - results - .subscribe( - foo -> { - // normal results processing - System.out.printf("Found hotel: %s%n", foo.getDocument(SearchDocument.class).get("HotelName")); - }, - err -> { - if (err instanceof HttpResponseException) { - // The exception contains the HTTP status code and the detailed message - // returned from the search service - HttpResponse response = ((HttpResponseException) err).getResponse(); - response.getBodyAsString() - .subscribe(body -> { - System.out.println("Status Code: " + response.getStatusCode()); - System.out.println("Message: " + body); - }); - } else { - // Allow other types of errors to throw - throw new RuntimeException(err); - } - }, - () -> System.out.println("completed")); - - /* - This will block until the above query has completed. This is strongly discouraged for use in production as - it eliminates the benefits of asynchronous IO. It is used here to ensure the sample runs to completion. - */ - results.blockLast(); - } -} diff --git a/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/IndexAndServiceStatisticsExample.java b/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/IndexAndServiceStatisticsExample.java deleted file mode 100644 index 66af6fb7979d..000000000000 --- a/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/IndexAndServiceStatisticsExample.java +++ /dev/null @@ -1,340 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -package com.azure.search.documents; - -import com.azure.core.credential.AzureKeyCredential; -import com.azure.core.util.Configuration; -import com.azure.json.JsonProviders; -import com.azure.json.JsonWriter; -import com.azure.search.documents.indexes.SearchIndexClient; -import com.azure.search.documents.indexes.SearchIndexClientBuilder; -import com.azure.search.documents.indexes.models.CorsOptions; -import com.azure.search.documents.indexes.models.DistanceScoringFunction; -import com.azure.search.documents.indexes.models.DistanceScoringParameters; -import com.azure.search.documents.indexes.models.FreshnessScoringFunction; -import com.azure.search.documents.indexes.models.FreshnessScoringParameters; -import com.azure.search.documents.indexes.models.LexicalAnalyzerName; -import com.azure.search.documents.indexes.models.MagnitudeScoringFunction; -import com.azure.search.documents.indexes.models.MagnitudeScoringParameters; -import com.azure.search.documents.indexes.models.ScoringFunctionAggregation; -import com.azure.search.documents.indexes.models.ScoringFunctionInterpolation; -import com.azure.search.documents.indexes.models.ScoringProfile; -import com.azure.search.documents.indexes.models.SearchField; -import com.azure.search.documents.indexes.models.SearchFieldDataType; -import com.azure.search.documents.indexes.models.SearchIndex; -import com.azure.search.documents.indexes.models.SearchIndexStatistics; -import com.azure.search.documents.indexes.models.SearchServiceStatistics; -import com.azure.search.documents.indexes.models.SearchSuggester; -import com.azure.search.documents.indexes.models.TagScoringFunction; -import com.azure.search.documents.indexes.models.TagScoringParameters; -import com.azure.search.documents.indexes.models.TextWeights; - -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.nio.charset.StandardCharsets; -import java.time.Duration; -import java.util.Arrays; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -/** - * In this sample we will demonstrate how to get statistics for and Index and a service. - */ -public class IndexAndServiceStatisticsExample { - - /** - * From the Azure portal, get your Azure AI Search service name and API key and populate ADMIN_KEY and - * SEARCH_SERVICE_NAME. - */ - private static final String ENDPOINT = Configuration.getGlobalConfiguration().get("AZURE_COGNITIVE_SEARCH_ENDPOINT"); - private static final String ADMIN_KEY = Configuration.getGlobalConfiguration().get("AZURE_COGNITIVE_SEARCH_ADMIN_KEY"); - - public static void main(String[] args) { - SearchIndexClient client = createClient(); - getIndexStatistics(client); - getServiceStatistics(client); - } - - private static void getServiceStatistics(SearchIndexClient client) { - SearchServiceStatistics searchServiceStatistics = client.getServiceStatistics(); - - System.out.println(":" + searchServiceStatistics); - ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); - try (JsonWriter jsonWriter = JsonProviders.createWriter(outputStream)) { - searchServiceStatistics.toJson(jsonWriter).flush(); - System.out.println(new String(outputStream.toByteArray(), StandardCharsets.UTF_8)); - } catch (IOException ex) { - ex.printStackTrace(); - } - - /* Output: - { - "counters":{ - "documentCount":{ - "usage":5009, - "quota":null - }, - "indexesCount":{ - "usage":4, - "quota":50 - }, - "indexersCount":{ - "usage":2, - "quota":50 - }, - "dataSourcesCount":{ - "usage":2, - "quota":50 - }, - "storageSize":{ - "usage":19551042, - "quota":26843545600 - }, - "synonymMaps":{ - "usage":0, - "quota":5 - } - }, - "limits":{ - "maxFieldsPerIndex":1000, - "maxFieldNestingDepthPerIndex":10, - "maxComplexCollectionFieldsPerIndex":40, - "maxComplexObjectsInCollectionsPerDocument":3000 - } - } - */ - } - - private static void getIndexStatistics(SearchIndexClient client) { - SearchIndex testIndex = createTestIndex(); - SearchIndex index = client.createOrUpdateIndex(testIndex); - SearchIndexStatistics result = client.getIndexStatistics(index.getName()); - long documentCount = result.getDocumentCount(); - long storageSize = result.getStorageSize(); - - System.out.println("document Count:" + documentCount); - System.out.println("storage Size:" + storageSize); - - // Output: - // document Count:0 - // storage Size:0 - } - - /** - * A helper method to create an index for testing - * - * @return an Index - */ - private static SearchIndex createTestIndex() { - Map weights = new HashMap<>(); - weights.put("Description", 1.5); - weights.put("Category", 2.0); - List fieldList = Arrays.asList( - new SearchField("HotelId", SearchFieldDataType.STRING) - .setKey(Boolean.TRUE) - .setSearchable(Boolean.FALSE) - .setFilterable(Boolean.TRUE) - .setSortable(Boolean.TRUE) - .setFacetable(Boolean.TRUE) - .setHidden(Boolean.FALSE), - new SearchField("HotelName", SearchFieldDataType.STRING) - .setSearchable(Boolean.TRUE) - .setFilterable(Boolean.TRUE) - .setSortable(Boolean.TRUE) - .setFacetable(Boolean.FALSE) - .setHidden(Boolean.FALSE), - new SearchField("Description", SearchFieldDataType.STRING) - .setKey(Boolean.FALSE) - .setSearchable(Boolean.TRUE) - .setFilterable(Boolean.FALSE) - .setSortable(Boolean.FALSE) - .setFacetable(Boolean.FALSE) - .setAnalyzerName(LexicalAnalyzerName.EN_LUCENE) - .setHidden(Boolean.FALSE), - new SearchField("DescriptionFr", SearchFieldDataType.STRING) - .setSearchable(Boolean.TRUE) - .setFilterable(Boolean.FALSE) - .setSortable(Boolean.FALSE) - .setFacetable(Boolean.FALSE) - .setAnalyzerName(LexicalAnalyzerName.FR_LUCENE) - .setHidden(Boolean.FALSE), - new SearchField("Description_Custom", SearchFieldDataType.STRING) - .setSearchable(Boolean.TRUE) - .setFilterable(Boolean.FALSE) - .setSortable(Boolean.FALSE) - .setFacetable(Boolean.FALSE) - .setSearchAnalyzerName(LexicalAnalyzerName.STOP) - .setIndexAnalyzerName(LexicalAnalyzerName.STOP) - .setHidden(Boolean.FALSE), - new SearchField("Category", SearchFieldDataType.STRING) - .setSearchable(Boolean.TRUE) - .setFilterable(Boolean.TRUE) - .setSortable(Boolean.TRUE) - .setFacetable(Boolean.TRUE) - .setHidden(Boolean.FALSE), - new SearchField("Tags", SearchFieldDataType.collection(SearchFieldDataType.STRING)) - .setSearchable(Boolean.TRUE) - .setFilterable(Boolean.TRUE) - .setSortable(Boolean.FALSE) - .setFacetable(Boolean.TRUE) - .setHidden(Boolean.FALSE), - new SearchField("ParkingIncluded", SearchFieldDataType.BOOLEAN) - .setFilterable(Boolean.TRUE) - .setSortable(Boolean.TRUE) - .setFacetable(Boolean.TRUE) - .setHidden(Boolean.FALSE), - new SearchField("SmokingAllowed", SearchFieldDataType.BOOLEAN) - .setFilterable(Boolean.TRUE) - .setSortable(Boolean.TRUE) - .setFacetable(Boolean.TRUE) - .setHidden(Boolean.FALSE), - new SearchField("LastRenovationDate", SearchFieldDataType.DATE_TIME_OFFSET) - .setFilterable(Boolean.TRUE) - .setSortable(Boolean.TRUE) - .setFacetable(Boolean.TRUE) - .setHidden(Boolean.FALSE), - new SearchField("Rating", SearchFieldDataType.INT32) - .setFilterable(Boolean.TRUE) - .setSortable(Boolean.TRUE) - .setFacetable(Boolean.TRUE) - .setHidden(Boolean.FALSE), - new SearchField("Address", SearchFieldDataType.COMPLEX) - .setFields(Arrays.asList( - new SearchField("StreetAddress", SearchFieldDataType.STRING) - .setSearchable(Boolean.TRUE) - .setHidden(Boolean.FALSE), - new SearchField("City", SearchFieldDataType.STRING) - .setSearchable(Boolean.TRUE) - .setFilterable(Boolean.TRUE) - .setSortable(Boolean.TRUE) - .setFacetable(Boolean.TRUE) - .setHidden(Boolean.FALSE), - new SearchField("StateProvince", SearchFieldDataType.STRING) - .setSearchable(Boolean.TRUE) - .setFilterable(Boolean.TRUE) - .setSortable(Boolean.TRUE) - .setFacetable(Boolean.TRUE) - .setHidden(Boolean.FALSE), - new SearchField("Country", SearchFieldDataType.STRING) - .setSearchable(Boolean.TRUE) - .setFilterable(Boolean.TRUE) - .setSortable(Boolean.TRUE) - .setFacetable(Boolean.TRUE) - .setHidden(Boolean.FALSE), - new SearchField("PostalCode", SearchFieldDataType.STRING) - .setSearchable(Boolean.TRUE) - .setFilterable(Boolean.TRUE) - .setSortable(Boolean.TRUE) - .setFacetable(Boolean.TRUE) - .setHidden(Boolean.FALSE) - ) - ), - new SearchField("Location", SearchFieldDataType.GEOGRAPHY_POINT) - .setFilterable(Boolean.TRUE) - .setSortable(Boolean.TRUE) - .setFacetable(Boolean.FALSE) - .setHidden(Boolean.FALSE), - new SearchField("Rooms", SearchFieldDataType.collection(SearchFieldDataType.COMPLEX)) - .setFields(Arrays.asList( - new SearchField("Description", SearchFieldDataType.STRING) - .setSearchable(Boolean.TRUE) - .setHidden(Boolean.FALSE) - .setAnalyzerName(LexicalAnalyzerName.EN_LUCENE), - new SearchField("DescriptionFr", SearchFieldDataType.STRING) - .setSearchable(Boolean.TRUE) - .setHidden(Boolean.FALSE) - .setAnalyzerName(LexicalAnalyzerName.FR_LUCENE), - new SearchField("Type", SearchFieldDataType.STRING) - .setSearchable(Boolean.TRUE) - .setFilterable(Boolean.TRUE) - .setFacetable(Boolean.TRUE) - .setHidden(Boolean.FALSE), - new SearchField("BaseRate", SearchFieldDataType.DOUBLE) - .setKey(Boolean.FALSE) - .setSearchable(Boolean.FALSE) - .setFilterable(Boolean.TRUE) - .setFacetable(Boolean.TRUE) - .setHidden(Boolean.FALSE), - new SearchField("BedOptions", SearchFieldDataType.STRING) - .setSearchable(Boolean.TRUE) - .setFilterable(Boolean.TRUE) - .setFacetable(Boolean.TRUE) - .setHidden(Boolean.FALSE), - new SearchField("SleepsCount", SearchFieldDataType.INT32) - .setFilterable(Boolean.TRUE) - .setFacetable(Boolean.TRUE) - .setHidden(Boolean.FALSE), - new SearchField("SmokingAllowed", SearchFieldDataType.BOOLEAN) - .setFilterable(Boolean.TRUE) - .setFacetable(Boolean.TRUE) - .setHidden(Boolean.FALSE), - new SearchField("Tags", SearchFieldDataType.collection(SearchFieldDataType.STRING)) - .setSearchable(Boolean.TRUE) - .setFilterable(Boolean.TRUE) - .setSortable(Boolean.FALSE) - .setFacetable(Boolean.TRUE) - .setHidden(Boolean.FALSE) - ) - ), - new SearchField("TotalGuests", SearchFieldDataType.INT64) - .setFilterable(Boolean.TRUE) - .setSortable(Boolean.TRUE) - .setFacetable(Boolean.TRUE) - .setHidden(Boolean.TRUE), - new SearchField("ProfitMargin", SearchFieldDataType.DOUBLE) - ); - return new SearchIndex("hotels", fieldList) - .setScoringProfiles(Arrays.asList( - new ScoringProfile("MyProfile") - .setFunctionAggregation(ScoringFunctionAggregation.AVERAGE) - .setFunctions(new MagnitudeScoringFunction("Rating", 2.0, - new MagnitudeScoringParameters(1, 4) - .setShouldBoostBeyondRangeByConstant(true)) - .setInterpolation(ScoringFunctionInterpolation.CONSTANT), - new DistanceScoringFunction("Location", 1.5, - new DistanceScoringParameters("Loc", 5)) - .setInterpolation(ScoringFunctionInterpolation.LINEAR), - new FreshnessScoringFunction("LastRenovationDate", 1.1, - new FreshnessScoringParameters(Duration.ofDays(365))) - .setInterpolation(ScoringFunctionInterpolation.LOGARITHMIC) - ) - .setTextWeights(new TextWeights(weights)), - new ScoringProfile("ProfileTwo") - .setFunctionAggregation(ScoringFunctionAggregation.MAXIMUM) - .setFunctions(new TagScoringFunction("Tags", 1.5, new TagScoringParameters("MyTags")) - .setInterpolation(ScoringFunctionInterpolation.LINEAR) - ), - new ScoringProfile("ProfileThree") - .setFunctionAggregation(ScoringFunctionAggregation.MINIMUM) - .setFunctions(new MagnitudeScoringFunction("Rating", 3.0, - new MagnitudeScoringParameters(0, 10) - .setShouldBoostBeyondRangeByConstant(false)) - .setInterpolation(ScoringFunctionInterpolation.QUADRATIC) - ), - new ScoringProfile("ProfileFour") - .setFunctionAggregation(ScoringFunctionAggregation.FIRST_MATCHING) - .setFunctions(new MagnitudeScoringFunction("Rating", 3.5, - new MagnitudeScoringParameters(1, 5) - .setShouldBoostBeyondRangeByConstant(false)) - .setInterpolation(ScoringFunctionInterpolation.CONSTANT)))) - .setDefaultScoringProfile("MyProfile") - .setCorsOptions(new CorsOptions(Arrays.asList("http://tempuri.org", "http://localhost:80")) - .setMaxAgeInSeconds(60L)) - .setSuggesters(new SearchSuggester("FancySuggester", Collections.singletonList("HotelName"))); - } - - /** - * Builds a {@link SearchIndexClient} - * - * @return async service client - */ - private static SearchIndexClient createClient() { - AzureKeyCredential searchApiKeyCredential = new AzureKeyCredential(ADMIN_KEY); - return new SearchIndexClientBuilder() - .endpoint(ENDPOINT) - .credential(searchApiKeyCredential) - .buildClient(); - } -} diff --git a/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/IndexClientConfigurationExample.java b/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/IndexClientConfigurationExample.java deleted file mode 100644 index 2af012dbadc7..000000000000 --- a/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/IndexClientConfigurationExample.java +++ /dev/null @@ -1,61 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -package com.azure.search.documents; - -import com.azure.core.credential.AzureKeyCredential; -import com.azure.core.http.netty.NettyAsyncHttpClientBuilder; -import com.azure.core.http.policy.RetryPolicy; -import com.azure.core.util.Configuration; - -/** - * This example shows how to use the {@link SearchClientBuilder} to create an index client - *

- * This sample is based on the hotels-sample index available to install from the portal. - * See Search getting started portal - */ -public class IndexClientConfigurationExample { - - /** - * From the Azure portal, get your Azure AI Search service URL and API key, - * and set the values of these environment variables: - */ - private static final String ENDPOINT = Configuration.getGlobalConfiguration().get("AZURE_COGNITIVE_SEARCH_ENDPOINT"); - private static final String API_KEY = Configuration.getGlobalConfiguration().get("AZURE_COGNITIVE_SEARCH_API_KEY"); - - public static void main(String[] args) { - createMinimalClient(); - createAdvancedClient(); - } - - /** - * Builds a {@link SearchClient} with the minimum required configuration - * - * @return an index client with all defaults - */ - private static SearchClient createMinimalClient() { - return new SearchClientBuilder() - .endpoint(ENDPOINT) - .credential(new AzureKeyCredential(API_KEY)) - .indexName("hotels") - .buildClient(); - } - - /** - * Builds a {@link SearchAsyncClient} with additional configuration - * - * @return a customized async index client - */ - private static SearchAsyncClient createAdvancedClient() { - return new SearchClientBuilder() - .endpoint(ENDPOINT) - .credential(new AzureKeyCredential(API_KEY)) - .indexName("hotels") - .serviceVersion(SearchServiceVersion.V2020_06_30) - .addPolicy(new RetryPolicy()) - .httpClient( - new NettyAsyncHttpClientBuilder() - .wiretap(true) - .build() - ).buildAsyncClient(); - } -} diff --git a/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/IndexContentManagementExample.java b/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/IndexContentManagementExample.java deleted file mode 100644 index 3c374829de27..000000000000 --- a/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/IndexContentManagementExample.java +++ /dev/null @@ -1,77 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.search.documents; - -import com.azure.core.credential.AzureKeyCredential; -import com.azure.core.util.Configuration; -import com.azure.search.documents.models.Hotel; -import com.azure.search.documents.indexes.models.IndexDocumentsBatch; -import com.azure.search.documents.models.IndexDocumentsResult; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; - -/** - * This example shows how to manage the contents of an Azure AI Search index. - *

- * This sample is based on the hotels-sample index available to install from the portal. - * See https://docs.microsoft.com/azure/search/search-get-started-portal - */ -public class IndexContentManagementExample { - - /** - * From the Azure portal, get your Azure AI Search service URL and API key, - * and set the values of these environment variables: - */ - private static final String ENDPOINT = Configuration.getGlobalConfiguration().get("AZURE_COGNITIVE_SEARCH_ENDPOINT"); - private static final String ADMIN_KEY = Configuration.getGlobalConfiguration().get("AZURE_COGNITIVE_SEARCH_ADMIN_KEY"); - - private static final String INDEX_NAME = "hotels-sample-index"; - - public static void main(String[] args) { - basicIndexing(); - advancedIndexing(); - } - - /** - * Quickly upload, merge, mergeOrUpload, and delete Lists of the same - * type directly from the index client - */ - private static void basicIndexing() { - SearchClient client = new SearchClientBuilder() - .endpoint(ENDPOINT) - .credential(new AzureKeyCredential(ADMIN_KEY)) - .indexName(INDEX_NAME) - .buildClient(); - - List hotels = new ArrayList<>(); - hotels.add(new Hotel().setHotelId("100")); - hotels.add(new Hotel().setHotelId("200")); - hotels.add(new Hotel().setHotelId("300")); - - // Perform index operations on a list of documents - IndexDocumentsResult result = client.mergeOrUploadDocuments(hotels); - System.out.printf("Indexed %s documents%n", result.getResults().size()); - } - - /** - * Advanced usage that includes different types of operations in a single batch - */ - private static void advancedIndexing() { - SearchClient client = new SearchClientBuilder() - .endpoint(ENDPOINT) - .credential(new AzureKeyCredential(ADMIN_KEY)) - .indexName(INDEX_NAME) - .buildClient(); - - IndexDocumentsBatch batch = new IndexDocumentsBatch() - .addMergeOrUploadActions(Collections.singletonList(new Hotel().setHotelId("100"))) - .addDeleteActions(Collections.singletonList(new Hotel().setHotelId("200"))); - - // Send a single batch that performs many different actions - IndexDocumentsResult result = client.indexDocuments(batch); - System.out.printf("Indexed %s documents%n", result.getResults().size()); - } -} diff --git a/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/PerCallRequestIdExample.java b/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/PerCallRequestIdExample.java deleted file mode 100644 index cbc29a9be53d..000000000000 --- a/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/PerCallRequestIdExample.java +++ /dev/null @@ -1,110 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.search.documents; - -import com.azure.core.credential.AzureKeyCredential; -import com.azure.core.http.HttpHeaders; -import com.azure.core.http.policy.AddHeadersFromContextPolicy; -import com.azure.core.http.rest.Response; -import com.azure.core.util.Configuration; -import com.azure.core.util.Context; -import com.azure.search.documents.models.Hotel; -import com.azure.search.documents.models.IndexDocumentsResult; - -import java.util.ArrayList; -import java.util.List; -import java.util.UUID; - -/** - * This example shows how to set a custom {@code x-ms-client-request-id} per request. - *

- * By default, clients are built with a policy that adds a per request generated {@code x-ms-client-request-id}. This - * will show how to leverage {@link Context} to set a application passed {@code x-ms-client-request-id} per API call. - */ -@SuppressWarnings("unused") -public class PerCallRequestIdExample { - private static final String ENDPOINT = Configuration.getGlobalConfiguration().get("AZURE_COGNITIVE_SEARCH_ENDPOINT"); - private static final String ADMIN_KEY = Configuration.getGlobalConfiguration().get("AZURE_COGNITIVE_SEARCH_ADMIN_KEY"); - - private static final String INDEX_NAME = "hotels-sample-index"; - - public static void main(String[] args) { - synchronousApiCall(); - asynchronousApiCall(); - } - - /** - * This example shows how to pass {@code x-ms-client-request-id} when using a synchronous client. - *

- * Synchronous clients only accept {@link Context} in their maximum parameter overloads. - */ - private static void synchronousApiCall() { - SearchClient client = createBuilder().buildClient(); - - List hotels = new ArrayList<>(); - hotels.add(new Hotel().setHotelId("100")); - hotels.add(new Hotel().setHotelId("200")); - hotels.add(new Hotel().setHotelId("300")); - - // Setup context to pass custom x-ms-client-request-id. - HttpHeaders headers = new HttpHeaders(); - headers.set("x-ms-client-request-id", UUID.randomUUID().toString()); - - Context context = new Context(AddHeadersFromContextPolicy.AZURE_REQUEST_HTTP_HEADERS_KEY, headers); - - // Print out expected 'x-ms-client-request-id' header value. - System.out.printf("Sending request with 'x-ms-client-request-id': %s%n", headers.get("x-ms-client-request-id")); - - // Perform index operations on a list of documents - Response response = client.mergeOrUploadDocumentsWithResponse(hotels, null, context); - System.out.printf("Indexed %s documents%n", response.getValue().getResults().size()); - - // Print out verification of 'x-ms-client-request-id' returned by the service response. - System.out.printf("Received response with returned 'x-ms-client-request-id': %s%n", - response.getHeaders().get("x-ms-client-request-id")); - } - - /** - * This examples shows how to pass {@code x-ms-client-request-id} when using an asynchronous client. - *

- * Asynchronous clients are able to accept {@link Context} in all APIs using Reactor's - * {@link Mono#contextWrite(ContextView)} or {@link Flux#contextWrite(ContextView)} - */ - private static void asynchronousApiCall() { - SearchAsyncClient client = createBuilder().buildAsyncClient(); - - List hotels = new ArrayList<>(); - hotels.add(new Hotel().setHotelId("100")); - hotels.add(new Hotel().setHotelId("200")); - hotels.add(new Hotel().setHotelId("300")); - - // Setup context to pass custom x-ms-client-request-id. - HttpHeaders headers = new HttpHeaders(); - headers.set("x-ms-client-request-id", UUID.randomUUID().toString()); - - reactor.util.context.Context context = reactor.util.context.Context.of( - AddHeadersFromContextPolicy.AZURE_REQUEST_HTTP_HEADERS_KEY, headers); - - // Print out expected 'x-ms-client-request-id' header value. - System.out.printf("Sending request with 'x-ms-client-request-id': %s%n", headers.get("x-ms-client-request-id")); - - // Perform index operations on a list of documents - client.mergeDocumentsWithResponse(hotels, null) - .contextWrite(context) - .doOnSuccess(response -> { - System.out.printf("Indexed %s documents%n", response.getValue().getResults().size()); - - // Print out verification of 'x-ms-client-request-id' returned by the service response. - System.out.printf("Received response with returned 'x-ms-client-request-id': %s%n", - response.getHeaders().get("x-ms-client-request-id")); - }).block(); - } - - private static SearchClientBuilder createBuilder() { - return new SearchClientBuilder() - .endpoint(ENDPOINT) - .credential(new AzureKeyCredential(ADMIN_KEY)) - .indexName(INDEX_NAME); - } -} diff --git a/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/ReadmeSamples.java b/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/ReadmeSamples.java index 0e79c55451a0..840f136bbb96 100644 --- a/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/ReadmeSamples.java +++ b/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/ReadmeSamples.java @@ -1,312 +1,12 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -package com.azure.search.documents; - -import com.azure.core.credential.AzureKeyCredential; -import com.azure.core.exception.HttpResponseException; -import com.azure.core.http.HttpHeaders; -import com.azure.core.http.HttpResponse; -import com.azure.core.http.policy.AddHeadersFromContextPolicy; -import com.azure.core.util.Configuration; -import com.azure.core.util.Context; -import com.azure.identity.AzureAuthorityHosts; -import com.azure.identity.DefaultAzureCredential; -import com.azure.identity.DefaultAzureCredentialBuilder; -import com.azure.search.documents.indexes.SearchIndexAsyncClient; -import com.azure.search.documents.indexes.SearchIndexClient; -import com.azure.search.documents.indexes.SearchIndexClientBuilder; -import com.azure.search.documents.indexes.SearchIndexerAsyncClient; -import com.azure.search.documents.indexes.SearchIndexerClient; -import com.azure.search.documents.indexes.SearchIndexerClientBuilder; -import com.azure.search.documents.indexes.SearchableField; -import com.azure.search.documents.indexes.SimpleField; -import com.azure.search.documents.indexes.models.IndexDocumentsBatch; -import com.azure.search.documents.indexes.models.LexicalAnalyzerName; -import com.azure.search.documents.indexes.models.SearchField; -import com.azure.search.documents.indexes.models.SearchFieldDataType; -import com.azure.search.documents.indexes.models.SearchIndex; -import com.azure.search.documents.indexes.models.SearchSuggester; -import com.azure.search.documents.models.SearchAudience; -import com.azure.search.documents.models.SearchOptions; -import com.azure.search.documents.models.SearchResult; -import com.azure.search.documents.util.SearchPagedIterable; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; - -/** - * Code samples for the README.md - */ -@SuppressWarnings("unused") -public class ReadmeSamples { - private static final String ENDPOINT = "endpoint"; - private static final String ADMIN_KEY = "admin key"; - private static final String API_KEY = "api key"; - private static final String INDEX_NAME = "index name"; - private static final SearchIndexClient SEARCH_INDEX_CLIENT = new SearchIndexClientBuilder().buildClient(); - private static final SearchClient SEARCH_CLIENT = new SearchClientBuilder().buildClient(); - private static final SearchAsyncClient SEARCH_ASYNC_CLIENT = new SearchClientBuilder().buildAsyncClient(); - - public void createSearchClient() { - // BEGIN: readme-sample-createSearchClient - SearchClient searchClient = new SearchClientBuilder() - .endpoint(ENDPOINT) - .credential(new AzureKeyCredential(ADMIN_KEY)) - .indexName(INDEX_NAME) - .buildClient(); - // END: readme-sample-createSearchClient - } - - public void createAsyncSearchClient() { - // BEGIN: readme-sample-createAsyncSearchClient - SearchAsyncClient searchAsyncClient = new SearchClientBuilder() - .endpoint(ENDPOINT) - .credential(new AzureKeyCredential(ADMIN_KEY)) - .indexName(INDEX_NAME) - .buildAsyncClient(); - // END: readme-sample-createAsyncSearchClient - } - - public void createIndexClient() { - // BEGIN: readme-sample-createIndexClient - SearchIndexClient searchIndexClient = new SearchIndexClientBuilder() - .endpoint(ENDPOINT) - .credential(new AzureKeyCredential(API_KEY)) - .buildClient(); - // END: readme-sample-createIndexClient - } - - public void createIndexAsyncClient() { - // BEGIN: readme-sample-createIndexAsyncClient - SearchIndexAsyncClient searchIndexAsyncClient = new SearchIndexClientBuilder() - .endpoint(ENDPOINT) - .credential(new AzureKeyCredential(API_KEY)) - .buildAsyncClient(); - // END: readme-sample-createIndexAsyncClient - } - - public void createIndexerClient() { - // BEGIN: readme-sample-createIndexerClient - SearchIndexerClient searchIndexerClient = new SearchIndexerClientBuilder() - .endpoint(ENDPOINT) - .credential(new AzureKeyCredential(API_KEY)) - .buildClient(); - // END: readme-sample-createIndexerClient - } - - public void createIndexerAsyncClient() { - // BEGIN: readme-sample-createIndexerAsyncClient - SearchIndexerAsyncClient searchIndexerAsyncClient = new SearchIndexerClientBuilder() - .endpoint(ENDPOINT) - .credential(new AzureKeyCredential(API_KEY)) - .buildAsyncClient(); - // END: readme-sample-createIndexerAsyncClient - } - - public void customHeaders() { - HttpHeaders headers = new HttpHeaders(); - headers.set("my-header1", "my-header1-value"); - headers.set("my-header2", "my-header2-value"); - headers.set("my-header3", "my-header3-value"); - // Call API by passing headers in Context. - SearchIndex index = new SearchIndex(INDEX_NAME).setFields( - new SearchField("hotelId", SearchFieldDataType.STRING) - .setKey(true) - .setFilterable(true) - .setSortable(true)); - SEARCH_INDEX_CLIENT.createIndexWithResponse(index, - new Context(AddHeadersFromContextPolicy.AZURE_REQUEST_HTTP_HEADERS_KEY, headers)); - // Above three HttpHeader will be added in outgoing HttpRequest. - } - - public void handleErrorsWithSyncClient() { - // BEGIN: readme-sample-handleErrorsWithSyncClient - try { - Iterable results = SEARCH_CLIENT.search("hotel"); - } catch (HttpResponseException ex) { - // The exception contains the HTTP status code and the detailed message - // returned from the search service - HttpResponse response = ex.getResponse(); - System.out.println("Status Code: " + response.getStatusCode()); - System.out.println("Message: " + ex.getMessage()); - } - // END: readme-sample-handleErrorsWithSyncClient - } - - public void searchWithDynamicType() { - // BEGIN: readme-sample-searchWithDynamicType - for (SearchResult searchResult : SEARCH_CLIENT.search("luxury")) { - SearchDocument doc = searchResult.getDocument(SearchDocument.class); - String id = (String) doc.get("hotelId"); - String name = (String) doc.get("hotelName"); - System.out.printf("This is hotelId %s, and this is hotel name %s.%n", id, name); - } - // END: readme-sample-searchWithDynamicType - } - - // BEGIN: readme-sample-hotelclass - public static class Hotel { - @SimpleField(isKey = true, isFilterable = true, isSortable = true) - private String id; - @SearchableField(isFilterable = true, isSortable = true) - private String name; - - public String getId() { - return id; - } +// Code generated by Microsoft (R) TypeSpec Code Generator. - public Hotel setId(String id) { - this.id = id; - return this; - } - - public String getName() { - return name; - } - - public Hotel setName(String name) { - this.name = name; - return this; - } - } - // END: readme-sample-hotelclass - - public void searchWithStronglyType() { - // BEGIN: readme-sample-searchWithStronglyType - for (SearchResult searchResult : SEARCH_CLIENT.search("luxury")) { - Hotel doc = searchResult.getDocument(Hotel.class); - String id = doc.getId(); - String name = doc.getName(); - System.out.printf("This is hotelId %s, and this is hotel name %s.%n", id, name); - } - // END: readme-sample-searchWithStronglyType - } - - public void searchWithSearchOptions() { - // BEGIN: readme-sample-searchWithSearchOptions - SearchOptions options = new SearchOptions() - .setFilter("rating ge 4") - .setOrderBy("rating desc") - .setTop(5); - SearchPagedIterable searchResultsIterable = SEARCH_CLIENT.search("luxury", options, Context.NONE); - // ... - // END: readme-sample-searchWithSearchOptions - } - - public void searchWithAsyncClient() { - // BEGIN: readme-sample-searchWithAsyncClient - SEARCH_ASYNC_CLIENT.search("luxury") - .subscribe(result -> { - Hotel hotel = result.getDocument(Hotel.class); - System.out.printf("This is hotelId %s, and this is hotel name %s.%n", hotel.getId(), hotel.getName()); - }); - // END: readme-sample-searchWithAsyncClient - } - - public void retrieveDocuments() { - // BEGIN: readme-sample-retrieveDocuments - Hotel hotel = SEARCH_CLIENT.getDocument("1", Hotel.class); - System.out.printf("This is hotelId %s, and this is hotel name %s.%n", hotel.getId(), hotel.getName()); - // END: readme-sample-retrieveDocuments - } - - public void batchDocumentsOperations() { - // BEGIN: readme-sample-batchDocumentsOperations - IndexDocumentsBatch batch = new IndexDocumentsBatch<>(); - batch.addUploadActions(Collections.singletonList(new Hotel().setId("783").setName("Upload Inn"))); - batch.addMergeActions(Collections.singletonList(new Hotel().setId("12").setName("Renovated Ranch"))); - SEARCH_CLIENT.indexDocuments(batch); - // END: readme-sample-batchDocumentsOperations - } - - public void createIndex() { - // BEGIN: readme-sample-createIndex - List searchFieldList = new ArrayList<>(); - searchFieldList.add(new SearchField("hotelId", SearchFieldDataType.STRING) - .setKey(true) - .setFilterable(true) - .setSortable(true)); - - searchFieldList.add(new SearchField("hotelName", SearchFieldDataType.STRING) - .setSearchable(true) - .setFilterable(true) - .setSortable(true)); - searchFieldList.add(new SearchField("description", SearchFieldDataType.STRING) - .setSearchable(true) - .setAnalyzerName(LexicalAnalyzerName.EU_LUCENE)); - searchFieldList.add(new SearchField("tags", SearchFieldDataType.collection(SearchFieldDataType.STRING)) - .setSearchable(true) - .setFilterable(true) - .setFacetable(true)); - searchFieldList.add(new SearchField("address", SearchFieldDataType.COMPLEX) - .setFields(new SearchField("streetAddress", SearchFieldDataType.STRING).setSearchable(true), - new SearchField("city", SearchFieldDataType.STRING) - .setSearchable(true) - .setFilterable(true) - .setFacetable(true) - .setSortable(true), - new SearchField("stateProvince", SearchFieldDataType.STRING) - .setSearchable(true) - .setFilterable(true) - .setFacetable(true) - .setSortable(true), - new SearchField("country", SearchFieldDataType.STRING) - .setSearchable(true) - .setFilterable(true) - .setFacetable(true) - .setSortable(true), - new SearchField("postalCode", SearchFieldDataType.STRING) - .setSearchable(true) - .setFilterable(true) - .setFacetable(true) - .setSortable(true) - )); - - // Prepare suggester. - SearchSuggester suggester = new SearchSuggester("sg", Collections.singletonList("hotelName")); - // Prepare SearchIndex with index name and search fields. - SearchIndex index = new SearchIndex("hotels").setFields(searchFieldList).setSuggesters(suggester); - // Create an index - SEARCH_INDEX_CLIENT.createIndex(index); - // END: readme-sample-createIndex - } - - public void createIndexUseFieldBuilder() { - // BEGIN: readme-sample-createIndexUseFieldBuilder - List searchFields = SearchIndexClient.buildSearchFields(Hotel.class, null); - SEARCH_INDEX_CLIENT.createIndex(new SearchIndex("index", searchFields)); - // END: readme-sample-createIndexUseFieldBuilder - } - - public void nationalCloud() { - // BEGIN: readme-sample-nationalCloud - // Create a SearchClient that will authenticate through AAD in the China national cloud. - SearchClient searchClient = new SearchClientBuilder() - .endpoint(ENDPOINT) - .indexName(INDEX_NAME) - .credential(new DefaultAzureCredentialBuilder() - .authorityHost(AzureAuthorityHosts.AZURE_CHINA) - .build()) - .audience(SearchAudience.AZURE_CHINA) - .buildClient(); - // END: readme-sample-nationalCloud - } - - public void searchClientWithTokenCredential() { - // BEGIN: readme-sample-searchClientWithTokenCredential - String indexName = "nycjobs"; - - // Get the service endpoint from the environment - String endpoint = Configuration.getGlobalConfiguration().get("SEARCH_ENDPOINT"); - DefaultAzureCredential credential = new DefaultAzureCredentialBuilder().build(); +package com.azure.search.documents; - // Create a client - SearchClient client = new SearchClientBuilder() - .endpoint(endpoint) - .indexName(indexName) - .credential(credential) - .buildClient(); - // END: readme-sample-searchClientWithTokenCredential +public final class ReadmeSamples { + public void readmeSamples() { + // BEGIN: com.azure.search.documents.readme + // END: com.azure.search.documents.readme } } diff --git a/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/RefineSearchCapabilitiesExample.java b/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/RefineSearchCapabilitiesExample.java deleted file mode 100644 index cc302b8b46ca..000000000000 --- a/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/RefineSearchCapabilitiesExample.java +++ /dev/null @@ -1,160 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.search.documents; - -import com.azure.core.credential.AzureKeyCredential; -import com.azure.core.util.Configuration; -import com.azure.search.documents.indexes.SearchIndexClient; -import com.azure.search.documents.indexes.SearchIndexClientBuilder; -import com.azure.search.documents.indexes.SearchIndexerClient; -import com.azure.search.documents.indexes.SearchIndexerClientBuilder; -import com.azure.search.documents.indexes.models.InputFieldMappingEntry; -import com.azure.search.documents.indexes.models.OutputFieldMappingEntry; -import com.azure.search.documents.indexes.models.SearchField; -import com.azure.search.documents.indexes.models.SearchIndex; -import com.azure.search.documents.indexes.models.SearchIndexer; -import com.azure.search.documents.indexes.models.SearchIndexerSkill; -import com.azure.search.documents.indexes.models.SearchIndexerSkillset; -import com.azure.search.documents.indexes.models.SearchServiceCounters; -import com.azure.search.documents.indexes.models.SearchServiceLimits; -import com.azure.search.documents.indexes.models.SearchServiceStatistics; -import com.azure.search.documents.indexes.models.SynonymMap; -import com.azure.search.documents.indexes.models.WebApiSkill; -import com.azure.search.documents.models.Hotel; -import com.azure.search.documents.models.IndexDocumentsResult; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; - -/** - * This scenario assumes an existing search solution, with index and an indexer setup (see LifecycleSetupExample) For - * more information visit Azure AI Search - * Sample Data. - */ -public class RefineSearchCapabilitiesExample { - - /** - * From the Azure portal, get your Azure AI Search service URL and API admin key, and set the values of these - * environment variables: - */ - private static final String ENDPOINT = Configuration.getGlobalConfiguration().get("AZURE_COGNITIVE_SEARCH_ENDPOINT"); - private static final String ADMIN_KEY = Configuration.getGlobalConfiguration().get("AZURE_COGNITIVE_SEARCH_ADMIN_KEY"); - - private static final String INDEX_NAME = "hotels-sample-index"; - private static final String INDEXER_NAME = "hotels-sample-indexer"; - - public static void main(String[] args) { - SearchIndexClient searchIndexClient = createIndexClient(); - SearchIndexerClient searchIndexerClient = createIndexerClient(); - SearchClient indexClient = createSearchClient(); - - // Add a synonym map to an index field - addSynonymMapToIndex(searchIndexClient); - - // Add a custom web based skillset to the indexer - addCustomWebSkillset(searchIndexerClient); - - // Manually add a set of documents to the index - uploadDocumentsToIndex(indexClient); - - // Retrieve service statistics - getServiceStatistics(searchIndexClient); - } - - private static void addCustomWebSkillset(SearchIndexerClient client) { - String skillsetName = "custom-web-skillset"; - List inputs = Collections.singletonList( - new InputFieldMappingEntry("text") - .setSource("/document/Description") - ); - - List outputs = Collections.singletonList( - new OutputFieldMappingEntry("textItems") - .setTargetName("TextItems") - ); - - HashMap headers = new HashMap<>(); - headers.put("Ocp-Apim-Subscription-Key", "Bing entity search API key"); - - SearchIndexerSkill webApiSkill = new WebApiSkill(inputs, outputs, - "https://api.cognitive.microsoft.com/bing/v7.0/entities/") - .setHttpMethod("POST") // Supports only "POST" and "PUT" HTTP methods - .setHttpHeaders(headers) - .setName("webapi-skill") - .setDescription("A WebApi skill that can be used as a custom skillset"); - - SearchIndexerSkillset skillset = new SearchIndexerSkillset(skillsetName, Collections.singletonList(webApiSkill)) - .setDescription("Skillset for testing custom skillsets"); - - client.createOrUpdateSkillset(skillset); - System.out.printf("Created Skillset %s%n", skillsetName); - - SearchIndexer indexer = client.getIndexer(INDEXER_NAME).setSkillsetName(skillsetName); - client.createOrUpdateIndexer(indexer); - System.out.printf("Updated Indexer %s with Skillset %s%n", INDEXER_NAME, skillsetName); - } - - private static void getServiceStatistics(SearchIndexClient client) { - SearchServiceStatistics statistics = client.getServiceStatistics(); - SearchServiceCounters counters = statistics.getCounters(); - SearchServiceLimits limits = statistics.getLimits(); - - System.out.println("Service Statistics:"); - System.out.printf(" Documents quota: %d, documents usage: %d%n", counters.getDocumentCounter().getQuota(), counters.getDocumentCounter().getUsage()); - System.out.printf(" Max fields per index limit: %d%n", limits.getMaxFieldsPerIndex()); - - } - - private static void uploadDocumentsToIndex(SearchClient client) { - - List hotels = new ArrayList<>(); - hotels.add(new Hotel().setHotelId("100")); - hotels.add(new Hotel().setHotelId("200")); - hotels.add(new Hotel().setHotelId("300")); - - // Perform index operations on a list of documents - IndexDocumentsResult result = client.mergeOrUploadDocuments(hotels); - System.out.printf("Indexed %s documents%n", result.getResults().size()); - } - - private static void addSynonymMapToIndex(SearchIndexClient client) { - String synonymMapName = "hotel-synonym-sample"; - SynonymMap synonymMap = new SynonymMap(synonymMapName, - "hotel, motel\ninternet,wifi\nfive star=>luxury\neconomy,inexpensive=>budget"); - - client.createOrUpdateSynonymMap(synonymMap); - - SearchIndex index = client.getIndex(INDEX_NAME); - List fields = index.getFields(); - fields.get(1).setSynonymMapNames(synonymMapName); - index.setFields(fields); - - client.createOrUpdateIndex(index); - System.out.printf("Updated index %s with synonym map %s on field %s%n", INDEX_NAME, synonymMapName, "HotelName"); - } - - private static SearchIndexClient createIndexClient() { - return new SearchIndexClientBuilder() - .endpoint(ENDPOINT) - .credential(new AzureKeyCredential(ADMIN_KEY)) - .buildClient(); - } - - private static SearchIndexerClient createIndexerClient() { - return new SearchIndexerClientBuilder() - .endpoint(ENDPOINT) - .credential(new AzureKeyCredential(ADMIN_KEY)) - .buildClient(); - } - - private static SearchClient createSearchClient() { - return new SearchClientBuilder() - .endpoint(ENDPOINT) - .credential(new AzureKeyCredential(ADMIN_KEY)) - .indexName(INDEX_NAME) - .buildClient(); - } -} diff --git a/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/RunningSearchSolutionExample.java b/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/RunningSearchSolutionExample.java deleted file mode 100644 index ece4284031ee..000000000000 --- a/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/RunningSearchSolutionExample.java +++ /dev/null @@ -1,139 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.search.documents; - -import com.azure.core.credential.AzureKeyCredential; -import com.azure.core.http.rest.PagedIterableBase; -import com.azure.core.util.Configuration; -import com.azure.core.util.Context; -import com.azure.search.documents.indexes.SearchIndexClient; -import com.azure.search.documents.indexes.SearchIndexClientBuilder; -import com.azure.search.documents.indexes.SearchIndexerClient; -import com.azure.search.documents.indexes.SearchIndexerClientBuilder; -import com.azure.search.documents.indexes.models.SearchIndexStatistics; -import com.azure.search.documents.indexes.models.SearchIndexerStatus; -import com.azure.search.documents.models.AutocompleteItem; -import com.azure.search.documents.models.AutocompleteMode; -import com.azure.search.documents.models.AutocompleteOptions; -import com.azure.search.documents.models.SearchOptions; -import com.azure.search.documents.models.SuggestOptions; -import com.azure.search.documents.models.SuggestResult; -import com.azure.search.documents.util.AutocompletePagedResponse; -import com.azure.search.documents.util.SearchPagedIterable; -import com.azure.search.documents.util.SuggestPagedResponse; - -import java.util.Iterator; - -/** - * This scenario assumes an existing search solution, with index and an indexer setup (see LifecycleSetupExample) - * Azure AI Search Sample Data. - */ -public class RunningSearchSolutionExample { - - /** - * From the Azure portal, get your Azure AI Search service URL and API admin key, and set the values of these - * environment variables: - */ - private static final String ENDPOINT = Configuration.getGlobalConfiguration().get("AZURE_COGNITIVE_SEARCH_ENDPOINT"); - private static final String ADMIN_KEY = Configuration.getGlobalConfiguration().get("AZURE_COGNITIVE_SEARCH_ADMIN_KEY"); - - private static final String INDEX_NAME = "hotels-sample-index"; - private static final String INDEXER_NAME = "hotels-sample-indexer"; - private static final String SUGGESTER_NAME = "sg"; - - public static void main(String[] args) { - SearchIndexClient searchIndexClient = createIndexClient(); - SearchIndexerClient searchIndexerClient = createIndexerClient(); - SearchClient indexClient = createSearchClient(); - - // get index statistics - SearchIndexStatistics indexStatistics = searchIndexClient.getIndexStatistics(INDEX_NAME); - System.out.printf("Index %s: Document Count = %d, Storage Size = %d%n", INDEX_NAME, indexStatistics.getDocumentCount(), indexStatistics.getStorageSize()); - - // run indexer - searchIndexerClient.runIndexer(INDEXER_NAME); - - // get indexer status - SearchIndexerStatus indexerStatus = searchIndexerClient.getIndexerStatus(INDEXER_NAME); - System.out.printf("Indexer %s status = %s%n", INDEXER_NAME, indexerStatus.getStatus()); - - // run a search query - searchQuery(indexClient); - - // run an autocomplete query - autocompleteQuery(indexClient); - - // run a suggest query with fuzzy matching - suggestQuery(indexClient); - - } - - private static void suggestQuery(SearchClient client) { - - SuggestOptions suggestOptions = new SuggestOptions() - .setUseFuzzyMatching(true); - - PagedIterableBase suggestResult = client.suggest("vew", - SUGGESTER_NAME, suggestOptions, Context.NONE); - Iterator iterator = suggestResult.iterableByPage().iterator(); - - System.out.println("Suggest with fuzzy matching:"); - iterator.forEachRemaining( - r -> r.getValue().forEach( - res -> System.out.printf(" Found match to: %s, match = %s%n", (String) res - .getDocument(SearchDocument.class).get("HotelName"), res.getText()) - ) - ); - } - - private static void autocompleteQuery(SearchClient client) { - - AutocompleteOptions params = new AutocompleteOptions().setAutocompleteMode( - AutocompleteMode.ONE_TERM_WITH_CONTEXT); - - PagedIterableBase results = client.autocomplete("co", - SUGGESTER_NAME, params, Context.NONE); - - System.out.println("Autocomplete with one term context results:"); - results.forEach(result -> System.out.println(result.getText())); - } - - private static void searchQuery(SearchClient client) { - - // search=Resort&searchfields=HotelName&$count=true - SearchOptions searchOptions = new SearchOptions() - .setIncludeTotalCount(true) - .setSearchFields("HotelName"); - SearchPagedIterable searchResults = client.search("Resort", searchOptions, Context.NONE); - - System.out.println("Search query results:"); - searchResults.forEach(result -> { - SearchDocument doc = result.getDocument(SearchDocument.class); - String hotelName = (String) doc.get("HotelName"); - System.out.printf(" Hotel: %s%n", hotelName); - }); - } - - private static SearchClient createSearchClient() { - return new SearchClientBuilder() - .endpoint(ENDPOINT) - .credential(new AzureKeyCredential(ADMIN_KEY)) - .indexName(INDEX_NAME) - .buildClient(); - } - - private static SearchIndexClient createIndexClient() { - return new SearchIndexClientBuilder() - .endpoint(ENDPOINT) - .credential(new AzureKeyCredential(ADMIN_KEY)) - .buildClient(); - } - - private static SearchIndexerClient createIndexerClient() { - return new SearchIndexerClientBuilder() - .endpoint(ENDPOINT) - .credential(new AzureKeyCredential(ADMIN_KEY)) - .buildClient(); - } -} diff --git a/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/SearchAsyncWithFullyTypedDocumentsExample.java b/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/SearchAsyncWithFullyTypedDocumentsExample.java deleted file mode 100644 index b19f9b4ee6de..000000000000 --- a/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/SearchAsyncWithFullyTypedDocumentsExample.java +++ /dev/null @@ -1,62 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.search.documents; - -import com.azure.core.credential.AzureKeyCredential; -import com.azure.core.util.Configuration; -import com.azure.search.documents.models.Hotel; -import com.azure.search.documents.util.SearchPagedFlux; -import com.fasterxml.jackson.databind.DeserializationFeature; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; - -import java.text.SimpleDateFormat; -import java.util.TimeZone; - -/** - * This example shows how to convert a search result into a fully typed object. - * In case that the searched document schema is known, the user can convert the result of the search query from a property bag into a fully typed object - * In this sample, the deserialization into well known type is done using Jackson ObjectMapper - *

- * This sample is based on the hotels-sample index available to install from the portal. - * See https://docs.microsoft.com/azure/search/search-get-started-portal - */ -public class SearchAsyncWithFullyTypedDocumentsExample { - - /** - * From the Azure portal, get your Azure AI Search service URL and API key, - * and set the values of these environment variables: - */ - private static final String ENDPOINT = Configuration.getGlobalConfiguration().get("AZURE_COGNITIVE_SEARCH_ENDPOINT"); - private static final String API_KEY = Configuration.getGlobalConfiguration().get("AZURE_COGNITIVE_SEARCH_API_KEY"); - - private static final String INDEX_NAME = "hotels-sample-index"; - - public static void main(String[] args) { - SearchAsyncClient searchClient = new SearchClientBuilder() - .endpoint(ENDPOINT) - .credential(new AzureKeyCredential(API_KEY)) - .indexName(INDEX_NAME) - .buildAsyncClient(); - - ObjectMapper objectMapper = new ObjectMapper(); - SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'"); - df.setTimeZone(TimeZone.getDefault()); - objectMapper.setDateFormat(df); - objectMapper.registerModule(new JavaTimeModule()); - objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); - - SearchPagedFlux results = searchClient.search("searchText"); - results - .subscribe(item -> { - SearchDocument searchDocument = item.getDocument(SearchDocument.class); - // Convert the property bag received from the search query to an object of type Hotel - Hotel hotel = objectMapper.convertValue(searchDocument, Hotel.class); - System.out.println("Hotel " + hotel.getHotelId()); - }); - - results.blockLast(); - - } -} diff --git a/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/SearchForDynamicDocumentsExample.java b/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/SearchForDynamicDocumentsExample.java deleted file mode 100644 index 3bc2a5542152..000000000000 --- a/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/SearchForDynamicDocumentsExample.java +++ /dev/null @@ -1,101 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.search.documents; - -import com.azure.core.credential.AzureKeyCredential; -import com.azure.core.util.Configuration; -import com.azure.core.util.Context; -import com.azure.search.documents.models.SearchOptions; -import com.azure.search.documents.models.SearchResult; -import reactor.core.publisher.Flux; - -/** - * This example shows how to perform basic searches using the Azure AI Search SDK for Java - *

- * This sample is based on the hotels-sample index available to install from the portal. - * See https://docs.microsoft.com/azure/search/search-get-started-portal - */ -public class SearchForDynamicDocumentsExample { - - /** - * From the Azure portal, get your Azure AI Search service URL and API key, - * and set the values of these environment variables: - */ - private static final String ENDPOINT = Configuration.getGlobalConfiguration().get("AZURE_COGNITIVE_SEARCH_ENDPOINT"); - private static final String API_KEY = Configuration.getGlobalConfiguration().get("AZURE_COGNITIVE_SEARCH_API_KEY"); - - private static final String INDEX_NAME = "hotels-sample-index"; - - public static void main(String[] args) { - searchWithSyncClient(); - searchWithAsyncClient(); - } - - /** - * Minimal search with {@link SearchClient} - * Search for luxury hotels print all results to the console - */ - private static void searchWithSyncClient() { - SearchClient client = new SearchClientBuilder() - .endpoint(ENDPOINT) - .credential(new AzureKeyCredential(API_KEY)) - .indexName(INDEX_NAME) - .buildClient(); - - // Perform a text-based search - for (SearchResult result : client.search("luxury hotel", - new SearchOptions(), Context.NONE)) { - - // Each result is a dynamic Map - SearchDocument doc = result.getDocument(SearchDocument.class); - String hotelName = (String) doc.get("HotelName"); - Double rating = (Double) doc.get("Rating"); - - System.out.printf("%s: %s%n", hotelName, rating); - } - } - - /** - * Additional search options and results processing using {@link SearchAsyncClient} - * Search for the top 5 rated luxury hotels near Redmond and print all results to the console - */ - private static void searchWithAsyncClient() { - SearchAsyncClient client = new SearchClientBuilder() - .endpoint(ENDPOINT) - .credential(new AzureKeyCredential(API_KEY)) - .indexName(INDEX_NAME) - .buildAsyncClient(); - - // Add additional options for the search - SearchOptions parameters = new SearchOptions() - .setFilter("geo.distance(Location,geography'POINT(-122.121513 47.673988)') le 5") // items having a geo-location distance which is less than 5 km from Redmond - .setFacets("Tags,sort:value") - .setOrderBy("Rating") - .setTop(5) - .setIncludeTotalCount(true); - - // Perform a search and subscribe to the results and log additional information - Flux results = client.search("hotel", parameters) - .log() - .doOnSubscribe(__ -> System.out.println("Subscribed to PagedFlux results")); - - // Subscribe and process all results across all pages in the response - results.subscribe( - result -> { - SearchDocument doc = result.getDocument(SearchDocument.class); - String hotelName = (String) doc.get("HotelName"); - Integer rating = (Integer) doc.get("Rating"); - - System.out.printf("%s: %d%n", hotelName, rating); - }, - err -> System.out.printf("error: %s%n", err), - () -> System.out.println("Completed processing")); - - /* - This will block until the above query has completed. This is strongly discouraged for use in production as - it eliminates the benefits of asynchronous IO. It is used here to ensure the sample runs to completion. - */ - results.blockLast(); - } -} diff --git a/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/SearchJavaDocCodeSnippets.java b/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/SearchJavaDocCodeSnippets.java deleted file mode 100644 index c059e375dd61..000000000000 --- a/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/SearchJavaDocCodeSnippets.java +++ /dev/null @@ -1,2656 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.search.documents; - -import com.azure.core.credential.AzureKeyCredential; -import com.azure.core.http.rest.PagedIterable; -import com.azure.core.http.rest.Response; -import com.azure.core.util.Context; -import com.azure.search.documents.indexes.SearchIndexAsyncClient; -import com.azure.search.documents.indexes.SearchIndexClient; -import com.azure.search.documents.indexes.SearchIndexClientBuilder; -import com.azure.search.documents.indexes.SearchIndexerAsyncClient; -import com.azure.search.documents.indexes.SearchIndexerClient; -import com.azure.search.documents.indexes.SearchIndexerClientBuilder; -import com.azure.search.documents.indexes.models.AnalyzeTextOptions; -import com.azure.search.documents.indexes.models.AnalyzedTokenInfo; -import com.azure.search.documents.indexes.models.FieldMapping; -import com.azure.search.documents.indexes.models.IndexDocumentsBatch; -import com.azure.search.documents.indexes.models.InputFieldMappingEntry; -import com.azure.search.documents.indexes.models.LexicalTokenizerName; -import com.azure.search.documents.indexes.models.OcrSkill; -import com.azure.search.documents.indexes.models.OutputFieldMappingEntry; -import com.azure.search.documents.indexes.models.SearchField; -import com.azure.search.documents.indexes.models.SearchFieldDataType; -import com.azure.search.documents.indexes.models.SearchIndex; -import com.azure.search.documents.indexes.models.SearchIndexStatistics; -import com.azure.search.documents.indexes.models.SearchIndexer; -import com.azure.search.documents.indexes.models.SearchIndexerDataContainer; -import com.azure.search.documents.indexes.models.SearchIndexerDataSourceConnection; -import com.azure.search.documents.indexes.models.SearchIndexerDataSourceType; -import com.azure.search.documents.indexes.models.SearchIndexerSkillset; -import com.azure.search.documents.indexes.models.SearchIndexerStatus; -import com.azure.search.documents.indexes.models.SearchServiceStatistics; -import com.azure.search.documents.indexes.models.SearchSuggester; -import com.azure.search.documents.indexes.models.SynonymMap; -import com.azure.search.documents.models.AutocompleteItem; -import com.azure.search.documents.models.AutocompleteMode; -import com.azure.search.documents.models.AutocompleteOptions; -import com.azure.search.documents.models.IndexDocumentsOptions; -import com.azure.search.documents.models.IndexDocumentsResult; -import com.azure.search.documents.models.IndexingResult; -import com.azure.search.documents.models.SearchOptions; -import com.azure.search.documents.models.SearchResult; -import com.azure.search.documents.models.SuggestOptions; -import com.azure.search.documents.models.SuggestResult; -import com.azure.search.documents.util.AutocompletePagedIterable; -import com.azure.search.documents.util.SearchPagedFlux; -import com.azure.search.documents.util.SearchPagedIterable; -import com.azure.search.documents.util.SearchPagedResponse; -import com.azure.search.documents.util.SuggestPagedIterable; - -import java.util.Arrays; -import java.util.Collections; -import java.util.List; -import java.util.Map; -import java.util.concurrent.atomic.AtomicLong; - -@SuppressWarnings("unused") -public class SearchJavaDocCodeSnippets { - private static final SearchClient SEARCH_CLIENT = new SearchClientBuilder().buildClient(); - private static final long SEARCH_SKIP_LIMIT = 100_000; // May change over time - - /** - * Code snippet for creating a {@link SearchClient}. - */ - public void createSearchClientFromBuilder() { - // BEGIN: com.azure.search.documents.SearchClient.instantiation - SearchClient searchClient = new SearchClientBuilder() - .credential(new AzureKeyCredential("{key}")) - .endpoint("{endpoint}") - .indexName("{indexName}") - .buildClient(); - // END: com.azure.search.documents.SearchClient.instantiation - } - - /** - * Code snippet for {@link SearchClient#uploadDocuments(Iterable)}. - */ - public void uploadDocuments() { - // BEGIN: com.azure.search.documents.SearchClient.uploadDocuments#Iterable - SearchDocument searchDocument = new SearchDocument(); - searchDocument.put("hotelId", "1"); - searchDocument.put("hotelName", "test"); - IndexDocumentsResult result = SEARCH_CLIENT.uploadDocuments(Collections.singletonList(searchDocument)); - for (IndexingResult indexingResult : result.getResults()) { - System.out.printf("Does document with key %s upload successfully? %b%n", indexingResult.getKey(), - indexingResult.isSucceeded()); - } - // END: com.azure.search.documents.SearchClient.uploadDocuments#Iterable - } - - /** - * Code snippet for {@link SearchClient#uploadDocumentsWithResponse(Iterable, IndexDocumentsOptions, Context)} - */ - public void uploadDocumentsWithResponse() { - // BEGIN: com.azure.search.documents.SearchClient.uploadDocumentsWithResponse#Iterable-IndexDocumentsOptions-Context - SearchDocument searchDocument = new SearchDocument(); - searchDocument.put("hotelId", "1"); - searchDocument.put("hotelName", "test"); - Response resultResponse = SEARCH_CLIENT.uploadDocumentsWithResponse( - Collections.singletonList(searchDocument), null, new Context(KEY_1, VALUE_1)); - System.out.println("The status code of the response is " + resultResponse.getStatusCode()); - for (IndexingResult indexingResult : resultResponse.getValue().getResults()) { - System.out.printf("Does document with key %s upload successfully? %b%n", indexingResult.getKey(), - indexingResult.isSucceeded()); - } - // END: com.azure.search.documents.SearchClient.uploadDocumentsWithResponse#Iterable-IndexDocumentsOptions-Context - } - - /** - * Code snippet for {@link SearchClient#mergeDocuments(Iterable)} - */ - public void mergeDocuments() { - // BEGIN: com.azure.search.documents.SearchClient.mergeDocuments#Iterable - SearchDocument searchDocument = new SearchDocument(); - searchDocument.put("hotelName", "merge"); - IndexDocumentsResult result = SEARCH_CLIENT.mergeDocuments(Collections.singletonList(searchDocument)); - for (IndexingResult indexingResult : result.getResults()) { - System.out.printf("Does document with key %s merge successfully? %b%n", indexingResult.getKey(), - indexingResult.isSucceeded()); - } - // END: com.azure.search.documents.SearchClient.mergeDocuments#Iterable - } - - /** - * Code snippet for {@link SearchClient#mergeDocumentsWithResponse(Iterable, IndexDocumentsOptions, Context)} - */ - public void mergeDocumentsWithResponse() { - // BEGIN: com.azure.search.documents.SearchClient.mergeDocumentsWithResponse#Iterable-IndexDocumentsOptions-Context - SearchDocument searchDocument = new SearchDocument(); - searchDocument.put("hotelName", "test"); - Response resultResponse = SEARCH_CLIENT.mergeDocumentsWithResponse( - Collections.singletonList(searchDocument), null, new Context(KEY_1, VALUE_1)); - System.out.println("The status code of the response is " + resultResponse.getStatusCode()); - for (IndexingResult indexingResult : resultResponse.getValue().getResults()) { - System.out.printf("Does document with key %s merge successfully? %b%n", indexingResult.getKey(), - indexingResult.isSucceeded()); - } - // END: com.azure.search.documents.SearchClient.mergeDocumentsWithResponse#Iterable-IndexDocumentsOptions-Context - } - - /** - * Code snippet for {@link SearchClient#mergeOrUploadDocuments(Iterable)} - */ - public void mergeOrUploadDocuments() { - // BEGIN: com.azure.search.documents.SearchClient.mergeOrUploadDocuments#Iterable - SearchDocument searchDocument = new SearchDocument(); - searchDocument.put("hotelId", "1"); - searchDocument.put("hotelName", "test"); - IndexDocumentsResult result = SEARCH_CLIENT.mergeOrUploadDocuments(Collections.singletonList(searchDocument)); - for (IndexingResult indexingResult : result.getResults()) { - System.out.printf("Does document with key %s mergeOrUpload successfully? %b%n", indexingResult.getKey(), - indexingResult.isSucceeded()); - } - // END: com.azure.search.documents.SearchClient.mergeOrUploadDocuments#Iterable - } - - /** - * Code snippet for {@link SearchClient#mergeOrUploadDocumentsWithResponse(Iterable, IndexDocumentsOptions, Context)} - */ - public void mergeOrUploadDocumentsWithResponse() { - // BEGIN: com.azure.search.documents.SearchClient.mergeOrUploadDocumentsWithResponse#Iterable-IndexDocumentsOptions-Context - SearchDocument searchDocument = new SearchDocument(); - searchDocument.put("hotelId", "1"); - searchDocument.put("hotelName", "test"); - Response resultResponse = SEARCH_CLIENT.mergeOrUploadDocumentsWithResponse( - Collections.singletonList(searchDocument), null, new Context(KEY_1, VALUE_1)); - System.out.println("The status code of the response is " + resultResponse.getStatusCode()); - for (IndexingResult indexingResult : resultResponse.getValue().getResults()) { - System.out.printf("Does document with key %s mergeOrUpload successfully? %b%n", indexingResult.getKey(), - indexingResult.isSucceeded()); - } - // END: com.azure.search.documents.SearchClient.mergeOrUploadDocumentsWithResponse#Iterable-IndexDocumentsOptions-Context - } - - /** - * Code snippet for {@link SearchClient#deleteDocuments(Iterable)} - */ - public void deleteDocuments() { - // BEGIN: com.azure.search.documents.SearchClient.deleteDocuments#Iterable - SearchDocument searchDocument = new SearchDocument(); - searchDocument.put("hotelId", "1"); - searchDocument.put("hotelName", "test"); - IndexDocumentsResult result = SEARCH_CLIENT.deleteDocuments(Collections.singletonList(searchDocument)); - for (IndexingResult indexingResult : result.getResults()) { - System.out.printf("Does document with key %s delete successfully? %b%n", indexingResult.getKey(), - indexingResult.isSucceeded()); - } - // END: com.azure.search.documents.SearchClient.deleteDocuments#Iterable - } - - - /** - * Code snippet for {@link SearchClient#deleteDocumentsWithResponse(Iterable, IndexDocumentsOptions, Context)} - */ - public void deleteDocumentsWithResponse() { - // BEGIN: com.azure.search.documents.SearchClient.deleteDocumentsWithResponse#Iterable-IndexDocumentsOptions-Context - SearchDocument searchDocument = new SearchDocument(); - searchDocument.put("hotelId", "1"); - searchDocument.put("hotelName", "test"); - Response resultResponse = SEARCH_CLIENT.deleteDocumentsWithResponse( - Collections.singletonList(searchDocument), null, new Context(KEY_1, VALUE_1)); - System.out.println("The status code of the response is " + resultResponse.getStatusCode()); - for (IndexingResult indexingResult : resultResponse.getValue().getResults()) { - System.out.printf("Does document with key %s delete successfully? %b%n", indexingResult.getKey(), - indexingResult.isSucceeded()); - } - // END: com.azure.search.documents.SearchClient.deleteDocumentsWithResponse#Iterable-IndexDocumentsOptions-Context - } - - /** - * Code snippet for {@link SearchClient#indexDocuments(IndexDocumentsBatch)} - */ - public void indexDocuments() { - // BEGIN: com.azure.search.documents.SearchClient.indexDocuments#IndexDocumentsBatch - SearchDocument searchDocument1 = new SearchDocument(); - searchDocument1.put("hotelId", "1"); - searchDocument1.put("hotelName", "test1"); - SearchDocument searchDocument2 = new SearchDocument(); - searchDocument2.put("hotelId", "2"); - searchDocument2.put("hotelName", "test2"); - IndexDocumentsBatch indexDocumentsBatch = new IndexDocumentsBatch<>(); - indexDocumentsBatch.addUploadActions(Collections.singletonList(searchDocument1)); - indexDocumentsBatch.addDeleteActions(Collections.singletonList(searchDocument2)); - IndexDocumentsResult result = SEARCH_CLIENT.indexDocuments(indexDocumentsBatch); - for (IndexingResult indexingResult : result.getResults()) { - System.out.printf("Does document with key %s finish successfully? %b%n", indexingResult.getKey(), - indexingResult.isSucceeded()); - } - // END: com.azure.search.documents.SearchClient.indexDocuments#IndexDocumentsBatch - } - - /** - * Code snippet for {@link SearchClient#indexDocumentsWithResponse(IndexDocumentsBatch, IndexDocumentsOptions, Context)} - */ - public void indexDocumentsWithResponse() { - // BEGIN: com.azure.search.documents.SearchClient.indexDocumentsWithResponse#IndexDocumentsBatch-IndexDocumentsOptions-Context - SearchDocument searchDocument1 = new SearchDocument(); - searchDocument1.put("hotelId", "1"); - searchDocument1.put("hotelName", "test1"); - SearchDocument searchDocument2 = new SearchDocument(); - searchDocument2.put("hotelId", "2"); - searchDocument2.put("hotelName", "test2"); - IndexDocumentsBatch indexDocumentsBatch = new IndexDocumentsBatch<>(); - indexDocumentsBatch.addUploadActions(Collections.singletonList(searchDocument1)); - indexDocumentsBatch.addDeleteActions(Collections.singletonList(searchDocument2)); - Response resultResponse = SEARCH_CLIENT.indexDocumentsWithResponse(indexDocumentsBatch, - null, new Context(KEY_1, VALUE_1)); - System.out.println("The status code of the response is " + resultResponse.getStatusCode()); - for (IndexingResult indexingResult : resultResponse.getValue().getResults()) { - System.out.printf("Does document with key %s finish successfully? %b%n", indexingResult.getKey(), - indexingResult.isSucceeded()); - } - // END: com.azure.search.documents.SearchClient.indexDocumentsWithResponse#IndexDocumentsBatch-IndexDocumentsOptions-Context - } - - /** - * Code snippet for {@link SearchClient#getDocument(String, Class)} - */ - public void getDocuments() { - // BEGIN: com.azure.search.documents.SearchClient.getDocuments#String-Class - SearchDocument result = SEARCH_CLIENT.getDocument("hotelId", SearchDocument.class); - for (Map.Entry keyValuePair : result.entrySet()) { - System.out.printf("Document key %s, Document value %s", keyValuePair.getKey(), keyValuePair.getValue()); - } - // END: com.azure.search.documents.SearchClient.getDocuments#String-Class - } - - /** - * Code snippet for {@link SearchClient#getDocumentWithResponse(String, Class, List, Context)} - */ - public void getDocumentsWithResponse() { - // BEGIN: com.azure.search.documents.SearchClient.getDocumentWithResponse#String-Class-List-Context - Response resultResponse = SEARCH_CLIENT.getDocumentWithResponse("hotelId", - SearchDocument.class, null, new Context(KEY_1, VALUE_1)); - System.out.println("The status code of the response is " + resultResponse.getStatusCode()); - for (Map.Entry keyValuePair : resultResponse.getValue().entrySet()) { - System.out.printf("Document key %s, Document value %s", keyValuePair.getKey(), keyValuePair.getValue()); - } - // END: com.azure.search.documents.SearchClient.getDocumentWithResponse#String-Class-List-Context - } - - /** - * Code snippet for {@link SearchClient#getDocumentCount()} - */ - public void getDocumentCount() { - // BEGIN: com.azure.search.documents.SearchClient.getDocumentCount - long count = SEARCH_CLIENT.getDocumentCount(); - System.out.printf("There are %d documents in service.", count); - // END: com.azure.search.documents.SearchClient.getDocumentCount - } - - /** - * Code snippet for {@link SearchClient#getDocumentCountWithResponse(Context)} - */ - public void getDocumentCountWithResponse() { - // BEGIN: com.azure.search.documents.SearchClient.getDocumentCountWithResponse#Context - Response countResponse = SEARCH_CLIENT.getDocumentCountWithResponse(new Context(KEY_1, VALUE_1)); - System.out.println("The status code of the response is " + countResponse.getStatusCode()); - System.out.printf("There are %d documents in service.", countResponse.getValue()); - // END: com.azure.search.documents.SearchClient.getDocumentCountWithResponse#Context - } - - /** - * Code snippet for {@link SearchClient#search(String)} - */ - public void searchDocuments() { - // BEGIN: com.azure.search.documents.SearchClient.search#String - SearchPagedIterable searchPagedIterable = SEARCH_CLIENT.search("searchText"); - System.out.printf("There are around %d results.", searchPagedIterable.getTotalCount()); - - long numberOfDocumentsReturned = 0; - for (SearchPagedResponse resultResponse: searchPagedIterable.iterableByPage()) { - System.out.println("The status code of the response is " + resultResponse.getStatusCode()); - numberOfDocumentsReturned += resultResponse.getValue().size(); - resultResponse.getValue().forEach(searchResult -> { - for (Map.Entry keyValuePair: searchResult - .getDocument(SearchDocument.class).entrySet()) { - System.out.printf("Document key %s, document value %s", keyValuePair.getKey(), - keyValuePair.getValue()); - } - }); - - if (numberOfDocumentsReturned >= SEARCH_SKIP_LIMIT) { - // Reached the $skip limit, stop requesting more documents. - break; - } - } - // END: com.azure.search.documents.SearchClient.search#String - } - - /** - * Code snippet for {@link SearchClient#search(String, SearchOptions, Context)} - */ - public void searchDocumentsWithOptions() { - // BEGIN: com.azure.search.documents.SearchClient.search#String-SearchOptions-Context - SearchPagedIterable searchPagedIterable = SEARCH_CLIENT.search("searchText", - new SearchOptions().setOrderBy("hotelId desc"), new Context(KEY_1, VALUE_1)); - System.out.printf("There are around %d results.", searchPagedIterable.getTotalCount()); - - long numberOfDocumentsReturned = 0; - for (SearchPagedResponse resultResponse: searchPagedIterable.iterableByPage()) { - System.out.println("The status code of the response is " + resultResponse.getStatusCode()); - numberOfDocumentsReturned += resultResponse.getValue().size(); - resultResponse.getValue().forEach(searchResult -> { - for (Map.Entry keyValuePair: searchResult - .getDocument(SearchDocument.class).entrySet()) { - System.out.printf("Document key %s, document value %s", keyValuePair.getKey(), - keyValuePair.getValue()); - } - }); - - if (numberOfDocumentsReturned >= SEARCH_SKIP_LIMIT) { - // Reached the $skip limit, stop requesting more documents. - break; - } - } - // END: com.azure.search.documents.SearchClient.search#String-SearchOptions-Context - } - - /** - * Code snippet for {@link SearchClient#suggest(String, String)} - */ - public void suggestDocuments() { - // BEGIN: com.azure.search.documents.SearchClient.suggest#String-String - SuggestPagedIterable suggestPagedIterable = SEARCH_CLIENT.suggest("searchText", "sg"); - for (SuggestResult result: suggestPagedIterable) { - SearchDocument searchDocument = result.getDocument(SearchDocument.class); - for (Map.Entry keyValuePair: searchDocument.entrySet()) { - System.out.printf("Document key %s, document value %s", keyValuePair.getKey(), keyValuePair.getValue()); - } - } - // END: com.azure.search.documents.SearchClient.suggest#String-String - } - - /** - * Code snippet for {@link SearchClient#suggest(String, String, SuggestOptions, Context)} - */ - public void suggestDocumentsWithOptions() { - // BEGIN: com.azure.search.documents.SearchClient.suggest#String-String-SuggestOptions-Context - SuggestPagedIterable suggestPagedIterable = SEARCH_CLIENT.suggest("searchText", "sg", - new SuggestOptions().setOrderBy("hotelId desc"), new Context(KEY_1, VALUE_1)); - for (SuggestResult result: suggestPagedIterable) { - SearchDocument searchDocument = result.getDocument(SearchDocument.class); - for (Map.Entry keyValuePair: searchDocument.entrySet()) { - System.out.printf("Document key %s, document value %s", keyValuePair.getKey(), keyValuePair.getValue()); - } - } - // END: com.azure.search.documents.SearchClient.suggest#String-String-SuggestOptions-Context - } - - /** - * Code snippet for {@link SearchClient#autocomplete(String, String)} - */ - public void autocompleteDocuments() { - // BEGIN: com.azure.search.documents.SearchClient.autocomplete#String-String - AutocompletePagedIterable autocompletePagedIterable = SEARCH_CLIENT.autocomplete("searchText", "sg"); - for (AutocompleteItem result: autocompletePagedIterable) { - System.out.printf("The complete term is %s", result.getText()); - } - // END: com.azure.search.documents.SearchClient.autocomplete#String-String - } - - /** - * Code snippet for {@link SearchClient#autocomplete(String, String, AutocompleteOptions, Context)} - */ - public void autocompleteDocumentsWithOptions() { - // BEGIN: com.azure.search.documents.SearchClient.autocomplete#String-String-AutocompleteOptions-Context - AutocompletePagedIterable autocompletePagedIterable = SEARCH_CLIENT.autocomplete("searchText", "sg", - new AutocompleteOptions().setAutocompleteMode(AutocompleteMode.ONE_TERM_WITH_CONTEXT), - new Context(KEY_1, VALUE_1)); - for (AutocompleteItem result: autocompletePagedIterable) { - System.out.printf("The complete term is %s", result.getText()); - } - // END: com.azure.search.documents.SearchClient.autocomplete#String-String-AutocompleteOptions-Context - } - - private static final SearchAsyncClient SEARCH_ASYNC_CLIENT = new SearchClientBuilder().buildAsyncClient(); - - /** - * Code snippet for {@link SearchAsyncClient#uploadDocuments(Iterable)}. - */ - public void uploadDocumentsAsync() { - // BEGIN: com.azure.search.documents.SearchAsyncClient.uploadDocuments#Iterable - SearchDocument searchDocument = new SearchDocument(); - searchDocument.put("hotelId", "1"); - searchDocument.put("hotelName", "test"); - SEARCH_ASYNC_CLIENT.uploadDocuments(Collections.singletonList(searchDocument)) - .subscribe(result -> { - for (IndexingResult indexingResult : result.getResults()) { - System.out.printf("Does document with key %s upload successfully? %b%n", - indexingResult.getKey(), indexingResult.isSucceeded()); - } - }); - // END: com.azure.search.documents.SearchAsyncClient.uploadDocuments#Iterable - } - - /** - * Code snippet for {@link SearchAsyncClient#uploadDocumentsWithResponse(Iterable, IndexDocumentsOptions)} - */ - public void uploadDocumentsWithResponseAsync() { - // BEGIN: com.azure.search.documents.SearchAsyncClient.uploadDocumentsWithResponse#Iterable-IndexDocumentsOptions - SearchDocument searchDocument = new SearchDocument(); - searchDocument.put("hotelId", "1"); - searchDocument.put("hotelName", "test"); - SEARCH_ASYNC_CLIENT.uploadDocumentsWithResponse(Collections.singletonList(searchDocument), null) - .subscribe(resultResponse -> { - System.out.println("The status code of the response is " + resultResponse.getStatusCode()); - for (IndexingResult indexingResult : resultResponse.getValue().getResults()) { - System.out.printf("Does document with key %s upload successfully? %b%n", indexingResult.getKey(), - indexingResult.isSucceeded()); - } - }); - // END: com.azure.search.documents.SearchAsyncClient.uploadDocumentsWithResponse#Iterable-IndexDocumentsOptions - } - - /** - * Code snippet for {@link SearchAsyncClient#mergeDocuments(Iterable)} - */ - public void mergeDocumentsAsync() { - // BEGIN: com.azure.search.documents.SearchAsyncClient.mergeDocuments#Iterable - SearchDocument searchDocument = new SearchDocument(); - searchDocument.put("hotelName", "merge"); - SEARCH_ASYNC_CLIENT.mergeDocuments(Collections.singletonList(searchDocument)) - .subscribe(result -> { - for (IndexingResult indexingResult : result.getResults()) { - System.out.printf("Does document with key %s merge successfully? %b%n", indexingResult.getKey(), - indexingResult.isSucceeded()); - } - }); - // END: com.azure.search.documents.SearchAsyncClient.mergeDocuments#Iterable - } - - /** - * Code snippet for {@link SearchAsyncClient#mergeDocumentsWithResponse(Iterable, IndexDocumentsOptions)} - */ - public void mergeDocumentsWithResponseAsync() { - // BEGIN: com.azure.search.documents.SearchAsyncClient.mergeDocumentsWithResponse#Iterable-IndexDocumentsOptions - SearchDocument searchDocument = new SearchDocument(); - searchDocument.put("hotelName", "test"); - SEARCH_ASYNC_CLIENT.mergeDocumentsWithResponse(Collections.singletonList(searchDocument), null) - .subscribe(resultResponse -> { - System.out.println("The status code of the response is " + resultResponse.getStatusCode()); - for (IndexingResult indexingResult : resultResponse.getValue().getResults()) { - System.out.printf("Does document with key %s merge successfully? %b%n", indexingResult.getKey(), - indexingResult.isSucceeded()); - } - }); - // END: com.azure.search.documents.SearchAsyncClient.mergeDocumentsWithResponse#Iterable-IndexDocumentsOptions - } - - /** - * Code snippet for {@link SearchAsyncClient#mergeOrUploadDocuments(Iterable)} - */ - public void mergeOrUploadDocumentsAsync() { - // BEGIN: com.azure.search.documents.SearchAsyncClient.mergeOrUploadDocuments#Iterable - SearchDocument searchDocument = new SearchDocument(); - searchDocument.put("hotelId", "1"); - searchDocument.put("hotelName", "test"); - SEARCH_ASYNC_CLIENT.mergeOrUploadDocuments(Collections.singletonList(searchDocument)) - .subscribe(result -> { - for (IndexingResult indexingResult : result.getResults()) { - System.out.printf("Does document with key %s mergeOrUpload successfully? %b%n", - indexingResult.getKey(), indexingResult.isSucceeded()); - } - }); - // END: com.azure.search.documents.SearchAsyncClient.mergeOrUploadDocuments#Iterable - } - - /** - * Code snippet for {@link SearchAsyncClient#mergeOrUploadDocumentsWithResponse(Iterable, IndexDocumentsOptions)} - */ - public void mergeOrUploadDocumentsWithResponseAsync() { - // BEGIN: com.azure.search.documents.SearchAsyncClient.mergeOrUploadDocumentsWithResponse#Iterable-IndexDocumentsOptions - SearchDocument searchDocument = new SearchDocument(); - searchDocument.put("hotelId", "1"); - searchDocument.put("hotelName", "test"); - SEARCH_ASYNC_CLIENT.mergeOrUploadDocumentsWithResponse(Collections.singletonList(searchDocument), null) - .subscribe(resultResponse -> { - System.out.println("The status code of the response is " + resultResponse.getStatusCode()); - for (IndexingResult indexingResult : resultResponse.getValue().getResults()) { - System.out.printf("Does document with key %s mergeOrUpload successfully? %b%n", - indexingResult.getKey(), indexingResult.isSucceeded()); - } - }); - // END: com.azure.search.documents.SearchAsyncClient.mergeOrUploadDocumentsWithResponse#Iterable-IndexDocumentsOptions - } - - /** - * Code snippet for {@link SearchAsyncClient#deleteDocuments(Iterable)} - */ - public void deleteDocumentsAsync() { - // BEGIN: com.azure.search.documents.SearchAsyncClient.deleteDocuments#Iterable - SearchDocument searchDocument = new SearchDocument(); - searchDocument.put("hotelId", "1"); - searchDocument.put("hotelName", "test"); - SEARCH_ASYNC_CLIENT.deleteDocuments(Collections.singletonList(searchDocument)) - .subscribe(result -> { - for (IndexingResult indexingResult : result.getResults()) { - System.out.printf("Does document with key %s delete successfully? %b%n", indexingResult.getKey(), - indexingResult.isSucceeded()); - } - }); - // END: com.azure.search.documents.SearchAsyncClient.deleteDocuments#Iterable - } - - - /** - * Code snippet for {@link SearchAsyncClient#deleteDocumentsWithResponse(Iterable, IndexDocumentsOptions)} - */ - public void deleteDocumentsWithResponseAsync() { - // BEGIN: com.azure.search.documents.SearchAsyncClient.deleteDocumentsWithResponse#Iterable-IndexDocumentsOptions - SearchDocument searchDocument = new SearchDocument(); - searchDocument.put("hotelId", "1"); - searchDocument.put("hotelName", "test"); - SEARCH_ASYNC_CLIENT.deleteDocumentsWithResponse(Collections.singletonList(searchDocument), null) - .subscribe(resultResponse -> { - System.out.println("The status code of the response is " + resultResponse.getStatusCode()); - for (IndexingResult indexingResult : resultResponse.getValue().getResults()) { - System.out.printf("Does document with key %s delete successfully? %b%n", indexingResult.getKey(), - indexingResult.isSucceeded()); - } - }); - // END: com.azure.search.documents.SearchAsyncClient.deleteDocumentsWithResponse#Iterable-IndexDocumentsOptions - } - - /** - * Code snippet for {@link SearchAsyncClient#indexDocuments(IndexDocumentsBatch)} - */ - public void indexDocumentsAsync() { - // BEGIN: com.azure.search.documents.SearchAsyncClient.indexDocuments#IndexDocumentsBatch - SearchDocument searchDocument1 = new SearchDocument(); - searchDocument1.put("hotelId", "1"); - searchDocument1.put("hotelName", "test1"); - SearchDocument searchDocument2 = new SearchDocument(); - searchDocument2.put("hotelId", "2"); - searchDocument2.put("hotelName", "test2"); - IndexDocumentsBatch indexDocumentsBatch = new IndexDocumentsBatch<>(); - indexDocumentsBatch.addUploadActions(Collections.singletonList(searchDocument1)); - indexDocumentsBatch.addDeleteActions(Collections.singletonList(searchDocument2)); - SEARCH_ASYNC_CLIENT.indexDocuments(indexDocumentsBatch) - .subscribe(result -> { - for (IndexingResult indexingResult : result.getResults()) { - System.out.printf("Does document with key %s finish successfully? %b%n", indexingResult.getKey(), - indexingResult.isSucceeded()); - } - }); - // END: com.azure.search.documents.SearchAsyncClient.indexDocuments#IndexDocumentsBatch - } - - /** - * Code snippet for {@link SearchAsyncClient#indexDocumentsWithResponse(IndexDocumentsBatch, IndexDocumentsOptions)} - */ - public void indexDocumentsWithResponseAsync() { - // BEGIN: com.azure.search.documents.SearchAsyncClient.indexDocumentsWithResponse#IndexDocumentsBatch-IndexDocumentsOptions - SearchDocument searchDocument1 = new SearchDocument(); - searchDocument1.put("hotelId", "1"); - searchDocument1.put("hotelName", "test1"); - SearchDocument searchDocument2 = new SearchDocument(); - searchDocument2.put("hotelId", "2"); - searchDocument2.put("hotelName", "test2"); - IndexDocumentsBatch indexDocumentsBatch = new IndexDocumentsBatch<>(); - indexDocumentsBatch.addUploadActions(Collections.singletonList(searchDocument1)); - indexDocumentsBatch.addDeleteActions(Collections.singletonList(searchDocument2)); - SEARCH_ASYNC_CLIENT.indexDocumentsWithResponse(indexDocumentsBatch, null) - .subscribe(resultResponse -> { - System.out.println("The status code of the response is " + resultResponse.getStatusCode()); - for (IndexingResult indexingResult : resultResponse.getValue().getResults()) { - System.out.printf("Does document with key %s finish successfully? %b%n", indexingResult.getKey(), - indexingResult.isSucceeded()); - } - }); - // END: com.azure.search.documents.SearchAsyncClient.indexDocumentsWithResponse#IndexDocumentsBatch-IndexDocumentsOptions - } - - /** - * Code snippet for {@link SearchAsyncClient#getDocument(String, Class)} - */ - public void getDocumentsAsync() { - // BEGIN: com.azure.search.documents.SearchAsyncClient.getDocuments#String-Class - SEARCH_ASYNC_CLIENT.getDocument("hotelId", SearchDocument.class) - .subscribe(result -> { - for (Map.Entry keyValuePair : result.entrySet()) { - System.out.printf("Document key %s, Document value %s", keyValuePair.getKey(), - keyValuePair.getValue()); - } - }); - // END: com.azure.search.documents.SearchAsyncClient.getDocuments#String-Class - } - - /** - * Code snippet for {@link SearchAsyncClient#getDocumentWithResponse(String, Class, List)} - */ - public void getDocumentsWithResponseAsync() { - // BEGIN: com.azure.search.documents.SearchAsyncClient.getDocumentWithResponse#String-Class-List - SEARCH_ASYNC_CLIENT.getDocumentWithResponse("hotelId", SearchDocument.class, null) - .subscribe(resultResponse -> { - System.out.println("The status code of the response is " + resultResponse.getStatusCode()); - for (Map.Entry keyValuePair : resultResponse.getValue().entrySet()) { - System.out.printf("Document key %s, Document value %s", keyValuePair.getKey(), - keyValuePair.getValue()); - } - }); - // END: com.azure.search.documents.SearchAsyncClient.getDocumentWithResponse#String-Class-List - } - - /** - * Code snippet for {@link SearchAsyncClient#getDocumentCount()} - */ - public void getDocumentCountAsync() { - // BEGIN: com.azure.search.documents.SearchAsyncClient.getDocumentCount - SEARCH_ASYNC_CLIENT.getDocumentCount() - .subscribe(count -> System.out.printf("There are %d documents in service.", count)); - // END: com.azure.search.documents.SearchAsyncClient.getDocumentCount - } - - /** - * Code snippet for {@link SearchAsyncClient#getDocumentCountWithResponse()} - */ - public void getDocumentCountWithResponseAsync() { - // BEGIN: com.azure.search.documents.SearchAsyncClient.getDocumentCountWithResponse - SEARCH_ASYNC_CLIENT.getDocumentCountWithResponse() - .subscribe(countResponse -> { - System.out.println("The status code of the response is " + countResponse.getStatusCode()); - System.out.printf("There are %d documents in service.", countResponse.getValue()); - }); - // END: com.azure.search.documents.SearchAsyncClient.getDocumentCountWithResponse - } - - /** - * Code snippet for {@link SearchAsyncClient#search(String)} - */ - public void searchDocumentsAsync() { - // BEGIN: com.azure.search.documents.SearchAsyncClient.search#String - SearchPagedFlux searchPagedFlux = SEARCH_ASYNC_CLIENT.search("searchText"); - searchPagedFlux.getTotalCount().subscribe( - count -> System.out.printf("There are around %d results.", count)); - - AtomicLong numberOfDocumentsReturned = new AtomicLong(); - searchPagedFlux.byPage() - .takeUntil(page -> { - if (numberOfDocumentsReturned.addAndGet(page.getValue().size()) >= SEARCH_SKIP_LIMIT) { - // Reached the $skip limit, stop requesting more documents. - return true; - } - - return false; - }) - .subscribe(resultResponse -> { - for (SearchResult result: resultResponse.getValue()) { - SearchDocument searchDocument = result.getDocument(SearchDocument.class); - for (Map.Entry keyValuePair: searchDocument.entrySet()) { - System.out.printf("Document key %s, document value %s", keyValuePair.getKey(), keyValuePair.getValue()); - } - } - }); - // END: com.azure.search.documents.SearchAsyncClient.search#String - } - - /** - * Code snippet for {@link SearchAsyncClient#search(String, SearchOptions, Context)} - */ - public void searchDocumentsWithOptionsAsync() { - // BEGIN: com.azure.search.documents.SearchAsyncClient.search#String-SearchOptions - SearchPagedFlux pagedFlux = SEARCH_ASYNC_CLIENT.search("searchText", - new SearchOptions().setOrderBy("hotelId desc")); - - pagedFlux.getTotalCount().subscribe(count -> System.out.printf("There are around %d results.", count)); - - AtomicLong numberOfDocumentsReturned = new AtomicLong(); - pagedFlux.byPage() - .takeUntil(page -> { - if (numberOfDocumentsReturned.addAndGet(page.getValue().size()) >= SEARCH_SKIP_LIMIT) { - // Reached the $skip limit, stop requesting more documents. - return true; - } - - return false; - }) - .subscribe(searchResultResponse -> searchResultResponse.getValue().forEach(searchDocument -> { - for (Map.Entry keyValuePair - : searchDocument.getDocument(SearchDocument.class).entrySet()) { - System.out.printf("Document key %s, document value %s", keyValuePair.getKey(), - keyValuePair.getValue()); - } - })); - // END: com.azure.search.documents.SearchAsyncClient.search#String-SearchOptions - } - - /** - * Code snippet for {@link SearchAsyncClient#suggest(String, String)} - */ - public void suggestDocumentsAsync() { - // BEGIN: com.azure.search.documents.SearchAsyncClient.suggest#String-String - SEARCH_ASYNC_CLIENT.suggest("searchText", "sg") - .subscribe(results -> { - for (Map.Entry keyValuePair: results.getDocument(SearchDocument.class).entrySet()) { - System.out.printf("Document key %s, document value %s", keyValuePair.getKey(), - keyValuePair.getValue()); - } - }); - // END: com.azure.search.documents.SearchAsyncClient.suggest#String-String - } - - /** - * Code snippet for {@link SearchAsyncClient#suggest(String, String, SuggestOptions)} - */ - public void suggestDocumentsWithOptionsAsync() { - // BEGIN: com.azure.search.documents.SearchAsyncClient.suggest#String-String-SuggestOptions - SEARCH_ASYNC_CLIENT.suggest("searchText", "sg", - new SuggestOptions().setOrderBy("hotelId desc")) - .subscribe(results -> { - for (Map.Entry keyValuePair: results.getDocument(SearchDocument.class).entrySet()) { - System.out.printf("Document key %s, document value %s", keyValuePair.getKey(), - keyValuePair.getValue()); - } - }); - // END: com.azure.search.documents.SearchAsyncClient.suggest#String-String-SuggestOptions - } - - /** - * Code snippet for {@link SearchAsyncClient#autocomplete(String, String)} - */ - public void autocompleteDocumentsAsync() { - // BEGIN: com.azure.search.documents.SearchAsyncClient.autocomplete#String-String - SEARCH_ASYNC_CLIENT.autocomplete("searchText", "sg") - .subscribe(result -> System.out.printf("The complete term is %s", result.getText())); - // END: com.azure.search.documents.SearchAsyncClient.autocomplete#String-String - } - - /** - * Code snippet for {@link SearchAsyncClient#autocomplete(String, String, AutocompleteOptions)} - */ - public void autocompleteDocumentsWithOptionsAsync() { - // BEGIN: com.azure.search.documents.SearchAsyncClient.autocomplete#String-String-AutocompleteOptions - SEARCH_ASYNC_CLIENT.autocomplete("searchText", "sg", - new AutocompleteOptions().setAutocompleteMode(AutocompleteMode.ONE_TERM_WITH_CONTEXT)) - .subscribe(result -> - System.out.printf("The complete term is %s", result.getText()) - ); - // END: com.azure.search.documents.SearchAsyncClient.autocomplete#String-String-AutocompleteOptions - } - - /** - * Code snippet for creating a {@link SearchAsyncClient}. - */ - public void createSearchAsyncClientFromBuilder() { - // BEGIN: com.azure.search.documents.SearchAsyncClient.instantiation - SearchAsyncClient searchAsyncClient = new SearchClientBuilder() - .credential(new AzureKeyCredential("{key}")) - .endpoint("{endpoint}") - .indexName("{indexName}") - .buildAsyncClient(); - // END: com.azure.search.documents.SearchAsyncClient.instantiation - } - - private static final SearchIndexClient SEARCH_INDEX_CLIENT = new SearchIndexClientBuilder().buildClient(); - private static final String KEY_1 = "key1"; - private static final String VALUE_1 = "val1"; - - /** - * Code snippet for creating a {@link SearchIndexClient}. - */ - public void createSearchIndexClientFromBuilder() { - // BEGIN: com.azure.search.documents.indexes.SearchIndexClient.instantiation - SearchIndexClient searchIndexClient = new SearchIndexClientBuilder() - .credential(new AzureKeyCredential("{key}")) - .endpoint("{endpoint}") - .buildClient(); - // END: com.azure.search.documents.indexes.SearchIndexClient.instantiation - } - - /** - * Code snippet for creating {@link SearchIndexClient#createIndex(SearchIndex)}. - */ - public void createSearchIndex() { - // BEGIN: com.azure.search.documents.indexes.SearchIndexClient.createIndex#SearchIndex - List searchFields = Arrays.asList( - new SearchField("hotelId", SearchFieldDataType.STRING).setKey(true), - new SearchField("hotelName", SearchFieldDataType.STRING).setSearchable(true) - ); - SearchIndex searchIndex = new SearchIndex("searchIndex", searchFields); - SearchIndex indexFromService = SEARCH_INDEX_CLIENT.createIndex(searchIndex); - System.out.printf("The index name is %s. The ETag of index is %s.%n", indexFromService.getName(), - indexFromService.getETag()); - // END: com.azure.search.documents.indexes.SearchIndexClient.createIndex#SearchIndex - } - - /** - * Code snippet for {@link SearchIndexClient#createIndexWithResponse(SearchIndex, Context)}. - */ - public void createSearchIndexWithResponse() { - // BEGIN: com.azure.search.documents.indexes.SearchIndexClient.createIndexWithResponse#SearchIndex-Context - List searchFields = Arrays.asList( - new SearchField("hotelId", SearchFieldDataType.STRING).setKey(true), - new SearchField("hotelName", SearchFieldDataType.STRING).setSearchable(true) - ); - SearchIndex searchIndex = new SearchIndex("searchIndex", searchFields); - - Response indexFromServiceResponse = - SEARCH_INDEX_CLIENT.createIndexWithResponse(searchIndex, new Context(KEY_1, VALUE_1)); - System.out.printf("The status code of the response is %s. The index name is %s.%n", - indexFromServiceResponse.getStatusCode(), indexFromServiceResponse.getValue().getName()); - // END: com.azure.search.documents.indexes.SearchIndexClient.createIndexWithResponse#SearchIndex-Context - } - - /** - * Code snippet for {@link SearchIndexClient#getIndex(String)} - */ - public void getSearchIndex() { - // BEGIN: com.azure.search.documents.indexes.SearchIndexClient.getIndex#String - SearchIndex indexFromService = - SEARCH_INDEX_CLIENT.getIndex("searchIndex"); - System.out.printf("The index name is %s. The ETag of index is %s.%n", indexFromService.getName(), - indexFromService.getETag()); - // END: com.azure.search.documents.indexes.SearchIndexClient.getIndex#String - } - - /** - * Code snippet for {@link SearchIndexClient#getIndexWithResponse(String, Context)}} - */ - public void getSearchIndexWithResponse() { - // BEGIN: com.azure.search.documents.indexes.SearchIndexClient.getIndexWithResponse#String-Context - Response indexFromServiceResponse = - SEARCH_INDEX_CLIENT.getIndexWithResponse("searchIndex", new Context(KEY_1, VALUE_1)); - - System.out.printf("The status code of the response is %s. The index name is %s.%n", - indexFromServiceResponse.getStatusCode(), indexFromServiceResponse.getValue().getName()); - // END: com.azure.search.documents.indexes.SearchIndexClient.getIndexWithResponse#String-Context - } - - /** - * Code snippet for {@link SearchIndexClient#getIndexStatistics(String)} - */ - public void getSearchIndexStatistics() { - // BEGIN: com.azure.search.documents.indexes.SearchIndexClient.getIndexStatistics#String - SearchIndexStatistics statistics = SEARCH_INDEX_CLIENT.getIndexStatistics("searchIndex"); - System.out.printf("There are %d documents and storage size of %d available in 'searchIndex'.%n", - statistics.getDocumentCount(), statistics.getStorageSize()); - // END: com.azure.search.documents.indexes.SearchIndexClient.getIndexStatistics#String - } - - /** - * Code snippet for {@link SearchIndexClient#getIndexStatisticsWithResponse(String, Context)} - */ - public void getSearchIndexStatisticsWithResponse() { - // BEGIN: com.azure.search.documents.indexes.SearchIndexClient.getIndexStatisticsWithResponse#String-Context - Response statistics = SEARCH_INDEX_CLIENT.getIndexStatisticsWithResponse("searchIndex", - new Context(KEY_1, VALUE_1)); - System.out.printf("The status code of the response is %s.%n" - + "There are %d documents and storage size of %d available in 'searchIndex'.%n", - statistics.getStatusCode(), statistics.getValue().getDocumentCount(), - statistics.getValue().getStorageSize()); - // END: com.azure.search.documents.indexes.SearchIndexClient.getIndexStatisticsWithResponse#String-Context - } - - /** - * Code snippet for {@link SearchIndexClient#listIndexes()} - */ - public void listIndexes() { - // BEGIN: com.azure.search.documents.indexes.SearchIndexClient.listIndexes - PagedIterable indexes = SEARCH_INDEX_CLIENT.listIndexes(); - for (SearchIndex index: indexes) { - System.out.printf("The index name is %s. The ETag of index is %s.%n", index.getName(), - index.getETag()); - } - // END: com.azure.search.documents.indexes.SearchIndexClient.listIndexes - } - - /** - * Code snippet for {@link SearchIndexClient#listIndexes(Context)} - */ - public void listIndexesWithContext() { - // BEGIN: com.azure.search.documents.indexes.SearchIndexClient.listIndexesWithResponse#Context - PagedIterable indexes = SEARCH_INDEX_CLIENT.listIndexes(new Context(KEY_1, VALUE_1)); - System.out.println("The status code of the response is" - + indexes.iterableByPage().iterator().next().getStatusCode()); - for (SearchIndex index: indexes) { - System.out.printf("The index name is %s. The ETag of index is %s.%n", index.getName(), index.getETag()); - } - // END: com.azure.search.documents.indexes.SearchIndexClient.listIndexesWithResponse#Context - } - - /** - * Code snippet for {@link SearchIndexClient#listIndexNames()} - */ - public void listIndexNames() { - // BEGIN: com.azure.search.documents.indexes.SearchIndexClient.listIndexNames - PagedIterable indexes = SEARCH_INDEX_CLIENT.listIndexNames(); - for (String indexName: indexes) { - System.out.printf("The index name is %s.%n", indexName); - } - // END: com.azure.search.documents.indexes.SearchIndexClient.listIndexNames - } - - /** - * Code snippet for {@link SearchIndexClient#listIndexNames(Context)} - */ - public void listIndexNamesWithContext() { - // BEGIN: com.azure.search.documents.indexes.SearchIndexClient.listIndexNames#Context - PagedIterable indexes = SEARCH_INDEX_CLIENT.listIndexNames(new Context(KEY_1, VALUE_1)); - System.out.println("The status code of the response is" - + indexes.iterableByPage().iterator().next().getStatusCode()); - for (String indexName: indexes) { - System.out.printf("The index name is %s.%n", indexName); - } - // END: com.azure.search.documents.indexes.SearchIndexClient.listIndexNames#Context - } - - /** - * Code snippet for {@link SearchIndexClient#createOrUpdateIndex(SearchIndex)} - */ - public void createOrUpdateIndex() { - // BEGIN: com.azure.search.documents.indexes.SearchIndexClient.createOrUpdateIndex#SearchIndex - SearchIndex indexFromService = SEARCH_INDEX_CLIENT.getIndex("searchIndex"); - indexFromService.setSuggesters(Collections.singletonList(new SearchSuggester("sg", - Collections.singletonList("hotelName")))); - SearchIndex updatedIndex = SEARCH_INDEX_CLIENT.createOrUpdateIndex(indexFromService); - System.out.printf("The index name is %s. The suggester name of index is %s.%n", updatedIndex.getName(), - updatedIndex.getSuggesters().get(0).getName()); - // END: com.azure.search.documents.indexes.SearchIndexClient.createOrUpdateIndex#SearchIndex - } - - /** - * Code snippet for {@link SearchIndexClient#createIndexWithResponse(SearchIndex, Context)} - */ - public void createOrUpdateIndexWithResponse() { - // BEGIN: com.azure.search.documents.indexes.SearchIndexClient.createOrUpdateIndexWithResponse#SearchIndex-boolean-boolean-Context - SearchIndex indexFromService = SEARCH_INDEX_CLIENT.getIndex("searchIndex"); - indexFromService.setSuggesters(Collections.singletonList(new SearchSuggester("sg", - Collections.singletonList("hotelName")))); - Response updatedIndexResponse = SEARCH_INDEX_CLIENT.createOrUpdateIndexWithResponse(indexFromService, true, - false, new Context(KEY_1, VALUE_1)); - System.out.printf("The status code of the normal response is %s.%n" - + "The index name is %s. The ETag of index is %s.%n", updatedIndexResponse.getStatusCode(), - updatedIndexResponse.getValue().getName(), updatedIndexResponse.getValue().getETag()); - // END: com.azure.search.documents.indexes.SearchIndexClient.createOrUpdateIndexWithResponse#SearchIndex-boolean-boolean-Context - } - - /** - * Code snippet for {@link SearchIndexClient#deleteIndex(String)} - */ - public void deleteSearchIndex() { - // BEGIN: com.azure.search.documents.indexes.SearchIndexClient.deleteIndex#String - SEARCH_INDEX_CLIENT.deleteIndex("searchIndex"); - // END: com.azure.search.documents.indexes.SearchIndexClient.deleteIndex#String - } - - /** - * Code snippet for {@link SearchIndexClient#deleteIndexWithResponse(SearchIndex, boolean, Context)} - */ - public void deleteSearchIndexWithResponse() { - // BEGIN: com.azure.search.documents.indexes.SearchIndexClient.deleteIndexWithResponse#SearchIndex-boolean-Context - SearchIndex indexFromService = SEARCH_INDEX_CLIENT.getIndex("searchIndex"); - Response deleteResponse = SEARCH_INDEX_CLIENT.deleteIndexWithResponse(indexFromService, true, - new Context(KEY_1, VALUE_1)); - System.out.printf("The status code of the response is %d.%n", deleteResponse.getStatusCode()); - // END: com.azure.search.documents.indexes.SearchIndexClient.deleteIndexWithResponse#SearchIndex-boolean-Context - } - - /** - * Code snippet for {@link SearchIndexClient#analyzeText(String, AnalyzeTextOptions)} - */ - public void analyzeText() { - // BEGIN: com.azure.search.documents.indexes.SearchIndexClient.analyzeText#String-AnalyzeTextOptions - PagedIterable tokenInfos = SEARCH_INDEX_CLIENT.analyzeText("searchIndex", - new AnalyzeTextOptions("The quick brown fox", LexicalTokenizerName.CLASSIC)); - for (AnalyzedTokenInfo tokenInfo : tokenInfos) { - System.out.printf("The token emitted by the analyzer is %s.%n", tokenInfo.getToken()); - } - // END: com.azure.search.documents.indexes.SearchIndexClient.analyzeText#String-AnalyzeTextOptions - } - - /** - * Code snippet for {@link SearchIndexClient#analyzeText(String, AnalyzeTextOptions, Context)} - */ - public void analyzeTextResponse() { - // BEGIN: com.azure.search.documents.indexes.SearchIndexClient.analyzeText#String-AnalyzeTextOptions-Context - PagedIterable tokenInfos = SEARCH_INDEX_CLIENT.analyzeText("searchIndex", - new AnalyzeTextOptions("The quick brown fox", LexicalTokenizerName.CLASSIC), new Context(KEY_1, VALUE_1)); - System.out.println("The status code of the response is " - + tokenInfos.iterableByPage().iterator().next().getStatusCode()); - for (AnalyzedTokenInfo tokenInfo : tokenInfos) { - System.out.printf("The token emitted by the analyzer is %s.%n", tokenInfo.getToken()); - } - // END: com.azure.search.documents.indexes.SearchIndexClient.analyzeText#String-AnalyzeTextOptions-Context - } - - /** - * Code snippet for creating {@link SearchIndexClient#createSynonymMap(SynonymMap)}. - */ - public void createSynonymMap() { - // BEGIN: com.azure.search.documents.indexes.SearchIndexClient.createSynonymMap#SynonymMap - SynonymMap synonymMap = new SynonymMap("synonymMap", - "United States, United States of America, USA\nWashington, Wash. => WA"); - SynonymMap synonymMapFromService = SEARCH_INDEX_CLIENT.createSynonymMap(synonymMap); - System.out.printf("The synonym map name is %s. The ETag of synonym map is %s.%n", - synonymMapFromService.getName(), synonymMapFromService.getETag()); - // END: com.azure.search.documents.indexes.SearchIndexClient.createSynonymMap#SynonymMap - } - - /** - * Code snippet for {@link SearchIndexClient#createIndexWithResponse(SearchIndex, Context)}. - */ - public void createSynonymMapWithResponse() { - // BEGIN: com.azure.search.documents.indexes.SearchIndexClient.createSynonymMapWithResponse#SynonymMap-Context - SynonymMap synonymMap = new SynonymMap("synonymMap", - "United States, United States of America, USA\nWashington, Wash. => WA"); - Response synonymMapFromService = SEARCH_INDEX_CLIENT.createSynonymMapWithResponse(synonymMap, - new Context(KEY_1, VALUE_1)); - System.out.printf("The status code of the response is %d.%n" - + "The synonym map name is %s. The ETag of synonym map is %s.%n", synonymMapFromService.getStatusCode(), - synonymMapFromService.getValue().getName(), synonymMapFromService.getValue().getETag()); - // END: com.azure.search.documents.indexes.SearchIndexClient.createSynonymMapWithResponse#SynonymMap-Context - } - - /** - * Code snippet for {@link SearchIndexClient#getSynonymMap(String)} - */ - public void getSynonymMap() { - // BEGIN: com.azure.search.documents.indexes.SearchIndexClient.getSynonymMap#String - SynonymMap synonymMapFromService = - SEARCH_INDEX_CLIENT.getSynonymMap("synonymMap"); - System.out.printf("The synonym map is %s. The ETag of synonym map is %s.%n", synonymMapFromService.getName(), - synonymMapFromService.getETag()); - // END: com.azure.search.documents.indexes.SearchIndexClient.getSynonymMap#String - } - - /** - * Code snippet for {@link SearchIndexClient#getSynonymMapWithResponse(String, Context)}} - */ - public void getSynonymMapWithResponse() { - // BEGIN: com.azure.search.documents.indexes.SearchIndexClient.getSynonymMapWithResponse#String-Context - Response synonymMapFromService = - SEARCH_INDEX_CLIENT.getSynonymMapWithResponse("synonymMap", new Context(KEY_1, VALUE_1)); - System.out.printf("The status code of the response is %d.%n" - + "The synonym map name is %s. The ETag of synonym map is %s.%n", synonymMapFromService.getStatusCode(), - synonymMapFromService.getValue().getName(), synonymMapFromService.getValue().getETag()); - // END: com.azure.search.documents.indexes.SearchIndexClient.getSynonymMapWithResponse#String-Context - } - - /** - * Code snippet for {@link SearchIndexClient#listSynonymMaps()} - */ - public void listSynonymMaps() { - // BEGIN: com.azure.search.documents.indexes.SearchIndexClient.listSynonymMaps - PagedIterable synonymMaps = SEARCH_INDEX_CLIENT.listSynonymMaps(); - for (SynonymMap synonymMap: synonymMaps) { - System.out.printf("The synonymMap name is %s. The ETag of synonymMap is %s.%n", synonymMap.getName(), - synonymMap.getETag()); - } - // END: com.azure.search.documents.indexes.SearchIndexClient.listSynonymMaps - } - - /** - * Code snippet for {@link SearchIndexClient#listSynonymMaps(Context)} - */ - public void listSynonymMapsWithContext() { - // BEGIN: com.azure.search.documents.indexes.SearchIndexClient.listSynonymMapsWithResponse#Context - PagedIterable synonymMaps = SEARCH_INDEX_CLIENT.listSynonymMaps(new Context(KEY_1, VALUE_1)); - System.out.println("The status code of the response is" - + synonymMaps.iterableByPage().iterator().next().getStatusCode()); - for (SynonymMap index: synonymMaps) { - System.out.printf("The index name is %s. The ETag of index is %s.%n", index.getName(), index.getETag()); - } - // END: com.azure.search.documents.indexes.SearchIndexClient.listSynonymMapsWithResponse#Context - } - - /** - * Code snippet for {@link SearchIndexClient#listSynonymMapNames()} - */ - public void listSynonymMapNames() { - // BEGIN: com.azure.search.documents.indexes.SearchIndexClient.listSynonymMapNames - PagedIterable synonymMaps = SEARCH_INDEX_CLIENT.listSynonymMapNames(); - for (String synonymMap: synonymMaps) { - System.out.printf("The synonymMap name is %s.%n", synonymMap); - } - // END: com.azure.search.documents.indexes.SearchIndexClient.listSynonymMapNames - } - - /** - * Code snippet for {@link SearchIndexClient#listSynonymMapNames(Context)} - */ - public void listSynonymMapNamesWithContext() { - // BEGIN: com.azure.search.documents.indexes.SearchIndexClient.listSynonymMapNamesWithResponse#Context - PagedIterable synonymMaps = SEARCH_INDEX_CLIENT.listIndexNames(new Context(KEY_1, VALUE_1)); - System.out.println("The status code of the response is" - + synonymMaps.iterableByPage().iterator().next().getStatusCode()); - for (String synonymMapNames: synonymMaps) { - System.out.printf("The synonymMap name is %s.%n", synonymMapNames); - } - // END: com.azure.search.documents.indexes.SearchIndexClient.listSynonymMapNamesWithResponse#Context - } - - /** - * Code snippet for {@link SearchIndexClient#createOrUpdateSynonymMap(SynonymMap)} - */ - public void createOrUpdateSynonymMap() { - // BEGIN: com.azure.search.documents.indexes.SearchIndexClient.createOrUpdateSynonymMap#SynonymMap - SynonymMap synonymMap = SEARCH_INDEX_CLIENT.getSynonymMap("synonymMapName"); - synonymMap.setSynonyms("United States, United States of America, USA, America\nWashington, Wash. => WA"); - SynonymMap updatedSynonymMap = SEARCH_INDEX_CLIENT.createOrUpdateSynonymMap(synonymMap); - System.out.printf("The synonym map name is %s. The synonyms are %s.%n", updatedSynonymMap.getName(), - updatedSynonymMap.getSynonyms()); - // END: com.azure.search.documents.indexes.SearchIndexClient.createOrUpdateSynonymMap#SynonymMap - } - - /** - * Code snippet for {@link SearchIndexClient#createOrUpdateSynonymMapWithResponse(SynonymMap, boolean, Context)} - */ - public void createOrUpdateSynonymMapWithResponse() { - // BEGIN: com.azure.search.documents.indexes.SearchIndexClient.createOrUpdateSynonymMapWithResponse#SynonymMap-boolean-Context - SynonymMap synonymMap = SEARCH_INDEX_CLIENT.getSynonymMap("synonymMap"); - synonymMap.setSynonyms("United States, United States of America, USA, America\nWashington, Wash. => WA"); - Response updatedSynonymMap = - SEARCH_INDEX_CLIENT.createOrUpdateSynonymMapWithResponse(synonymMap, true, - new Context(KEY_1, VALUE_1)); - System.out.printf("The status code of the normal response is %s.%n" - + "The synonym map name is %s. The synonyms are %s.%n", updatedSynonymMap.getStatusCode(), - updatedSynonymMap.getValue().getName(), updatedSynonymMap.getValue().getSynonyms()); - // END: com.azure.search.documents.indexes.SearchIndexClient.createOrUpdateSynonymMapWithResponse#SynonymMap-boolean-Context - } - - /** - * Code snippet for {@link SearchIndexClient#deleteSynonymMap(String)} - */ - public void deleteSynonymMap() { - // BEGIN: com.azure.search.documents.indexes.SearchIndexClient.deleteSynonymMap#String - SEARCH_INDEX_CLIENT.deleteSynonymMap("synonymMap"); - // END: com.azure.search.documents.indexes.SearchIndexClient.deleteSynonymMap#String - } - - /** - * Code snippet for {@link SearchIndexClient#deleteSynonymMapWithResponse(SynonymMap, boolean, Context)} - */ - public void deleteSynonymMapWithResponse() { - // BEGIN: com.azure.search.documents.indexes.SearchIndexClient.deleteSynonymMapWithResponse#SynonymMap-boolean-Context - SynonymMap synonymMap = SEARCH_INDEX_CLIENT.getSynonymMap("synonymMap"); - Response response = SEARCH_INDEX_CLIENT.deleteSynonymMapWithResponse(synonymMap, true, - new Context(KEY_1, VALUE_1)); - System.out.println("The status code of the response is" + response.getStatusCode()); - // END: com.azure.search.documents.indexes.SearchIndexClient.deleteSynonymMapWithResponse#SynonymMap-boolean-Context - } - - /** - * Code snippet for {@link SearchIndexClient#getServiceStatistics()} - */ - public void getServiceStatistics() { - // BEGIN: com.azure.search.documents.indexes.SearchIndexClient.getServiceStatistics - SearchServiceStatistics serviceStatistics = SEARCH_INDEX_CLIENT.getServiceStatistics(); - System.out.printf("There are %s search indexes in your service.%n", - serviceStatistics.getCounters().getIndexCounter()); - // END: com.azure.search.documents.indexes.SearchIndexClient.getServiceStatistics - } - - /** - * Code snippet for {@link SearchIndexClient#getServiceStatisticsWithResponse(Context)} - */ - public void getServiceStatisticsWithResponse() { - // BEGIN: com.azure.search.documents.indexes.SearchIndexClient.getServiceStatisticsWithResponse#Context - Response serviceStatistics = - SEARCH_INDEX_CLIENT.getServiceStatisticsWithResponse(new Context(KEY_1, VALUE_1)); - System.out.printf("The status code of the response is %s.%nThere are %s search indexes in your service.%n", - serviceStatistics.getStatusCode(), - serviceStatistics.getValue().getCounters().getIndexCounter()); - // END: com.azure.search.documents.indexes.SearchIndexClient.getServiceStatisticsWithResponse#Context - } - - private static final SearchIndexAsyncClient SEARCH_INDEX_ASYNC_CLIENT = new SearchIndexClientBuilder() - .buildAsyncClient(); - - /** - * Code snippet for creating a {@link SearchIndexAsyncClient}. - */ - public void createSearchIndexAsyncClientFromBuilder() { - // BEGIN: com.azure.search.documents.indexes.SearchIndexAsyncClient.instantiation - SearchIndexAsyncClient searchIndexAsyncClient = new SearchIndexClientBuilder() - .credential(new AzureKeyCredential("{key}")) - .endpoint("{endpoint}") - .buildAsyncClient(); - // END: com.azure.search.documents.indexes.SearchIndexAsyncClient.instantiation - } - - /** - * Code snippet for creating {@link SearchIndexAsyncClient#createIndex(SearchIndex)}. - */ - public void createSearchIndexAsync() { - // BEGIN: com.azure.search.documents.indexes.SearchIndexAsyncClient.createIndex#SearchIndex - List searchFields = Arrays.asList( - new SearchField("hotelId", SearchFieldDataType.STRING).setKey(true), - new SearchField("hotelName", SearchFieldDataType.STRING).setSearchable(true) - ); - SearchIndex searchIndex = new SearchIndex("searchIndex", searchFields); - SEARCH_INDEX_ASYNC_CLIENT.createIndex(searchIndex) - .subscribe(indexFromService -> - System.out.printf("The index name is %s. The ETag of index is %s.%n", indexFromService.getName(), - indexFromService.getETag())); - // END: com.azure.search.documents.indexes.SearchIndexAsyncClient.createIndex#SearchIndex - } - - /** - * Code snippet for {@link SearchIndexAsyncClient#createIndexWithResponse(SearchIndex)}. - */ - public void createSearchIndexWithResponseAsync() { - // BEGIN: com.azure.search.documents.indexes.SearchIndexAsyncClient.createIndexWithResponse#SearchIndex - List searchFields = Arrays.asList( - new SearchField("hotelId", SearchFieldDataType.STRING).setKey(true), - new SearchField("hotelName", SearchFieldDataType.STRING).setSearchable(true) - ); - SearchIndex searchIndex = new SearchIndex("searchIndex", searchFields); - - SEARCH_INDEX_ASYNC_CLIENT.createIndexWithResponse(searchIndex) - .subscribe(indexFromServiceResponse -> - System.out.printf("The status code of the response is %s. The index name is %s.%n", - indexFromServiceResponse.getStatusCode(), indexFromServiceResponse.getValue().getName())); - // END: com.azure.search.documents.indexes.SearchIndexAsyncClient.createIndexWithResponse#SearchIndex - } - - /** - * Code snippet for {@link SearchIndexAsyncClient#getIndex(String)} - */ - public void getSearchIndexAsync() { - // BEGIN: com.azure.search.documents.indexes.SearchIndexAsyncClient.getIndex#String - SEARCH_INDEX_ASYNC_CLIENT.getIndex("searchIndex") - .subscribe(indexFromService -> - System.out.printf("The index name is %s. The ETag of index is %s.%n", indexFromService.getName(), - indexFromService.getETag())); - // END: com.azure.search.documents.indexes.SearchIndexAsyncClient.getIndex#String - } - - /** - * Code snippet for {@link SearchIndexAsyncClient#getIndexWithResponse(String)}} - */ - public void getSearchIndexWithResponseAsync() { - // BEGIN: com.azure.search.documents.indexes.SearchIndexAsyncClient.getIndexWithResponse#String - SEARCH_INDEX_ASYNC_CLIENT.getIndexWithResponse("searchIndex") - .subscribe(indexFromServiceResponse -> - System.out.printf("The status code of the response is %s. The index name is %s.%n", - indexFromServiceResponse.getStatusCode(), indexFromServiceResponse.getValue().getName())); - // END: com.azure.search.documents.indexes.SearchIndexAsyncClient.getIndexWithResponse#String - } - - /** - * Code snippet for {@link SearchIndexAsyncClient#getIndexStatistics(String)} - */ - public void getSearchIndexStatisticsAsync() { - // BEGIN: com.azure.search.documents.indexes.SearchIndexAsyncClient.getIndexStatistics#String - SEARCH_INDEX_ASYNC_CLIENT.getIndexStatistics("searchIndex") - .subscribe(statistics -> - System.out.printf("There are %d documents and storage size of %d available in 'searchIndex'.%n", - statistics.getDocumentCount(), statistics.getStorageSize())); - // END: com.azure.search.documents.indexes.SearchIndexAsyncClient.getIndexStatistics#String - } - - /** - * Code snippet for {@link SearchIndexAsyncClient#getIndexStatisticsWithResponse(String)} - */ - public void getSearchIndexStatisticsWithResponseAsync() { - // BEGIN: com.azure.search.documents.indexes.SearchIndexAsyncClient.getIndexStatisticsWithResponse#String - SEARCH_INDEX_ASYNC_CLIENT.getIndexStatisticsWithResponse("searchIndex") - .subscribe(statistics -> System.out.printf("The status code of the response is %s.%n" - + "There are %d documents and storage size of %d available in 'searchIndex'.%n", - statistics.getStatusCode(), statistics.getValue().getDocumentCount(), - statistics.getValue().getStorageSize())); - // END: com.azure.search.documents.indexes.SearchIndexAsyncClient.getIndexStatisticsWithResponse#String - } - - /** - * Code snippet for {@link SearchIndexAsyncClient#listIndexes()} - */ - public void listIndexesAsync() { - // BEGIN: com.azure.search.documents.indexes.SearchIndexAsyncClient.listIndexes - SEARCH_INDEX_ASYNC_CLIENT.listIndexes() - .subscribe(index -> - System.out.printf("The index name is %s. The ETag of index is %s.%n", index.getName(), - index.getETag())); - // END: com.azure.search.documents.indexes.SearchIndexAsyncClient.listIndexes - } - - /** - * Code snippet for {@link SearchIndexAsyncClient#listIndexNames()} - */ - public void listIndexNamesAsync() { - // BEGIN: com.azure.search.documents.indexes.SearchIndexAsyncClient.listIndexNames - SEARCH_INDEX_ASYNC_CLIENT.listIndexNames() - .subscribe(indexName -> System.out.printf("The index name is %s.%n", indexName)); - // END: com.azure.search.documents.indexes.SearchIndexAsyncClient.listIndexNames - } - - /** - * Code snippet for {@link SearchIndexAsyncClient#createOrUpdateIndex(SearchIndex)} - */ - public void createOrUpdateIndexAsync() { - // BEGIN: com.azure.search.documents.indexes.SearchIndexAsyncClient.createOrUpdateIndex#SearchIndex - SEARCH_INDEX_ASYNC_CLIENT.getIndex("searchIndex") - .doOnNext(indexFromService -> indexFromService.setSuggesters(Collections.singletonList( - new SearchSuggester("sg", Collections.singletonList("hotelName"))))) - .flatMap(SEARCH_INDEX_ASYNC_CLIENT::createOrUpdateIndex) - .subscribe(updatedIndex -> - System.out.printf("The index name is %s. The suggester name of index is %s.%n", - updatedIndex.getName(), updatedIndex.getSuggesters().get(0).getName())); - // END: com.azure.search.documents.indexes.SearchIndexAsyncClient.createOrUpdateIndex#SearchIndex - } - - /** - * Code snippet for {@link SearchIndexAsyncClient#createIndexWithResponse(SearchIndex)} - */ - public void createOrUpdateIndexWithResponseAsync() { - // BEGIN: com.azure.search.documents.indexes.SearchIndexAsyncClient.createOrUpdateIndexWithResponse#SearchIndex-boolean-boolean-Context - SEARCH_INDEX_ASYNC_CLIENT.getIndex("searchIndex") - .doOnNext(indexFromService -> indexFromService.setSuggesters(Collections.singletonList( - new SearchSuggester("sg", Collections.singletonList("hotelName"))))) - .flatMap(indexFromService -> SEARCH_INDEX_ASYNC_CLIENT.createOrUpdateIndexWithResponse(indexFromService, true, - false)) - .subscribe(updatedIndexResponse -> System.out.printf("The status code of the normal response is %s.%n" - + "The index name is %s. The ETag of index is %s.%n", updatedIndexResponse.getStatusCode(), - updatedIndexResponse.getValue().getName(), updatedIndexResponse.getValue().getETag())); - // END: com.azure.search.documents.indexes.SearchIndexAsyncClient.createOrUpdateIndexWithResponse#SearchIndex-boolean-boolean-Context - } - - /** - * Code snippet for {@link SearchIndexAsyncClient#deleteIndex(String)} - */ - public void deleteSearchIndexAsync() { - // BEGIN: com.azure.search.documents.indexes.SearchIndexAsyncClient.deleteIndex#String - SEARCH_INDEX_ASYNC_CLIENT.deleteIndex("searchIndex") - .subscribe(); - // END: com.azure.search.documents.indexes.SearchIndexAsyncClient.deleteIndex#String - } - - /** - * Code snippet for {@link SearchIndexAsyncClient#deleteIndexWithResponse(SearchIndex, boolean)} - */ - public void deleteSearchIndexWithResponseAsync() { - // BEGIN: com.azure.search.documents.indexes.SearchIndexAsyncClient.deleteIndexWithResponse#SearchIndex-boolean - SEARCH_INDEX_ASYNC_CLIENT.getIndex("searchIndex") - .flatMap(indexFromService -> SEARCH_INDEX_ASYNC_CLIENT.deleteIndexWithResponse(indexFromService, true)) - .subscribe(deleteResponse -> - System.out.printf("The status code of the response is %d.%n", deleteResponse.getStatusCode())); - // END: com.azure.search.documents.indexes.SearchIndexAsyncClient.deleteIndexWithResponse#SearchIndex-boolean - } - - /** - * Code snippet for {@link SearchIndexClient#analyzeText(String, AnalyzeTextOptions)} - */ - public void analyzeTextAsync() { - // BEGIN: com.azure.search.documents.indexes.SearchIndexAsyncClient.analyzeText#String-AnalyzeTextOptions - SEARCH_INDEX_ASYNC_CLIENT.analyzeText("searchIndex", - new AnalyzeTextOptions("The quick brown fox", LexicalTokenizerName.CLASSIC)) - .subscribe(tokenInfo -> - System.out.printf("The token emitted by the analyzer is %s.%n", tokenInfo.getToken())); - // END: com.azure.search.documents.indexes.SearchIndexAsyncClient.analyzeText#String-AnalyzeTextOptions - } - - /** - * Code snippet for creating {@link SearchIndexAsyncClient#createSynonymMap(SynonymMap)}. - */ - public void createSynonymMapAsync() { - // BEGIN: com.azure.search.documents.indexes.SearchIndexAsyncClient.createSynonymMap#SynonymMap - SynonymMap synonymMap = new SynonymMap("synonymMap", - "United States, United States of America, USA\nWashington, Wash. => WA"); - SEARCH_INDEX_ASYNC_CLIENT.createSynonymMap(synonymMap) - .subscribe(synonymMapFromService -> - System.out.printf("The synonym map name is %s. The ETag of synonym map is %s.%n", - synonymMapFromService.getName(), synonymMapFromService.getETag())); - // END: com.azure.search.documents.indexes.SearchIndexAsyncClient.createSynonymMap#SynonymMap - } - - /** - * Code snippet for {@link SearchIndexAsyncClient#createSynonymMapWithResponse(SynonymMap)} - */ - public void createSynonymMapWithResponseAsync() { - // BEGIN: com.azure.search.documents.indexes.SearchIndexAsyncClient.createSynonymMapWithResponse#SynonymMap - SynonymMap synonymMap = new SynonymMap("synonymMap", - "United States, United States of America, USA\nWashington, Wash. => WA"); - SEARCH_INDEX_ASYNC_CLIENT.createSynonymMapWithResponse(synonymMap) - .subscribe(synonymMapFromService -> - System.out.printf("The status code of the response is %d.%n" - + "The synonym map name is %s. The ETag of synonym map is %s.%n", - synonymMapFromService.getStatusCode(), - synonymMapFromService.getValue().getName(), synonymMapFromService.getValue().getETag())); - // END: com.azure.search.documents.indexes.SearchIndexAsyncClient.createSynonymMapWithResponse#SynonymMap - } - - /** - * Code snippet for {@link SearchIndexAsyncClient#getSynonymMap(String)} - */ - public void getSynonymMapAsync() { - // BEGIN: com.azure.search.documents.indexes.SearchIndexAsyncClient.getSynonymMap#String - SEARCH_INDEX_ASYNC_CLIENT.getSynonymMap("synonymMap") - .subscribe(synonymMapFromService -> - System.out.printf("The synonym map is %s. The ETag of synonym map is %s.%n", - synonymMapFromService.getName(), synonymMapFromService.getETag())); - // END: com.azure.search.documents.indexes.SearchIndexAsyncClient.getSynonymMap#String - } - - /** - * Code snippet for {@link SearchIndexAsyncClient#getSynonymMapWithResponse(String)}} - */ - public void getSynonymMapWithResponseAsync() { - // BEGIN: com.azure.search.documents.indexes.SearchIndexAsyncClient.getSynonymMapWithResponse#String - SEARCH_INDEX_ASYNC_CLIENT.getSynonymMapWithResponse("synonymMap") - .subscribe(synonymMapFromService -> System.out.printf("The status code of the response is %d.%n" - + "The synonym map name is %s. The ETag of synonym map is %s.%n", - synonymMapFromService.getStatusCode(), synonymMapFromService.getValue().getName(), - synonymMapFromService.getValue().getETag())); - // END: com.azure.search.documents.indexes.SearchIndexAsyncClient.getSynonymMapWithResponse#String - } - - /** - * Code snippet for {@link SearchIndexAsyncClient#listSynonymMaps()} - */ - public void listSynonymMapsAsync() { - // BEGIN: com.azure.search.documents.indexes.SearchIndexAsyncClient.listSynonymMaps - SEARCH_INDEX_ASYNC_CLIENT.listSynonymMaps() - .subscribe(synonymMap -> System.out.printf("The synonymMap name is %s. The ETag of synonymMap is %s.%n", - synonymMap.getName(), synonymMap.getETag())); - // END: com.azure.search.documents.indexes.SearchIndexAsyncClient.listSynonymMaps - } - - /** - * Code snippet for {@link SearchIndexAsyncClient#listSynonymMapNames()} - */ - public void listSynonymMapNamesAsync() { - // BEGIN: com.azure.search.documents.indexes.SearchIndexAsyncClient.listSynonymMapNames - SEARCH_INDEX_ASYNC_CLIENT.listSynonymMapNames() - .subscribe(synonymMap -> System.out.printf("The synonymMap name is %s.%n", synonymMap)); - // END: com.azure.search.documents.indexes.SearchIndexAsyncClient.listSynonymMapNames - } - - /** - * Code snippet for {@link SearchIndexAsyncClient#createOrUpdateSynonymMap(SynonymMap)} - */ - public void createOrUpdateSynonymMapAsync() { - // BEGIN: com.azure.search.documents.indexes.SearchIndexAsyncClient.createOrUpdateSynonymMap#SynonymMap - SEARCH_INDEX_ASYNC_CLIENT.getSynonymMap("searchIndex") - .doOnNext(synonymMap -> synonymMap - .setSynonyms("United States, United States of America, USA, America\nWashington, Wash. => WA")) - .flatMap(SEARCH_INDEX_ASYNC_CLIENT::createOrUpdateSynonymMap) - .subscribe(updatedSynonymMap -> - System.out.printf("The synonym map name is %s. The synonyms are %s.%n", updatedSynonymMap.getName(), - updatedSynonymMap.getSynonyms())); - // END: com.azure.search.documents.indexes.SearchIndexAsyncClient.createOrUpdateSynonymMap#SynonymMap - } - - /** - * Code snippet for {@link SearchIndexAsyncClient#createOrUpdateSynonymMapWithResponse(SynonymMap, boolean)} - */ - public void createOrUpdateSynonymMapWithResponseAsync() { - // BEGIN: com.azure.search.documents.indexes.SearchIndexAsyncClient.createOrUpdateSynonymMapWithResponse#SynonymMap-boolean-Context - SEARCH_INDEX_ASYNC_CLIENT.getSynonymMap("searchIndex") - .flatMap(synonymMap -> { - synonymMap.setSynonyms( - "United States, United States of America, USA, America\nWashington, Wash. => WA"); - return SEARCH_INDEX_ASYNC_CLIENT.createOrUpdateSynonymMapWithResponse(synonymMap, true); - }) - .subscribe(updatedSynonymMap -> - System.out.printf("The status code of the normal response is %s.%n" - + "The synonym map name is %s. The synonyms are %s.%n", updatedSynonymMap.getStatusCode(), - updatedSynonymMap.getValue().getName(), updatedSynonymMap.getValue().getSynonyms())); - // END: com.azure.search.documents.indexes.SearchIndexAsyncClient.createOrUpdateSynonymMapWithResponse#SynonymMap-boolean-Context - } - - /** - * Code snippet for {@link SearchIndexAsyncClient#deleteSynonymMap(String)} - */ - public void deleteSynonymMapAsync() { - // BEGIN: com.azure.search.documents.indexes.SearchIndexAsyncClient.deleteSynonymMap#String - SEARCH_INDEX_ASYNC_CLIENT.deleteSynonymMap("synonymMap") - .subscribe(); - // END: com.azure.search.documents.indexes.SearchIndexAsyncClient.deleteSynonymMap#String - } - - /** - * Code snippet for {@link SearchIndexAsyncClient#deleteSynonymMapWithResponse(SynonymMap, boolean)} - */ - public void deleteSynonymMapWithResponseAsync() { - // BEGIN: com.azure.search.documents.indexes.SearchIndexAsyncClient.deleteSynonymMapWithResponse#SynonymMap-boolean - SEARCH_INDEX_ASYNC_CLIENT.getSynonymMap("synonymMap") - .flatMap(synonymMap -> SEARCH_INDEX_ASYNC_CLIENT.deleteSynonymMapWithResponse(synonymMap, true)) - .subscribe(response -> System.out.println("The status code of the response is" + response.getStatusCode())); - // END: com.azure.search.documents.indexes.SearchIndexAsyncClient.deleteSynonymMapWithResponse#SynonymMap-boolean - } - - /** - * Code snippet for {@link SearchIndexAsyncClient#getServiceStatistics()} - */ - public void getServiceStatisticsAsync() { - // BEGIN: com.azure.search.documents.indexes.SearchIndexAsyncClient.getServiceStatistics - SEARCH_INDEX_ASYNC_CLIENT.getServiceStatistics() - .subscribe(serviceStatistics -> System.out.printf("There are %s search indexes in your service.%n", - serviceStatistics.getCounters().getIndexCounter())); - // END: com.azure.search.documents.indexes.SearchIndexAsyncClient.getServiceStatistics - } - - /** - * Code snippet for {@link SearchIndexAsyncClient#getServiceStatisticsWithResponse()} - */ - public void getServiceStatisticsWithResponseAsync() { - // BEGIN: com.azure.search.documents.indexes.SearchIndexAsyncClient.getServiceStatisticsWithResponse - SEARCH_INDEX_ASYNC_CLIENT.getServiceStatisticsWithResponse() - .subscribe(serviceStatistics -> - System.out.printf("The status code of the response is %s.%n" - + "There are %s search indexes in your service.%n", - serviceStatistics.getStatusCode(), - serviceStatistics.getValue().getCounters().getIndexCounter())); - // END: com.azure.search.documents.indexes.SearchIndexAsyncClient.getServiceStatisticsWithResponse - } - - private static final SearchIndexerClient SEARCH_INDEXER_CLIENT = new SearchIndexerClientBuilder().buildClient(); - /** - * Code snippet for creating a {@link SearchIndexerClient}. - */ - public void createSearchIndexerClientFromBuilder() { - // BEGIN: com.azure.search.documents.indexes.SearchIndexerClient.instantiation - SearchIndexerClient searchIndexerClient = new SearchIndexerClientBuilder() - .credential(new AzureKeyCredential("{key}")) - .endpoint("{endpoint}") - .buildClient(); - // END: com.azure.search.documents.indexes.SearchIndexerClient.instantiation - } - - /** - * Code snippet for creating {@link SearchIndexerClient#createIndexer(SearchIndexer)}. - */ - public void createSearchIndexer() { - // BEGIN: com.azure.search.documents.indexes.SearchIndexerClient.createIndexer#SearchIndexer - SearchIndexer searchIndexer = new SearchIndexer("searchIndexer", "dataSource", - "searchIndex"); - SearchIndexer indexerFromService = SEARCH_INDEXER_CLIENT.createIndexer(searchIndexer); - System.out.printf("The indexer name is %s. The ETag of indexer is %s.%n", indexerFromService.getName(), - indexerFromService.getETag()); - // END: com.azure.search.documents.indexes.SearchIndexerClient.createIndexer#SearchIndexer - } - - /** - * Code snippet for {@link SearchIndexerClient#createIndexerWithResponse(SearchIndexer, Context)}. - */ - public void createSearchIndexerWithResponse() { - // BEGIN: com.azure.search.documents.indexes.SearchIndexerClient.createIndexerWithResponse#SearchIndexer-Context - SearchIndexer searchIndexer = new SearchIndexer("searchIndexer", "dataSource", - "searchIndex"); - Response indexerFromServiceResponse = SEARCH_INDEXER_CLIENT.createIndexerWithResponse( - searchIndexer, new Context(KEY_1, VALUE_1)); - - System.out.printf("The status code of the response is %s. The indexer name is %s.%n", - indexerFromServiceResponse.getStatusCode(), indexerFromServiceResponse.getValue().getName()); - // END: com.azure.search.documents.indexes.SearchIndexerClient.createIndexerWithResponse#SearchIndexer-Context - } - - /** - * Code snippet for {@link SearchIndexerClient#getIndexer(String)} - */ - public void getSearchIndexer() { - // BEGIN: com.azure.search.documents.indexes.SearchIndexerClient.getIndexer#String - SearchIndexer indexerFromService = - SEARCH_INDEXER_CLIENT.getIndexer("searchIndexer"); - System.out.printf("The indexer name is %s. The ETag of indexer is %s.%n", indexerFromService.getName(), - indexerFromService.getETag()); - // END: com.azure.search.documents.indexes.SearchIndexerClient.getIndexer#String - } - - /** - * Code snippet for {@link SearchIndexerClient#getIndexerWithResponse(String, Context)}} - */ - public void getSearchIndexerWithResponse() { - // BEGIN: com.azure.search.documents.indexes.SearchIndexerClient.getIndexerWithResponse#String-Context - Response indexerFromServiceResponse = SEARCH_INDEXER_CLIENT.getIndexerWithResponse( - "searchIndexer", new Context(KEY_1, VALUE_1)); - - System.out.printf("The status code of the response is %s. The indexer name is %s.%n", - indexerFromServiceResponse.getStatusCode(), indexerFromServiceResponse.getValue().getName()); - // END: com.azure.search.documents.indexes.SearchIndexerClient.getIndexerWithResponse#String-Context - } - - - /** - * Code snippet for {@link SearchIndexerClient#listIndexers()} - */ - public void listIndexers() { - // BEGIN: com.azure.search.documents.indexes.SearchIndexerClient.listIndexers - PagedIterable indexers = SEARCH_INDEXER_CLIENT.listIndexers(); - for (SearchIndexer indexer: indexers) { - System.out.printf("The indexer name is %s. The ETag of indexer is %s.%n", indexer.getName(), - indexer.getETag()); - } - // END: com.azure.search.documents.indexes.SearchIndexerClient.listIndexers - } - - /** - * Code snippet for {@link SearchIndexerClient#listIndexers(Context)} - */ - public void listIndexersWithContext() { - // BEGIN: com.azure.search.documents.indexes.SearchIndexerClient.listIndexersWithResponse#Context - PagedIterable indexers = SEARCH_INDEXER_CLIENT.listIndexers(new Context(KEY_1, VALUE_1)); - System.out.println("The status code of the response is" - + indexers.iterableByPage().iterator().next().getStatusCode()); - for (SearchIndexer indexer: indexers) { - System.out.printf("The indexer name is %s. The ETag of index is %s.%n", - indexer.getName(), indexer.getETag()); - } - // END: com.azure.search.documents.indexes.SearchIndexerClient.listIndexersWithResponse#Context - } - - /** - * Code snippet for {@link SearchIndexerClient#listIndexerNames()} - */ - public void listIndexerNames() { - // BEGIN: com.azure.search.documents.indexes.SearchIndexerClient.listIndexerNames - PagedIterable indexers = SEARCH_INDEXER_CLIENT.listIndexerNames(); - for (String indexerName: indexers) { - System.out.printf("The indexer name is %s.%n", indexerName); - } - // END: com.azure.search.documents.indexes.SearchIndexerClient.listIndexerNames - } - - /** - * Code snippet for {@link SearchIndexerClient#listIndexerNames(Context)} - */ - public void listIndexerNamesWithContext() { - // BEGIN: com.azure.search.documents.indexes.SearchIndexerClient.listIndexerNames#Context - PagedIterable indexers = SEARCH_INDEXER_CLIENT.listIndexerNames(new Context(KEY_1, VALUE_1)); - System.out.println("The status code of the response is" - + indexers.iterableByPage().iterator().next().getStatusCode()); - for (String indexerName: indexers) { - System.out.printf("The indexer name is %s.%n", indexerName); - } - // END: com.azure.search.documents.indexes.SearchIndexerClient.listIndexerNames#Context - } - - /** - * Code snippet for {@link SearchIndexerClient#createOrUpdateIndexer(SearchIndexer)} - */ - public void createOrUpdateIndexer() { - // BEGIN: com.azure.search.documents.indexes.SearchIndexerClient.createOrUpdateIndexer#SearchIndexer - SearchIndexer searchIndexerFromService = SEARCH_INDEXER_CLIENT.getIndexer("searchIndexer"); - searchIndexerFromService.setFieldMappings(Collections.singletonList( - new FieldMapping("hotelName").setTargetFieldName("HotelName"))); - SearchIndexer updateIndexer = SEARCH_INDEXER_CLIENT.createOrUpdateIndexer(searchIndexerFromService); - System.out.printf("The indexer name is %s. The target field name of indexer is %s.%n", - updateIndexer.getName(), updateIndexer.getFieldMappings().get(0).getTargetFieldName()); - // END: com.azure.search.documents.indexes.SearchIndexerClient.createOrUpdateIndexer#SearchIndexer - } - - /** - * Code snippet for {@link SearchIndexerClient#createOrUpdateIndexerWithResponse(SearchIndexer, boolean, Context)} - */ - public void createOrUpdateIndexerWithResponse() { - // BEGIN: com.azure.search.documents.indexes.SearchIndexerClient.createOrUpdateIndexerWithResponse#SearchIndexer-boolean-Context - SearchIndexer searchIndexerFromService = SEARCH_INDEXER_CLIENT.getIndexer("searchIndexer"); - searchIndexerFromService.setFieldMappings(Collections.singletonList( - new FieldMapping("hotelName").setTargetFieldName("HotelName"))); - Response indexerFromService = SEARCH_INDEXER_CLIENT.createOrUpdateIndexerWithResponse( - searchIndexerFromService, true, new Context(KEY_1, VALUE_1)); - System.out.printf("The status code of the response is %s.%nThe indexer name is %s. " - + "The target field name of indexer is %s.%n", indexerFromService.getStatusCode(), - indexerFromService.getValue().getName(), - indexerFromService.getValue().getFieldMappings().get(0).getTargetFieldName()); - // END: com.azure.search.documents.indexes.SearchIndexerClient.createOrUpdateIndexerWithResponse#SearchIndexer-boolean-Context - } - - - /** - * Code snippet for {@link SearchIndexerClient#deleteIndexer(String)} - */ - public void deleteSearchIndexer() { - // BEGIN: com.azure.search.documents.indexes.SearchIndexerClient.deleteIndexer#String - SEARCH_INDEXER_CLIENT.deleteIndexer("searchIndexer"); - // END: com.azure.search.documents.indexes.SearchIndexerClient.deleteIndexer#String - } - - /** - * Code snippet for {@link SearchIndexerClient#deleteIndexerWithResponse(SearchIndexer, boolean, Context)} - */ - public void deleteSearchIndexerWithResponse() { - // BEGIN: com.azure.search.documents.indexes.SearchIndexerClient.deleteIndexerWithResponse#SearchIndexer-boolean-Context - SearchIndexer searchIndexer = SEARCH_INDEXER_CLIENT.getIndexer("searchIndexer"); - Response deleteResponse = SEARCH_INDEXER_CLIENT.deleteIndexerWithResponse(searchIndexer, true, - new Context(KEY_1, VALUE_1)); - System.out.printf("The status code of the response is %d.%n", deleteResponse.getStatusCode()); - // END: com.azure.search.documents.indexes.SearchIndexerClient.deleteIndexerWithResponse#SearchIndexer-boolean-Context - } - - /** - * Code snippet for {@link SearchIndexerClient#resetIndexer(String)} - */ - public void resetIndexer() { - // BEGIN: com.azure.search.documents.indexes.SearchIndexerClient.resetIndexer#String - SEARCH_INDEXER_CLIENT.resetIndexer("searchIndexer"); - // END: com.azure.search.documents.indexes.SearchIndexerClient.resetIndexer#String - } - - /** - * Code snippet for {@link SearchIndexerClient#resetIndexerWithResponse(String, Context)} - */ - public void resetIndexerWithResponse() { - // BEGIN: com.azure.search.documents.indexes.SearchIndexerClient.resetIndexerWithResponse#String-Context - Response response = SEARCH_INDEXER_CLIENT.resetIndexerWithResponse("searchIndexer", - new Context(KEY_1, VALUE_1)); - System.out.println("The status code of the response is " + response.getStatusCode()); - // END: com.azure.search.documents.indexes.SearchIndexerClient.resetIndexerWithResponse#String-Context - } - - /** - * Code snippet for {@link SearchIndexerClient#runIndexer(String)} - */ - public void runIndexer() { - // BEGIN: com.azure.search.documents.indexes.SearchIndexerClient.runIndexer#String - SEARCH_INDEXER_CLIENT.runIndexer("searchIndexer"); - // END: com.azure.search.documents.indexes.SearchIndexerClient.runIndexer#String - } - - /** - * Code snippet for {@link SearchIndexerClient#runIndexerWithResponse(String, Context)} - */ - public void runIndexerWithResponse() { - // BEGIN: com.azure.search.documents.indexes.SearchIndexerClient.runIndexerWithResponse#String-Context - Response response = SEARCH_INDEXER_CLIENT.runIndexerWithResponse("searchIndexer", - new Context(KEY_1, VALUE_1)); - System.out.println("The status code of the response is " + response.getStatusCode()); - // END: com.azure.search.documents.indexes.SearchIndexerClient.runIndexerWithResponse#String-Context - } - - /** - * Code snippet for {@link SearchIndexerClient#getIndexerStatus(String)} - */ - public void getIndexerStatus() { - // BEGIN: com.azure.search.documents.indexes.SearchIndexerClient.getIndexerStatus#String - SearchIndexerStatus indexerStatus = SEARCH_INDEXER_CLIENT.getIndexerStatus("searchIndexer"); - System.out.printf("The indexer status is %s.%n", indexerStatus.getStatus()); - // END: com.azure.search.documents.indexes.SearchIndexerClient.getIndexerStatus#String - } - - /** - * Code snippet for {@link SearchIndexerClient#getIndexerStatusWithResponse(String, Context)} - */ - public void getIndexerStatusWithResponse() { - // BEGIN: com.azure.search.documents.indexes.SearchIndexerClient.getIndexerStatusWithResponse#String-Context - Response response = SEARCH_INDEXER_CLIENT.getIndexerStatusWithResponse("searchIndexer", - new Context(KEY_1, VALUE_1)); - System.out.printf("The status code of the response is %s.%nThe indexer status is %s.%n", - response.getStatusCode(), response.getValue().getStatus()); - // END: com.azure.search.documents.indexes.SearchIndexerClient.getIndexerStatusWithResponse#String-Context - } - - /** - * Code snippet for creating {@link SearchIndexerClient#createDataSourceConnection(SearchIndexerDataSourceConnection)}. - */ - public void createDataSource() { - // BEGIN: com.azure.search.documents.indexes.SearchIndexerClient.createDataSourceConnection#SearchIndexerDataSourceConnection - SearchIndexerDataSourceConnection dataSource = new SearchIndexerDataSourceConnection("dataSource", - com.azure.search.documents.indexes.models.SearchIndexerDataSourceType.AZURE_BLOB, "{connectionString}", - new com.azure.search.documents.indexes.models.SearchIndexerDataContainer("container")); - SearchIndexerDataSourceConnection dataSourceFromService = - SEARCH_INDEXER_CLIENT.createDataSourceConnection(dataSource); - System.out.printf("The data source name is %s. The ETag of data source is %s.%n", - dataSourceFromService.getName(), dataSourceFromService.getETag()); - // END: com.azure.search.documents.indexes.SearchIndexerClient.createDataSourceConnection#SearchIndexerDataSourceConnection - } - - /** - * Code snippet for {@link SearchIndexerClient#createDataSourceConnectionWithResponse(SearchIndexerDataSourceConnection, Context)}. - */ - public void createDataSourceWithResponse() { - // BEGIN: com.azure.search.documents.indexes.SearchIndexerClient.createDataSourceConnectionWithResponse#SearchIndexerDataSourceConnection-Context - SearchIndexerDataSourceConnection dataSource = new SearchIndexerDataSourceConnection("dataSource", - SearchIndexerDataSourceType.AZURE_BLOB, "{connectionString}", - new SearchIndexerDataContainer("container")); - Response dataSourceFromService = - SEARCH_INDEXER_CLIENT.createDataSourceConnectionWithResponse(dataSource, new Context(KEY_1, VALUE_1)); - - System.out.printf("The status code of the response is %s. The data source name is %s.%n", - dataSourceFromService.getStatusCode(), dataSourceFromService.getValue().getName()); - // END: com.azure.search.documents.indexes.SearchIndexerClient.createDataSourceConnectionWithResponse#SearchIndexerDataSourceConnection-Context - } - - /** - * Code snippet for {@link SearchIndexerClient#getDataSourceConnection(String)} - */ - public void getDataSource() { - // BEGIN: com.azure.search.documents.indexes.SearchIndexerClient.getDataSourceConnection#String - SearchIndexerDataSourceConnection dataSource = - SEARCH_INDEXER_CLIENT.getDataSourceConnection("dataSource"); - System.out.printf("The dataSource name is %s. The ETag of dataSource is %s.%n", dataSource.getName(), - dataSource.getETag()); - // END: com.azure.search.documents.indexes.SearchIndexerClient.getDataSourceConnection#String - } - - /** - * Code snippet for {@link SearchIndexerClient#getDataSourceConnectionWithResponse(String, Context)} - */ - public void getDataSourceWithResponse() { - // BEGIN: com.azure.search.documents.indexes.SearchIndexerClient.getDataSourceConnectionWithResponse#String-Context - Response dataSource = - SEARCH_INDEXER_CLIENT.getDataSourceConnectionWithResponse( - "dataSource", new Context(KEY_1, VALUE_1)); - - System.out.printf("The status code of the response is %s. The data source name is %s.%n", - dataSource.getStatusCode(), dataSource.getValue().getName()); - // END: com.azure.search.documents.indexes.SearchIndexerClient.getDataSourceConnectionWithResponse#String-Context - } - - - /** - * Code snippet for {@link SearchIndexerClient#listDataSourceConnections()} - */ - public void listDataSources() { - // BEGIN: com.azure.search.documents.indexes.SearchIndexerClient.listDataSourceConnections - PagedIterable dataSources = SEARCH_INDEXER_CLIENT.listDataSourceConnections(); - for (SearchIndexerDataSourceConnection dataSource: dataSources) { - System.out.printf("The dataSource name is %s. The ETag of dataSource is %s.%n", dataSource.getName(), - dataSource.getETag()); - } - // END: com.azure.search.documents.indexes.SearchIndexerClient.listDataSourceConnections - } - - /** - * Code snippet for {@link SearchIndexerClient#listDataSourceConnections(Context)} - */ - public void listDataSourcesWithContext() { - // BEGIN: com.azure.search.documents.indexes.SearchIndexerClient.listDataSourceConnectionsWithResponse#Context - PagedIterable dataSources = - SEARCH_INDEXER_CLIENT.listDataSourceConnections(new Context(KEY_1, VALUE_1)); - - System.out.println("The status code of the response is" - + dataSources.iterableByPage().iterator().next().getStatusCode()); - for (SearchIndexerDataSourceConnection dataSource: dataSources) { - System.out.printf("The dataSource name is %s. The ETag of dataSource is %s.%n", - dataSource.getName(), dataSource.getETag()); - } - // END: com.azure.search.documents.indexes.SearchIndexerClient.listDataSourceConnectionsWithResponse#Context - } - - /** - * Code snippet for {@link SearchIndexerClient#listDataSourceConnectionNames()} - */ - public void listDataSourceNames() { - // BEGIN: com.azure.search.documents.indexes.SearchIndexerClient.listDataSourceConnectionNames - PagedIterable dataSources = SEARCH_INDEXER_CLIENT.listDataSourceConnectionNames(); - for (String dataSourceName: dataSources) { - System.out.printf("The dataSource name is %s.%n", dataSourceName); - } - // END: com.azure.search.documents.indexes.SearchIndexerClient.listDataSourceConnectionNames - } - - /** - * Code snippet for {@link SearchIndexerClient#listDataSourceConnectionNames(Context)} - */ - public void listDataSourceNamesWithContext() { - // BEGIN: com.azure.search.documents.indexes.SearchIndexerClient.listDataSourceConnectionNamesWithContext#Context - PagedIterable dataSources = SEARCH_INDEXER_CLIENT.listDataSourceConnectionNames(new Context(KEY_1, VALUE_1)); - System.out.println("The status code of the response is" - + dataSources.iterableByPage().iterator().next().getStatusCode()); - for (String dataSourceName: dataSources) { - System.out.printf("The dataSource name is %s.%n", dataSourceName); - } - // END: com.azure.search.documents.indexes.SearchIndexerClient.listDataSourceConnectionNamesWithContext#Context - } - - /** - * Code snippet for {@link SearchIndexerClient#createOrUpdateDataSourceConnection(SearchIndexerDataSourceConnection)} - */ - public void createOrUpdateDataSource() { - // BEGIN: com.azure.search.documents.indexes.SearchIndexerClient.createOrUpdateDataSourceConnection#SearchIndexerDataSourceConnection - SearchIndexerDataSourceConnection dataSource = SEARCH_INDEXER_CLIENT.getDataSourceConnection("dataSource"); - dataSource.setContainer(new SearchIndexerDataContainer("updatecontainer")); - - SearchIndexerDataSourceConnection updateDataSource = SEARCH_INDEXER_CLIENT - .createOrUpdateDataSourceConnection(dataSource); - System.out.printf("The dataSource name is %s. The container name of dataSource is %s.%n", - updateDataSource.getName(), updateDataSource.getContainer().getName()); - // END: com.azure.search.documents.indexes.SearchIndexerClient.createOrUpdateDataSourceConnection#SearchIndexerDataSourceConnection - } - - /** - * Code snippet for {@link SearchIndexerClient#createOrUpdateDataSourceConnectionWithResponse(SearchIndexerDataSourceConnection, boolean, Context)} - */ - public void createOrUpdateDataSourceWithResponse() { - // BEGIN: com.azure.search.documents.indexes.SearchIndexerClient.createOrUpdateDataSourceConnectionWithResponse#SearchIndexerDataSourceConnection-boolean-Context - SearchIndexerDataSourceConnection dataSource = SEARCH_INDEXER_CLIENT.getDataSourceConnection("dataSource"); - dataSource.setContainer(new SearchIndexerDataContainer("updatecontainer")); - - Response updateDataSource = SEARCH_INDEXER_CLIENT - .createOrUpdateDataSourceConnectionWithResponse(dataSource, true, new Context(KEY_1, VALUE_1)); - System.out.printf("The status code of the response is %s.%nThe dataSource name is %s. " - + "The container name of dataSource is %s.%n", updateDataSource.getStatusCode(), - updateDataSource.getValue().getName(), updateDataSource.getValue().getContainer().getName()); - // END: com.azure.search.documents.indexes.SearchIndexerClient.createOrUpdateDataSourceConnectionWithResponse#SearchIndexerDataSourceConnection-boolean-Context - } - - /** - * Code snippet for {@link SearchIndexerClient#deleteDataSourceConnection(String)} - */ - public void deleteDataSource() { - // BEGIN: com.azure.search.documents.indexes.SearchIndexerClient.deleteDataSourceConnection#String - SEARCH_INDEXER_CLIENT.deleteDataSourceConnection("dataSource"); - // END: com.azure.search.documents.indexes.SearchIndexerClient.deleteDataSourceConnection#String - } - - /** - * Code snippet for {@link SearchIndexerClient#deleteDataSourceConnectionWithResponse(SearchIndexerDataSourceConnection, boolean, Context)} - */ - public void deleteDataSourceWithResponse() { - // BEGIN: com.azure.search.documents.indexes.SearchIndexerClient.deleteDataSourceConnectionWithResponse#SearchIndexerDataSourceConnection-boolean-Context - SearchIndexerDataSourceConnection dataSource = - SEARCH_INDEXER_CLIENT.getDataSourceConnection("dataSource"); - Response deleteResponse = SEARCH_INDEXER_CLIENT.deleteDataSourceConnectionWithResponse(dataSource, true, - new Context(KEY_1, VALUE_1)); - System.out.printf("The status code of the response is %d.%n", deleteResponse.getStatusCode()); - // END: com.azure.search.documents.indexes.SearchIndexerClient.deleteDataSourceConnectionWithResponse#SearchIndexerDataSourceConnection-boolean-Context - } - - /** - * Code snippet for {@link SearchIndexerClient#createSkillset(SearchIndexerSkillset)} - */ - public void createSearchIndexerSkillset() { - // BEGIN: com.azure.search.documents.indexes.SearchIndexerClient.createSkillset#SearchIndexerSkillset - List inputs = Collections.singletonList( - new InputFieldMappingEntry("image") - .setSource("/document/normalized_images/*") - ); - - List outputs = Arrays.asList( - new OutputFieldMappingEntry("text") - .setTargetName("mytext"), - new OutputFieldMappingEntry("layoutText") - .setTargetName("myLayoutText") - ); - SearchIndexerSkillset searchIndexerSkillset = new SearchIndexerSkillset("searchIndexerSkillset", - Collections.singletonList(new OcrSkill(inputs, outputs) - .setShouldDetectOrientation(true) - .setDefaultLanguageCode(null) - .setName("myocr") - .setDescription("Extracts text (plain and structured) from image.") - .setContext("/document/normalized_images/*"))); - SearchIndexerSkillset skillset = SEARCH_INDEXER_CLIENT.createSkillset(searchIndexerSkillset); - System.out.printf("The indexer skillset name is %s. The ETag of indexer skillset is %s.%n", - skillset.getName(), skillset.getETag()); - // END: com.azure.search.documents.indexes.SearchIndexerClient.createSkillset#SearchIndexerSkillset - } - - /** - * Code snippet for {@link SearchIndexerClient#createSkillsetWithResponse(SearchIndexerSkillset, Context)}. - */ - public void createSearchIndexerSkillsetWithResponse() { - // BEGIN: com.azure.search.documents.indexes.SearchIndexerClient.createSkillsetWithResponse#SearchIndexerSkillset-Context - List inputs = Collections.singletonList( - new InputFieldMappingEntry("image") - .setSource("/document/normalized_images/*") - ); - - List outputs = Arrays.asList( - new OutputFieldMappingEntry("text") - .setTargetName("mytext"), - new OutputFieldMappingEntry("layoutText") - .setTargetName("myLayoutText") - ); - SearchIndexerSkillset searchIndexerSkillset = new SearchIndexerSkillset("searchIndexerSkillset", - Collections.singletonList(new OcrSkill(inputs, outputs) - .setShouldDetectOrientation(true) - .setDefaultLanguageCode(null) - .setName("myocr") - .setDescription("Extracts text (plain and structured) from image.") - .setContext("/document/normalized_images/*"))); - Response skillsetWithResponse = - SEARCH_INDEXER_CLIENT.createSkillsetWithResponse(searchIndexerSkillset, new Context(KEY_1, VALUE_1)); - System.out.printf("The status code of the response is %s. The indexer skillset name is %s.%n", - skillsetWithResponse.getStatusCode(), skillsetWithResponse.getValue().getName()); - // END: com.azure.search.documents.indexes.SearchIndexerClient.createSkillsetWithResponse#SearchIndexerSkillset-Context - } - - /** - * Code snippet for {@link SearchIndexerClient#getSkillset(String)} - */ - public void getSearchIndexerSkillset() { - // BEGIN: com.azure.search.documents.indexes.SearchIndexerClient.getSearchIndexerSkillset#String - SearchIndexerSkillset indexerSkillset = - SEARCH_INDEXER_CLIENT.getSkillset("searchIndexerSkillset"); - System.out.printf("The indexer skillset name is %s. The ETag of indexer skillset is %s.%n", - indexerSkillset.getName(), indexerSkillset.getETag()); - // END: com.azure.search.documents.indexes.SearchIndexerClient.getSearchIndexerSkillset#String - } - - /** - * Code snippet for {@link SearchIndexerClient#getSkillsetWithResponse(String, Context)} - */ - public void getSearchIndexerSkillsetWithResponse() { - // BEGIN: com.azure.search.documents.indexes.SearchIndexerClient.getSkillsetWithResponse#String-Context - Response skillsetWithResponse = SEARCH_INDEXER_CLIENT.getSkillsetWithResponse( - "searchIndexerSkillset", new Context(KEY_1, VALUE_1)); - - System.out.printf("The status code of the response is %s. The indexer skillset name is %s.%n", - skillsetWithResponse.getStatusCode(), skillsetWithResponse.getValue().getName()); - // END: com.azure.search.documents.indexes.SearchIndexerClient.getSkillsetWithResponse#String-Context - } - - - /** - * Code snippet for {@link SearchIndexerClient#listSkillsets()} - */ - public void listIndexerSkillset() { - // BEGIN: com.azure.search.documents.indexes.SearchIndexerClient.listSkillsets - PagedIterable indexerSkillsets = SEARCH_INDEXER_CLIENT.listSkillsets(); - for (SearchIndexerSkillset skillset: indexerSkillsets) { - System.out.printf("The skillset name is %s. The ETag of skillset is %s.%n", skillset.getName(), - skillset.getETag()); - } - // END: com.azure.search.documents.indexes.SearchIndexerClient.listSkillsets - } - - /** - * Code snippet for {@link SearchIndexerClient#listSkillsets(Context)} - */ - public void listIndexerSkillsetsWithContext() { - // BEGIN: com.azure.search.documents.indexes.SearchIndexerClient.listSkillsetsWithContext#Context - PagedIterable indexerSkillsets = SEARCH_INDEXER_CLIENT - .listSkillsets(new Context(KEY_1, VALUE_1)); - System.out.println("The status code of the response is" - + indexerSkillsets.iterableByPage().iterator().next().getStatusCode()); - for (SearchIndexerSkillset skillset: indexerSkillsets) { - System.out.printf("The skillset name is %s. The ETag of skillset is %s.%n", - skillset.getName(), skillset.getETag()); - } - // END: com.azure.search.documents.indexes.SearchIndexerClient.listSkillsetsWithContext#Context - } - - /** - * Code snippet for {@link SearchIndexerClient#listSkillsetNames()} - */ - public void listIndexerSkillsetNames() { - // BEGIN: com.azure.search.documents.indexes.SearchIndexerClient.listSkillsetNames - PagedIterable skillsetNames = SEARCH_INDEXER_CLIENT.listSkillsetNames(); - for (String skillsetName: skillsetNames) { - System.out.printf("The indexer skillset name is %s.%n", skillsetName); - } - // END: com.azure.search.documents.indexes.SearchIndexerClient.listSkillsetNames - } - - /** - * Code snippet for {@link SearchIndexerClient#listSkillsetNames(Context)} - */ - public void listIndexerSkillsetNamesWithContext() { - // BEGIN: com.azure.search.documents.indexes.SearchIndexerClient.listSkillsetNamesWithResponse#Context - PagedIterable skillsetNames = SEARCH_INDEXER_CLIENT.listSkillsetNames(new Context(KEY_1, VALUE_1)); - System.out.println("The status code of the response is" - + skillsetNames.iterableByPage().iterator().next().getStatusCode()); - for (String skillsetName: skillsetNames) { - System.out.printf("The indexer skillset name is %s.%n", skillsetName); - } - // END: com.azure.search.documents.indexes.SearchIndexerClient.listSkillsetNamesWithResponse#Context - } - - - /** - * Code snippet for {@link SearchIndexerClient#createOrUpdateSkillset(SearchIndexerSkillset)} - */ - public void createOrUpdateIndexerSkillset() { - // BEGIN: com.azure.search.documents.indexes.SearchIndexerClient.createOrUpdateIndexerSkillset#SearchIndexerSkillset - SearchIndexerSkillset indexerSkillset = SEARCH_INDEXER_CLIENT.getSkillset("searchIndexerSkillset"); - indexerSkillset.setDescription("This is new description!"); - SearchIndexerSkillset updateSkillset = SEARCH_INDEXER_CLIENT.createOrUpdateSkillset(indexerSkillset); - System.out.printf("The indexer skillset name is %s. The description of indexer skillset is %s.%n", - updateSkillset.getName(), updateSkillset.getDescription()); - // END: com.azure.search.documents.indexes.SearchIndexerClient.createOrUpdateIndexerSkillset#SearchIndexerSkillset - } - - /** - * Code snippet for {@link SearchIndexerClient#createOrUpdateSkillsetWithResponse(SearchIndexerSkillset, boolean, Context)} - */ - public void createOrUpdateIndexerSkillsetWithResponse() { - // BEGIN: com.azure.search.documents.indexes.SearchIndexerClient.createOrUpdateSkillsetWithResponse#SearchIndexerSkillset-boolean-Context - SearchIndexerSkillset indexerSkillset = SEARCH_INDEXER_CLIENT.getSkillset("searchIndexerSkillset"); - indexerSkillset.setDescription("This is new description!"); - Response updateSkillsetResponse = SEARCH_INDEXER_CLIENT.createOrUpdateSkillsetWithResponse( - indexerSkillset, true, new Context(KEY_1, VALUE_1)); - System.out.printf("The status code of the response is %s.%nThe indexer skillset name is %s. " - + "The description of indexer skillset is %s.%n", updateSkillsetResponse.getStatusCode(), - updateSkillsetResponse.getValue().getName(), - updateSkillsetResponse.getValue().getDescription()); - // END: com.azure.search.documents.indexes.SearchIndexerClient.createOrUpdateSkillsetWithResponse#SearchIndexerSkillset-boolean-Context - } - - /** - * Code snippet for {@link SearchIndexerClient#deleteSkillset(String)} - */ - public void deleteSearchIndexerSkillset() { - // BEGIN: com.azure.search.documents.indexes.SearchIndexerClient.deleteSkillset#String - SEARCH_INDEXER_CLIENT.deleteSkillset("searchIndexerSkillset"); - // END: com.azure.search.documents.indexes.SearchIndexerClient.deleteSkillset#String - } - - /** - * Code snippet for {@link SearchIndexerClient#deleteSkillsetWithResponse(SearchIndexerSkillset, boolean, Context)} - */ - public void deleteSearchIndexerSkillsetWithResponse() { - // BEGIN: com.azure.search.documents.indexes.SearchIndexerClient.deleteSkillsetWithResponse#SearchIndexerSkillset-boolean-Context - SearchIndexerSkillset searchIndexerSkillset = SEARCH_INDEXER_CLIENT.getSkillset("searchIndexerSkillset"); - Response deleteResponse = SEARCH_INDEXER_CLIENT.deleteSkillsetWithResponse(searchIndexerSkillset, true, - new Context(KEY_1, VALUE_1)); - System.out.printf("The status code of the response is %d.%n", deleteResponse.getStatusCode()); - // END: com.azure.search.documents.indexes.SearchIndexerClient.deleteSkillsetWithResponse#SearchIndexerSkillset-boolean-Context - } - - private static final SearchIndexerAsyncClient SEARCH_INDEXER_ASYNC_CLIENT = new SearchIndexerClientBuilder() - .buildAsyncClient(); - - /** - * Code snippet for creating a {@link SearchIndexerAsyncClient}. - */ - public void createSearchIndexerAsyncClientFromBuilder() { - // BEGIN: com.azure.search.documents.indexes.SearchIndexerAsyncClient.instantiation - SearchIndexerAsyncClient searchIndexerAsyncClient = new SearchIndexerClientBuilder() - .credential(new AzureKeyCredential("{key}")) - .endpoint("{endpoint}") - .buildAsyncClient(); - // END: com.azure.search.documents.indexes.SearchIndexerAsyncClient.instantiation - } - - /** - * Code snippet for creating {@link SearchIndexerAsyncClient#createIndexer(SearchIndexer)}. - */ - public void createSearchIndexerAsync() { - // BEGIN: com.azure.search.documents.indexes.SearchIndexerAsyncClient.createIndexer#SearchIndexer - SearchIndexer searchIndexer = new SearchIndexer("searchIndexer", "dataSource", - "searchIndex"); - SEARCH_INDEXER_ASYNC_CLIENT.createIndexer(searchIndexer) - .subscribe(indexerFromService -> - System.out.printf("The indexer name is %s. The ETag of indexer is %s.%n", indexerFromService.getName(), - indexerFromService.getETag())); - // END: com.azure.search.documents.indexes.SearchIndexerAsyncClient.createIndexer#SearchIndexer - } - - /** - * Code snippet for {@link SearchIndexerAsyncClient#createIndexerWithResponse(SearchIndexer)}. - */ - public void createSearchIndexerWithResponseAsync() { - // BEGIN: com.azure.search.documents.indexes.SearchIndexerAsyncClient.createIndexerWithResponse#SearchIndexer - SearchIndexer searchIndexer = new SearchIndexer("searchIndexer", "dataSource", - "searchIndex"); - SEARCH_INDEXER_ASYNC_CLIENT.createIndexerWithResponse(searchIndexer) - .subscribe(indexerFromServiceResponse -> - System.out.printf("The status code of the response is %s. The indexer name is %s.%n", - indexerFromServiceResponse.getStatusCode(), indexerFromServiceResponse.getValue().getName())); - // END: com.azure.search.documents.indexes.SearchIndexerAsyncClient.createIndexerWithResponse#SearchIndexer - } - - /** - * Code snippet for {@link SearchIndexerAsyncClient#getIndexer(String)} - */ - public void getSearchIndexerAsync() { - // BEGIN: com.azure.search.documents.indexes.SearchIndexerAsyncClient.getIndexer#String - SEARCH_INDEXER_ASYNC_CLIENT.getIndexer("searchIndexer") - .subscribe(indexerFromService -> - System.out.printf("The indexer name is %s. The ETag of indexer is %s.%n", indexerFromService.getName(), - indexerFromService.getETag())); - // END: com.azure.search.documents.indexes.SearchIndexerAsyncClient.getIndexer#String - } - - /** - * Code snippet for {@link SearchIndexerAsyncClient#getIndexerWithResponse(String)}} - */ - public void getSearchIndexerWithResponseAsync() { - // BEGIN: com.azure.search.documents.indexes.SearchIndexerAsyncClient.getIndexerWithResponse#String - SEARCH_INDEXER_ASYNC_CLIENT.getIndexerWithResponse("searchIndexer") - .subscribe(indexerFromServiceResponse -> - System.out.printf("The status code of the response is %s. The indexer name is %s.%n", - indexerFromServiceResponse.getStatusCode(), indexerFromServiceResponse.getValue().getName())); - // END: com.azure.search.documents.indexes.SearchIndexerAsyncClient.getIndexerWithResponse#String - } - - - /** - * Code snippet for {@link SearchIndexerAsyncClient#listIndexers()} - */ - public void listIndexersAsync() { - // BEGIN: com.azure.search.documents.indexes.SearchIndexerAsyncClient.listIndexers - SEARCH_INDEXER_ASYNC_CLIENT.listIndexers() - .subscribe(indexer -> - System.out.printf("The indexer name is %s. The ETag of indexer is %s.%n", indexer.getName(), - indexer.getETag())); - // END: com.azure.search.documents.indexes.SearchIndexerAsyncClient.listIndexers - } - - /** - * Code snippet for {@link SearchIndexerAsyncClient#listIndexerNames()} - */ - public void listIndexerNamesAsync() { - // BEGIN: com.azure.search.documents.indexes.SearchIndexerAsyncClient.listIndexerNames - SEARCH_INDEXER_ASYNC_CLIENT.listIndexerNames() - .subscribe(indexerName -> System.out.printf("The indexer name is %s.%n", indexerName)); - // END: com.azure.search.documents.indexes.SearchIndexerAsyncClient.listIndexerNames - } - - /** - * Code snippet for {@link SearchIndexerAsyncClient#createOrUpdateIndexer(SearchIndexer)} - */ - public void createOrUpdateIndexerAsync() { - // BEGIN: com.azure.search.documents.indexes.SearchIndexerAsyncClient.createOrUpdateIndexer#SearchIndexer - SEARCH_INDEXER_ASYNC_CLIENT.getIndexer("searchIndexer") - .flatMap(searchIndexerFromService -> { - searchIndexerFromService.setFieldMappings(Collections.singletonList( - new FieldMapping("hotelName").setTargetFieldName("HotelName"))); - return SEARCH_INDEXER_ASYNC_CLIENT.createOrUpdateIndexer(searchIndexerFromService); - }) - .subscribe(updatedIndexer -> - System.out.printf("The indexer name is %s. The target field name of indexer is %s.%n", - updatedIndexer.getName(), updatedIndexer.getFieldMappings().get(0).getTargetFieldName())); - // END: com.azure.search.documents.indexes.SearchIndexerAsyncClient.createOrUpdateIndexer#SearchIndexer - } - - /** - * Code snippet for {@link SearchIndexerAsyncClient#createOrUpdateIndexerWithResponse(SearchIndexer, boolean)} - */ - public void createOrUpdateIndexerWithResponseAsync() { - // BEGIN: com.azure.search.documents.indexes.SearchIndexerAsyncClient.createOrUpdateIndexerWithResponse#SearchIndexer-boolean - SEARCH_INDEXER_ASYNC_CLIENT.getIndexer("searchIndexer") - .flatMap(searchIndexerFromService -> { - searchIndexerFromService.setFieldMappings(Collections.singletonList( - new FieldMapping("hotelName").setTargetFieldName("HotelName"))); - return SEARCH_INDEXER_ASYNC_CLIENT.createOrUpdateIndexerWithResponse(searchIndexerFromService, true); - }) - .subscribe(indexerFromService -> - System.out.printf("The status code of the response is %s.%nThe indexer name is %s. " - + "The target field name of indexer is %s.%n", indexerFromService.getStatusCode(), - indexerFromService.getValue().getName(), - indexerFromService.getValue().getFieldMappings().get(0).getTargetFieldName())); - // END: com.azure.search.documents.indexes.SearchIndexerAsyncClient.createOrUpdateIndexerWithResponse#SearchIndexer-boolean - } - - /** - * Code snippet for {@link SearchIndexerAsyncClient#deleteIndexer(String)} - */ - public void deleteSearchIndexerAsync() { - // BEGIN: com.azure.search.documents.indexes.SearchIndexerAsyncClient.deleteIndexer#String - SEARCH_INDEXER_ASYNC_CLIENT.deleteIndexer("searchIndexer") - .subscribe(); - // END: com.azure.search.documents.indexes.SearchIndexerAsyncClient.deleteIndexer#String - } - - /** - * Code snippet for {@link SearchIndexerAsyncClient#deleteIndexerWithResponse(SearchIndexer, boolean)} - */ - public void deleteSearchIndexerWithResponseAsync() { - // BEGIN: com.azure.search.documents.indexes.SearchIndexerAsyncClient.deleteIndexerWithResponse#SearchIndexer-boolean - SEARCH_INDEXER_ASYNC_CLIENT.getIndexer("searchIndexer") - .flatMap(searchIndexer -> - SEARCH_INDEXER_ASYNC_CLIENT.deleteIndexerWithResponse(searchIndexer, true)) - .subscribe(deleteResponse -> - System.out.printf("The status code of the response is %d.%n", deleteResponse.getStatusCode())); - // END: com.azure.search.documents.indexes.SearchIndexerAsyncClient.deleteIndexerWithResponse#SearchIndexer-boolean - } - - /** - * Code snippet for {@link SearchIndexerAsyncClient#resetIndexer(String)} - */ - public void resetIndexerAsync() { - // BEGIN: com.azure.search.documents.indexes.SearchIndexerAsyncClient.resetIndexer#String - SEARCH_INDEXER_ASYNC_CLIENT.resetIndexer("searchIndexer") - .subscribe(); - // END: com.azure.search.documents.indexes.SearchIndexerAsyncClient.resetIndexer#String - } - - /** - * Code snippet for {@link SearchIndexerAsyncClient#resetIndexerWithResponse(String)} - */ - public void resetIndexerWithResponseAsync() { - // BEGIN: com.azure.search.documents.indexes.SearchIndexerAsyncClient.resetIndexerWithResponse#String - SEARCH_INDEXER_ASYNC_CLIENT.resetIndexerWithResponse("searchIndexer") - .subscribe(response -> - System.out.println("The status code of the response is " + response.getStatusCode())); - // END: com.azure.search.documents.indexes.SearchIndexerAsyncClient.resetIndexerWithResponse#String - } - - /** - * Code snippet for {@link SearchIndexerAsyncClient#runIndexer(String)} - */ - public void runIndexerAsync() { - // BEGIN: com.azure.search.documents.indexes.SearchIndexerAsyncClient.runIndexer#String - SEARCH_INDEXER_ASYNC_CLIENT.runIndexer("searchIndexer") - .subscribe(); - // END: com.azure.search.documents.indexes.SearchIndexerAsyncClient.runIndexer#String - } - - /** - * Code snippet for {@link SearchIndexerAsyncClient#runIndexerWithResponse(String)} - */ - public void runIndexerWithResponseAsync() { - // BEGIN: com.azure.search.documents.indexes.SearchIndexerAsyncClient.runIndexerWithResponse#String - SEARCH_INDEXER_ASYNC_CLIENT.runIndexerWithResponse("searchIndexer") - .subscribe(response -> - System.out.println("The status code of the response is " + response.getStatusCode())); - // END: com.azure.search.documents.indexes.SearchIndexerAsyncClient.runIndexerWithResponse#String - } - - /** - * Code snippet for {@link SearchIndexerAsyncClient#getIndexerStatus(String)} - */ - public void getIndexerStatusAsync() { - // BEGIN: com.azure.search.documents.indexes.SearchIndexerAsyncClient.getIndexerStatus#String - SEARCH_INDEXER_ASYNC_CLIENT.getIndexerStatus("searchIndexer") - .subscribe(indexerStatus -> - System.out.printf("The indexer status is %s.%n", indexerStatus.getStatus())); - // END: com.azure.search.documents.indexes.SearchIndexerAsyncClient.getIndexerStatus#String - } - - /** - * Code snippet for {@link SearchIndexerAsyncClient#getIndexerStatusWithResponse(String)} - */ - public void getIndexerStatusWithResponseAsync() { - // BEGIN: com.azure.search.documents.indexes.SearchIndexerAsyncClient.getIndexerStatusWithResponse#String - SEARCH_INDEXER_ASYNC_CLIENT.getIndexerStatusWithResponse("searchIndexer") - .subscribe(response -> - System.out.printf("The status code of the response is %s.%nThe indexer status is %s.%n", - response.getStatusCode(), response.getValue().getStatus())); - // END: com.azure.search.documents.indexes.SearchIndexerAsyncClient.getIndexerStatusWithResponse#String - } - - /** - * Code snippet for creating {@link SearchIndexerAsyncClient#createDataSourceConnection(SearchIndexerDataSourceConnection)}. - */ - public void createDataSourceAsync() { - // BEGIN: com.azure.search.documents.indexes.SearchIndexerAsyncClient.createDataSourceConnection#SearchIndexerDataSourceConnection - SearchIndexerDataSourceConnection dataSource = new SearchIndexerDataSourceConnection("dataSource", - com.azure.search.documents.indexes.models.SearchIndexerDataSourceType.AZURE_BLOB, "{connectionString}", - new com.azure.search.documents.indexes.models.SearchIndexerDataContainer("container")); - SEARCH_INDEXER_ASYNC_CLIENT.createDataSourceConnection(dataSource) - .subscribe(dataSourceFromService -> - System.out.printf("The data source name is %s. The ETag of data source is %s.%n", - dataSourceFromService.getName(), dataSourceFromService.getETag())); - // END: com.azure.search.documents.indexes.SearchIndexerAsyncClient.createDataSourceConnection#SearchIndexerDataSourceConnection - } - - /** - * Code snippet for {@link SearchIndexerAsyncClient#createDataSourceConnectionWithResponse(SearchIndexerDataSourceConnection)}. - */ - public void createDataSourceWithResponseAsync() { - // BEGIN: com.azure.search.documents.indexes.SearchIndexerAsyncClient.createDataSourceConnectionWithResponse#SearchIndexerDataSourceConnection - SearchIndexerDataSourceConnection dataSource = new SearchIndexerDataSourceConnection("dataSource", - SearchIndexerDataSourceType.AZURE_BLOB, "{connectionString}", - new SearchIndexerDataContainer("container")); - SEARCH_INDEXER_ASYNC_CLIENT.createDataSourceConnectionWithResponse(dataSource) - .subscribe(dataSourceFromService -> - System.out.printf("The status code of the response is %s. The data source name is %s.%n", - dataSourceFromService.getStatusCode(), dataSourceFromService.getValue().getName())); - // END: com.azure.search.documents.indexes.SearchIndexerAsyncClient.createDataSourceConnectionWithResponse#SearchIndexerDataSourceConnection - } - - /** - * Code snippet for {@link SearchIndexerAsyncClient#getDataSourceConnection(String)} - */ - public void getDataSourceAsync() { - // BEGIN: com.azure.search.documents.indexes.SearchIndexerAsyncClient.getDataSourceConnection#String - SEARCH_INDEXER_ASYNC_CLIENT.getDataSourceConnection("dataSource") - .subscribe(dataSource -> - System.out.printf("The dataSource name is %s. The ETag of dataSource is %s.%n", dataSource.getName(), - dataSource.getETag())); - // END: com.azure.search.documents.indexes.SearchIndexerAsyncClient.getDataSourceConnection#String - } - - /** - * Code snippet for {@link SearchIndexerAsyncClient#getDataSourceConnectionWithResponse(String)} - */ - public void getDataSourceWithResponseAsync() { - // BEGIN: com.azure.search.documents.indexes.SearchIndexerAsyncClient.getDataSourceConnectionWithResponse#String - SEARCH_INDEXER_ASYNC_CLIENT.getDataSourceConnectionWithResponse("dataSource") - .subscribe(dataSource -> - System.out.printf("The status code of the response is %s. The data source name is %s.%n", - dataSource.getStatusCode(), dataSource.getValue().getName())); - // END: com.azure.search.documents.indexes.SearchIndexerAsyncClient.getDataSourceConnectionWithResponse#String - } - - - /** - * Code snippet for {@link SearchIndexerAsyncClient#listDataSourceConnections()} - */ - public void listDataSourcesAsync() { - // BEGIN: com.azure.search.documents.indexes.SearchIndexerAsyncClient.listDataSourceConnections - SEARCH_INDEXER_ASYNC_CLIENT.listDataSourceConnections() - .subscribe(dataSource -> - System.out.printf("The dataSource name is %s. The ETag of dataSource is %s.%n", - dataSource.getName(), dataSource.getETag()) - ); - // END: com.azure.search.documents.indexes.SearchIndexerAsyncClient.listDataSourceConnections - } - - /** - * Code snippet for {@link SearchIndexerAsyncClient#listDataSourceConnectionNames()} - */ - public void listDataSourceNamesAsync() { - // BEGIN: com.azure.search.documents.indexes.SearchIndexerAsyncClient.listDataSourceConnectionNames - SEARCH_INDEXER_ASYNC_CLIENT.listDataSourceConnectionNames() - .subscribe(dataSourceName -> System.out.printf("The dataSource name is %s.%n", dataSourceName)); - // END: com.azure.search.documents.indexes.SearchIndexerAsyncClient.listDataSourceConnectionNames - } - - /** - * Code snippet for {@link SearchIndexerAsyncClient#createOrUpdateDataSourceConnection(SearchIndexerDataSourceConnection)} - */ - public void createOrUpdateDataSourceAsync() { - // BEGIN: com.azure.search.documents.indexes.SearchIndexerAsyncClient.createOrUpdateDataSourceConnection#SearchIndexerDataSourceConnection - SearchIndexerDataSourceConnection dataSource = SEARCH_INDEXER_CLIENT.getDataSourceConnection("dataSource"); - dataSource.setContainer(new SearchIndexerDataContainer("updatecontainer")); - - SearchIndexerDataSourceConnection updateDataSource = SEARCH_INDEXER_CLIENT - .createOrUpdateDataSourceConnection(dataSource); - System.out.printf("The dataSource name is %s. The container name of dataSource is %s.%n", - updateDataSource.getName(), updateDataSource.getContainer().getName()); - // END: com.azure.search.documents.indexes.SearchIndexerAsyncClient.createOrUpdateDataSourceConnection#SearchIndexerDataSourceConnection - } - - /** - * Code snippet for {@link SearchIndexerAsyncClient#createOrUpdateDataSourceConnectionWithResponse(SearchIndexerDataSourceConnection, boolean)} - */ - public void createOrUpdateDataSourceWithResponseAsync() { - // BEGIN: com.azure.search.documents.indexes.SearchIndexerAsyncClient.createOrUpdateDataSourceConnectionWithResponse#SearchIndexerDataSourceConnection-boolean - SEARCH_INDEXER_ASYNC_CLIENT.getDataSourceConnection("dataSource") - .flatMap(dataSource -> { - dataSource.setContainer(new SearchIndexerDataContainer("updatecontainer")); - return SEARCH_INDEXER_ASYNC_CLIENT.createOrUpdateDataSourceConnectionWithResponse(dataSource, true); - }) - .subscribe(updateDataSource -> - System.out.printf("The status code of the response is %s.%nThe dataSource name is %s. " - + "The container name of dataSource is %s.%n", updateDataSource.getStatusCode(), - updateDataSource.getValue().getName(), updateDataSource.getValue().getContainer().getName())); - // END: com.azure.search.documents.indexes.SearchIndexerAsyncClient.createOrUpdateDataSourceConnectionWithResponse#SearchIndexerDataSourceConnection-boolean - } - - - - - /** - * Code snippet for {@link SearchIndexerAsyncClient#deleteDataSourceConnection(String)} - */ - public void deleteDataSourceAsync() { - // BEGIN: com.azure.search.documents.indexes.SearchIndexerAsyncClient.deleteDataSourceConnection#String - SEARCH_INDEXER_ASYNC_CLIENT.deleteDataSourceConnection("dataSource") - .subscribe(); - // END: com.azure.search.documents.indexes.SearchIndexerAsyncClient.deleteDataSourceConnection#String - } - - /** - * Code snippet for {@link SearchIndexerAsyncClient#deleteDataSourceConnectionWithResponse(SearchIndexerDataSourceConnection, boolean)} - */ - public void deleteDataSourceWithResponseAsync() { - // BEGIN: com.azure.search.documents.indexes.SearchIndexerAsyncClient.deleteDataSourceConnectionWithResponse#SearchIndexerDataSourceConnection-boolean - SEARCH_INDEXER_ASYNC_CLIENT.getDataSourceConnection("dataSource") - .flatMap(dataSource -> SEARCH_INDEXER_ASYNC_CLIENT.deleteDataSourceConnectionWithResponse(dataSource, true)) - .subscribe(deleteResponse -> - System.out.printf("The status code of the response is %d.%n", deleteResponse.getStatusCode())); - // END: com.azure.search.documents.indexes.SearchIndexerAsyncClient.deleteDataSourceConnectionWithResponse#SearchIndexerDataSourceConnection-boolean - } - - /** - * Code snippet for {@link SearchIndexerAsyncClient#createSkillset(SearchIndexerSkillset)} - */ - public void createSearchIndexerSkillsetAsync() { - // BEGIN: com.azure.search.documents.indexes.SearchIndexerAsyncClient.createSkillset#SearchIndexerSkillset - List inputs = Collections.singletonList( - new InputFieldMappingEntry("image") - .setSource("/document/normalized_images/*") - ); - - List outputs = Arrays.asList( - new OutputFieldMappingEntry("text") - .setTargetName("mytext"), - new OutputFieldMappingEntry("layoutText") - .setTargetName("myLayoutText") - ); - SearchIndexerSkillset searchIndexerSkillset = new SearchIndexerSkillset("searchIndexerSkillset", - Collections.singletonList(new OcrSkill(inputs, outputs) - .setShouldDetectOrientation(true) - .setDefaultLanguageCode(null) - .setName("myocr") - .setDescription("Extracts text (plain and structured) from image.") - .setContext("/document/normalized_images/*"))); - SEARCH_INDEXER_ASYNC_CLIENT.createSkillset(searchIndexerSkillset) - .subscribe(skillset -> - System.out.printf("The indexer skillset name is %s. The ETag of indexer skillset is %s.%n", - skillset.getName(), skillset.getETag())); - // END: com.azure.search.documents.indexes.SearchIndexerAsyncClient.createSkillset#SearchIndexerSkillset - } - - /** - * Code snippet for {@link SearchIndexerAsyncClient#createSkillsetWithResponse(SearchIndexerSkillset)}. - */ - public void createSearchIndexerSkillsetWithResponseAsync() { - // BEGIN: com.azure.search.documents.indexes.SearchIndexerAsyncClient.createSkillsetWithResponse#SearchIndexerSkillset - List inputs = Collections.singletonList( - new InputFieldMappingEntry("image") - .setSource("/document/normalized_images/*") - ); - - List outputs = Arrays.asList( - new OutputFieldMappingEntry("text") - .setTargetName("mytext"), - new OutputFieldMappingEntry("layoutText") - .setTargetName("myLayoutText") - ); - SearchIndexerSkillset searchIndexerSkillset = new SearchIndexerSkillset("searchIndexerSkillset", - Collections.singletonList(new OcrSkill(inputs, outputs) - .setShouldDetectOrientation(true) - .setDefaultLanguageCode(null) - .setName("myocr") - .setDescription("Extracts text (plain and structured) from image.") - .setContext("/document/normalized_images/*"))); - SEARCH_INDEXER_ASYNC_CLIENT.createSkillsetWithResponse(searchIndexerSkillset) - .subscribe(skillsetWithResponse -> - System.out.printf("The status code of the response is %s. The indexer skillset name is %s.%n", - skillsetWithResponse.getStatusCode(), skillsetWithResponse.getValue().getName())); - // END: com.azure.search.documents.indexes.SearchIndexerAsyncClient.createSkillsetWithResponse#SearchIndexerSkillset - } - - /** - * Code snippet for {@link SearchIndexerAsyncClient#getSkillset(String)} - */ - public void getSearchIndexerSkillsetAsync() { - // BEGIN: com.azure.search.documents.indexes.SearchIndexerAsyncClient.getSearchIndexerSkillset#String - SEARCH_INDEXER_ASYNC_CLIENT.getSkillset("searchIndexerSkillset") - .subscribe(indexerSkillset -> - System.out.printf("The indexer skillset name is %s. The ETag of indexer skillset is %s.%n", - indexerSkillset.getName(), indexerSkillset.getETag())); - // END: com.azure.search.documents.indexes.SearchIndexerAsyncClient.getSearchIndexerSkillset#String - } - - /** - * Code snippet for {@link SearchIndexerAsyncClient#getSkillsetWithResponse(String)} - */ - public void getSearchIndexerSkillsetWithResponseAsync() { - // BEGIN: com.azure.search.documents.indexes.SearchIndexerAsyncClient.getSkillsetWithResponse#String - SEARCH_INDEXER_ASYNC_CLIENT.getSkillsetWithResponse("searchIndexerSkillset") - .subscribe(skillsetWithResponse -> - System.out.printf("The status code of the response is %s. The indexer skillset name is %s.%n", - skillsetWithResponse.getStatusCode(), skillsetWithResponse.getValue().getName())); - // END: com.azure.search.documents.indexes.SearchIndexerAsyncClient.getSkillsetWithResponse#String - } - - /** - * Code snippet for {@link SearchIndexerAsyncClient#listSkillsets()} - */ - public void listIndexerSkillsetAsync() { - // BEGIN: com.azure.search.documents.indexes.SearchIndexerAsyncClient.listSkillsets - SEARCH_INDEXER_ASYNC_CLIENT.listSkillsets() - .subscribe(skillset -> - System.out.printf("The skillset name is %s. The ETag of skillset is %s.%n", skillset.getName(), - skillset.getETag())); - // END: com.azure.search.documents.indexes.SearchIndexerAsyncClient.listSkillsets - } - - /** - * Code snippet for {@link SearchIndexerAsyncClient#listSkillsetNames()} - */ - public void listIndexerSkillsetNamesAsync() { - // BEGIN: com.azure.search.documents.indexes.SearchIndexerAsyncClient.listSkillsetNames - SEARCH_INDEXER_ASYNC_CLIENT.listSkillsetNames() - .subscribe(skillsetName -> System.out.printf("The indexer skillset name is %s.%n", skillsetName)); - // END: com.azure.search.documents.indexes.SearchIndexerAsyncClient.listSkillsetNames - } - - /** - * Code snippet for {@link SearchIndexerAsyncClient#createOrUpdateSkillset(SearchIndexerSkillset)} - */ - public void createOrUpdateIndexerSkillsetAsync() { - // BEGIN: com.azure.search.documents.indexes.SearchIndexerAsyncClient.createOrUpdateIndexerSkillset#SearchIndexerSkillset - SEARCH_INDEXER_ASYNC_CLIENT.getSkillset("searchIndexerSkillset") - .flatMap(indexerSkillset -> { - indexerSkillset.setDescription("This is new description!"); - return SEARCH_INDEXER_ASYNC_CLIENT.createOrUpdateSkillset(indexerSkillset); - }).subscribe(updateSkillset -> - System.out.printf("The indexer skillset name is %s. The description of indexer skillset is %s.%n", - updateSkillset.getName(), updateSkillset.getDescription())); - // END: com.azure.search.documents.indexes.SearchIndexerAsyncClient.createOrUpdateIndexerSkillset#SearchIndexerSkillset - } - - /** - * Code snippet for {@link SearchIndexerAsyncClient#createOrUpdateSkillsetWithResponse(SearchIndexerSkillset, boolean)} - */ - public void createOrUpdateIndexerSkillsetWithResponseAsync() { - // BEGIN: com.azure.search.documents.indexes.SearchIndexerAsyncClient.createOrUpdateSkillsetWithResponse#SearchIndexerSkillset-boolean - SEARCH_INDEXER_ASYNC_CLIENT.getSkillset("searchIndexerSkillset") - .flatMap(indexerSkillset -> { - indexerSkillset.setDescription("This is new description!"); - return SEARCH_INDEXER_ASYNC_CLIENT.createOrUpdateSkillsetWithResponse(indexerSkillset, true); - }) - .subscribe(updateSkillsetResponse -> - System.out.printf("The status code of the response is %s.%nThe indexer skillset name is %s. " - + "The description of indexer skillset is %s.%n", updateSkillsetResponse.getStatusCode(), - updateSkillsetResponse.getValue().getName(), - updateSkillsetResponse.getValue().getDescription())); - // END: com.azure.search.documents.indexes.SearchIndexerAsyncClient.createOrUpdateSkillsetWithResponse#SearchIndexerSkillset-boolean - } - - - /** - * Code snippet for {@link SearchIndexerAsyncClient#deleteSkillset(String)} - */ - public void deleteSearchIndexerSkillsetAsync() { - // BEGIN: com.azure.search.documents.indexes.SearchIndexerAsyncClient.deleteSkillset#String - SEARCH_INDEXER_ASYNC_CLIENT.deleteSkillset("searchIndexerSkillset") - .subscribe(); - // END: com.azure.search.documents.indexes.SearchIndexerAsyncClient.deleteSkillset#String - } - - /** - * Code snippet for {@link SearchIndexerAsyncClient#deleteSkillsetWithResponse(SearchIndexerSkillset, boolean)} - */ - public void deleteSearchIndexerSkillsetWithResponseAsync() { - // BEGIN: com.azure.search.documents.indexes.SearchIndexerAsyncClient.deleteSkillsetWithResponse#SearchIndexerSkillset-boolean - SEARCH_INDEXER_ASYNC_CLIENT.getSkillset("searchIndexerSkillset") - .flatMap(searchIndexerSkillset -> - SEARCH_INDEXER_ASYNC_CLIENT.deleteSkillsetWithResponse(searchIndexerSkillset, true)) - .subscribe(deleteResponse -> - System.out.printf("The status code of the response is %d.%n", deleteResponse.getStatusCode())); - // END: com.azure.search.documents.indexes.SearchIndexerAsyncClient.deleteSkillsetWithResponse#SearchIndexerSkillset-boolean - } -} diff --git a/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/SearchOptionsAsyncExample.java b/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/SearchOptionsAsyncExample.java deleted file mode 100644 index 264e0b6fb49d..000000000000 --- a/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/SearchOptionsAsyncExample.java +++ /dev/null @@ -1,104 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.search.documents; - -import com.azure.core.credential.AzureKeyCredential; -import com.azure.core.util.Configuration; -import com.azure.search.documents.models.SearchOptions; -import com.azure.search.documents.util.SearchPagedFlux; -import com.azure.search.documents.util.SearchPagedResponse; - -import java.util.stream.Stream; - -/** - * This example shows how to work with {@link SearchOptions} while performing searches - *

- * This sample is based on the hotels-sample index available to install from the portal. See Search getting started portal - *

- */ -public class SearchOptionsAsyncExample { - - /** - * From the Azure portal, get your Azure AI Search service URL and API key, and set the values of these - * environment variables: - */ - private static final String ENDPOINT = Configuration.getGlobalConfiguration().get("AZURE_COGNITIVE_SEARCH_ENDPOINT"); - private static final String API_KEY = Configuration.getGlobalConfiguration().get("AZURE_COGNITIVE_SEARCH_API_KEY"); - - private static final String INDEX_NAME = "hotels-sample-index"; - - public static void main(String[] args) { - SearchAsyncClient searchClient = new SearchClientBuilder() - .endpoint(ENDPOINT) - .credential(new AzureKeyCredential(API_KEY)) - .indexName(INDEX_NAME) - .buildAsyncClient(); - - searchResultsAsList(searchClient); - searchResultAsStreamOfPagedResponse(searchClient); - searchResultsCountFormPage(searchClient); - searchResultsCoverageFromPage(searchClient); - searchResultsFacetsFromPage(searchClient); - } - - private static void searchResultsFacetsFromPage(SearchAsyncClient searchClient) { - // Each page in the response of the search query holds the facets value - // Get Facets property from the first page in the response - SearchPagedFlux results = searchClient.search("*", - new SearchOptions().setFacets("Rooms/BaseRate,values:5|8|10")); - - results.getFacets() - .doOnNext(facetResults -> facetResults.forEach((key, value) -> value.forEach(result -> { - System.out.println(key + " :"); - System.out.println(" count: " + result.getCount()); - result.getAdditionalProperties().forEach((f, d) -> System.out.println(" " + f + " : " + d)); - }))) - .block(); - } - - private static void searchResultsCoverageFromPage(SearchAsyncClient searchClient) { - // Each page in the response of the search query holds the coverage value - // Get Coverage property from the first page in the response - SearchPagedFlux results = searchClient.search("*", - new SearchOptions().setMinimumCoverage(80.0)); - - System.out.println("Coverage = " + results.getCoverage().block()); - } - - private static void searchResultsCountFormPage(SearchAsyncClient searchClient) { - // Each page in the response of the search query holds the count value - // Get total search results count - // Get count property from the first page in the response - SearchPagedFlux results = searchClient.search("*", - new SearchOptions().setIncludeTotalCount(true)); - - System.out.println("Count = " + results.getTotalCount().block()); - } - - - private static void searchResultAsStreamOfPagedResponse(SearchAsyncClient searchClient) { - // Converting search results to stream - Stream streamResponse = searchClient.search("*") - .byPage().toStream(); - - streamResponse.forEach(searchPagedResponse -> searchPagedResponse.getElements().forEach(result -> - result.getDocument(SearchDocument.class).forEach((field, value) -> - System.out.println((field + ":" + value))))); - } - - private static void searchResultsAsList(SearchAsyncClient searchClient) { - // Converting search results to list - searchClient.search("*") - .log() - .doOnSubscribe(ignoredVal -> System.out.println("Subscribed to paged flux processing items")) - .doOnNext(result -> - result.getDocument(SearchDocument.class).forEach((field, value) -> - System.out.println((field + ":" + value))) - ) - .doOnComplete(() -> System.out.println("Completed processing")) - .collectList() - .block(); - } -} diff --git a/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/SearchOptionsExample.java b/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/SearchOptionsExample.java deleted file mode 100644 index 6a360734c99e..000000000000 --- a/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/SearchOptionsExample.java +++ /dev/null @@ -1,98 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.search.documents; - -import com.azure.core.credential.AzureKeyCredential; -import com.azure.core.util.Configuration; -import com.azure.core.util.Context; -import com.azure.search.documents.models.SearchOptions; -import com.azure.search.documents.models.SearchResult; -import com.azure.search.documents.util.SearchPagedIterable; - -import java.util.stream.Stream; - -/** - * This example shows how to work with {@link SearchOptions} while performing searches - *

- * This sample is based on the hotels-sample index available to install from the portal. - * See https://docs.microsoft.com/azure/search/search-get-started-portal - *

- */ -public class SearchOptionsExample { - - /** - * From the Azure portal, get your Azure AI Search service URL and API key, - * and set the values of these environment variables: - */ - private static final String ENDPOINT = Configuration.getGlobalConfiguration().get("AZURE_COGNITIVE_SEARCH_ENDPOINT"); - private static final String API_KEY = Configuration.getGlobalConfiguration().get("AZURE_COGNITIVE_SEARCH_API_KEY"); - - private static final String INDEX_NAME = "hotels-sample-index"; - - public static void main(String[] args) { - SearchClient searchClient = new SearchClientBuilder() - .endpoint(ENDPOINT) - .credential(new AzureKeyCredential(API_KEY)) - .indexName(INDEX_NAME) - .buildClient(); - - searchResultsAsPagedIterable(searchClient); - searchResultAsStream(searchClient); - searchResultsCountFromPage(searchClient); - searchResultsCoverageFromPage(searchClient); - searchResultsFacets(searchClient); - } - - private static void searchResultsFacets(SearchClient searchClient) { - // Each page in the response of the search query holds the facets value - // Get Facets property from the first page in the response - SearchPagedIterable results = searchClient.search("*", - new SearchOptions().setFacets("Rooms/BaseRate,values:5|8|10"), Context.NONE); - results.getFacets().forEach((k, v) -> { - v.forEach(result -> { - System.out.println(k + " :"); - System.out.println(" count: " + result.getCount()); - result.getAdditionalProperties().forEach((f, d) -> - System.out.println(" " + f + " : " + d) - ); - }); - }); - } - - private static void searchResultsCoverageFromPage(SearchClient searchClient) { - // Each page in the response of the search query holds the coverage value - // Accessing Coverage property when iterating by page - SearchPagedIterable results = searchClient.search("*", - new SearchOptions().setMinimumCoverage(80.0), Context.NONE); - - System.out.println("Coverage = " + results.getCoverage()); - } - - private static void searchResultsCountFromPage(SearchClient searchClient) { - // Each page in the response of the search query holds the count value - // Get total search results count - // Get count property from the first page in the response - SearchPagedIterable results = searchClient.search("*", - new SearchOptions().setIncludeTotalCount(true), Context.NONE); - - System.out.println("Count = " + results.getTotalCount()); - } - - private static void searchResultAsStream(SearchClient searchClient) { - // Converting search results to stream - SearchPagedIterable results = searchClient.search("*"); - Stream resultStream = results.stream(); - resultStream.forEach(result -> - result.getDocument(SearchDocument.class).forEach((field, value) -> - System.out.println((field + ":" + value))) - ); - } - - private static void searchResultsAsPagedIterable(SearchClient searchClient) { - searchClient.search("*").forEach(result -> - result.getDocument(SearchDocument.class).forEach((field, value) -> - System.out.println((field + ":" + value))) - ); - } -} diff --git a/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/SearchRequestUrlRewriterPolicy.java b/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/SearchRequestUrlRewriterPolicy.java deleted file mode 100644 index 21db634519c8..000000000000 --- a/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/SearchRequestUrlRewriterPolicy.java +++ /dev/null @@ -1,90 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -package com.azure.search.documents; - -import com.azure.core.http.HttpPipelineCallContext; -import com.azure.core.http.HttpPipelineNextPolicy; -import com.azure.core.http.HttpPipelineNextSyncPolicy; -import com.azure.core.http.HttpRequest; -import com.azure.core.http.HttpResponse; -import com.azure.core.http.policy.HttpPipelinePolicy; -import com.azure.core.util.UrlBuilder; -import reactor.core.publisher.Mono; - -/** - * This an example {@link HttpPipelinePolicy} that can rewrite request URLs to replace the OData URL syntax - * ({@code /docs('key')}) with standard URL syntax ({@code /docs/key}). - */ -public final class SearchRequestUrlRewriterPolicy implements HttpPipelinePolicy { - - @Override - public Mono process(HttpPipelineCallContext context, HttpPipelineNextPolicy next) { - context.setHttpRequest(rewriteUrl(context.getHttpRequest())); - return next.process(); - } - - @Override - public HttpResponse processSync(HttpPipelineCallContext context, HttpPipelineNextSyncPolicy next) { - context.setHttpRequest(rewriteUrl(context.getHttpRequest())); - return next.processSync(); - } - - private static HttpRequest rewriteUrl(HttpRequest request) { - UrlBuilder urlBuilder = UrlBuilder.parse(request.getUrl()); - String path = urlBuilder.getPath(); - - if (path.startsWith("/aliases('")) { - urlBuilder.setPath(createNewPath(path, "/aliases/", 10)); - } else if (path.startsWith("/datasources('")) { - urlBuilder.setPath(createNewPath(path, "/datasources/", 14)); - } else if (path.startsWith("/indexers('")) { - urlBuilder.setPath(createNewPath(path, "/indexers/", 11)); - } else if (path.startsWith("/indexes('")) { - // Indexes is special as it can be used for either the management-style APIs managing the index or with - // document retrieval. - // - // So it needs to replace the OData URL syntax for the index name and also check if it contains the - // document retrieval path. - int documentRetrievalIndex = path.indexOf("/docs('"); - if (documentRetrievalIndex != -1) { - int odataUrlClose = path.indexOf("')", 10); - StringBuilder newPath = new StringBuilder(path.length()) - .append("/indexes/") - .append(path, 10, odataUrlClose) - .append(path, odataUrlClose + 2, documentRetrievalIndex) - .append("/docs/"); - - odataUrlClose = path.indexOf("')", documentRetrievalIndex + 7); - newPath.append(path, documentRetrievalIndex + 7, odataUrlClose); - - if (odataUrlClose < path.length() - 2) { - newPath.append(path, odataUrlClose + 2, path.length()); - } - - urlBuilder.setPath(newPath.toString()); - } else { - urlBuilder.setPath(createNewPath(path, "/indexes/", 10)); - } - } else if (path.startsWith("/skillsets('")) { - urlBuilder.setPath(createNewPath(path, "/skillsets/", 12)); - } else if (path.startsWith("/synonymmaps('")) { - urlBuilder.setPath(createNewPath(path, "/synonymmaps/", 14)); - } else { - return request; - } - - return request.setUrl(urlBuilder.toString()); - } - - private static String createNewPath(String path, String pathSegment, int startIndex) { - int odataUrlClose = path.indexOf("')", startIndex); - StringBuilder newPath = - new StringBuilder(path.length()).append(pathSegment).append(path, startIndex, odataUrlClose); - - if (odataUrlClose < path.length() - 2) { - newPath.append(path, odataUrlClose + 2, path.length()); - } - - return newPath.toString(); - } -} diff --git a/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/SearchSuggestionExample.java b/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/SearchSuggestionExample.java deleted file mode 100644 index 6bd6e1b86280..000000000000 --- a/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/SearchSuggestionExample.java +++ /dev/null @@ -1,89 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.search.documents; - -import com.azure.core.credential.AzureKeyCredential; -import com.azure.core.http.rest.PagedIterableBase; -import com.azure.core.util.Configuration; -import com.azure.core.util.Context; -import com.azure.search.documents.models.SuggestOptions; -import com.azure.search.documents.models.SuggestResult; -import com.azure.search.documents.util.SuggestPagedResponse; - -import java.util.Iterator; -import java.util.List; - -/** - * This example shows how to work with suggestions and search results - *

- * This sample is based on the hotels-sample index available to install from the portal. - * See https://docs.microsoft.com/azure/search/search-get-started-portal - */ -public class SearchSuggestionExample { - - /** - * From the Azure portal, get your Azure AI Search service URL and API key, - * and set the values of these environment variables: - */ - private static final String ENDPOINT = Configuration.getGlobalConfiguration().get("AZURE_COGNITIVE_SEARCH_ENDPOINT"); - private static final String API_KEY = Configuration.getGlobalConfiguration().get("AZURE_COGNITIVE_SEARCH_API_KEY"); - - private static final String INDEX_NAME = "hotels-sample-index"; - - public static void main(String[] args) { - SearchClient client = new SearchClientBuilder() - .endpoint(ENDPOINT) - .credential(new AzureKeyCredential(API_KEY)) - .indexName(INDEX_NAME) - .buildClient(); - - suggestWithHighlights(client); - suggestWithFuzzySearch(client); - } - - private static void suggestWithHighlights(SearchClient searchClient) { - SuggestOptions suggestOptions = new SuggestOptions() - .setHighlightPreTag("") - .setHighlightPostTag("") - .setFilter("Category eq 'Luxury'") - .setTop(1); - - PagedIterableBase suggestResult = - searchClient.suggest("hotel", "sg", suggestOptions, Context.NONE); - Iterator iterator = suggestResult.iterableByPage().iterator(); - - List response = iterator.next().getValue(); - System.out.println("Received results with highlight:"); - response.forEach(r -> System.out.println(r.getText())); - - /* Output: - Received results with highlight: - Best hotel in town if you like luxury hotels. They have an amazing infinity pool, a spa, and - a really helpful concierge. The location is perfect -- right downtown, close to all the tourist - attractions. We highly recommend this hotel. - */ - } - - private static void suggestWithFuzzySearch(SearchClient searchClient) { - SuggestOptions suggestOptions = new SuggestOptions() - .setUseFuzzyMatching(true); - - PagedIterableBase suggestResult = - searchClient.suggest("hitel", "sg", suggestOptions, Context.NONE); - Iterator iterator = suggestResult.iterableByPage().iterator(); - - List response = iterator.next().getValue(); - System.out.println("Received results with fuzzy option:"); - response.forEach(r -> System.out.println(r.getText())); - - /* Output: - Received results with fuzzy option: - Countryside Hotel - Pretty good hotel - Another good hotel - Very popular hotel in town - Cheapest hotel in town. Infact, a motel. - */ - } -} diff --git a/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/SemanticSearchExample.java b/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/SemanticSearchExample.java deleted file mode 100644 index e28530b425fd..000000000000 --- a/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/SemanticSearchExample.java +++ /dev/null @@ -1,304 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -package com.azure.search.documents; - -import com.azure.core.credential.AzureKeyCredential; -import com.azure.core.util.Configuration; -import com.azure.core.util.Context; -import com.azure.core.util.CoreUtils; -import com.azure.json.JsonReader; -import com.azure.json.JsonSerializable; -import com.azure.json.JsonToken; -import com.azure.json.JsonWriter; -import com.azure.search.documents.indexes.SearchIndexClient; -import com.azure.search.documents.indexes.SearchIndexClientBuilder; -import com.azure.search.documents.indexes.SearchableField; -import com.azure.search.documents.indexes.SimpleField; -import com.azure.search.documents.indexes.models.SearchField; -import com.azure.search.documents.indexes.models.SearchFieldDataType; -import com.azure.search.documents.indexes.models.SearchIndex; -import com.azure.search.documents.indexes.models.SemanticConfiguration; -import com.azure.search.documents.indexes.models.SemanticField; -import com.azure.search.documents.indexes.models.SemanticPrioritizedFields; -import com.azure.search.documents.indexes.models.SemanticSearch; -import com.azure.search.documents.models.QueryAnswer; -import com.azure.search.documents.models.QueryAnswerResult; -import com.azure.search.documents.models.QueryAnswerType; -import com.azure.search.documents.models.QueryCaption; -import com.azure.search.documents.models.QueryCaptionResult; -import com.azure.search.documents.models.QueryCaptionType; -import com.azure.search.documents.models.SearchOptions; -import com.azure.search.documents.models.SearchResult; -import com.azure.search.documents.models.SemanticErrorMode; -import com.azure.search.documents.models.SemanticSearchOptions; -import com.azure.search.documents.models.SemanticSearchResults; -import com.azure.search.documents.util.SearchPagedIterable; - -import java.io.IOException; -import java.time.Duration; -import java.util.Arrays; -import java.util.List; - -import static com.azure.search.documents.TestHelpers.waitForIndexing; - -/** - * This example shows how to work with {@link SemanticSearch} while performing searches. - *

- * This sample is based on the hotels-sample index available to install from the portal. - *

- * See https://docs.microsoft.com/azure/search/search-get-started-portal - */ -public class SemanticSearchExample { - /** - * From the Azure portal, get your Azure AI Search service URL and API key, - * and set the values of these environment variables: - */ - private static final String ENDPOINT = Configuration.getGlobalConfiguration().get("AZURE_COGNITIVE_SEARCH_ENDPOINT"); - private static final String API_KEY = Configuration.getGlobalConfiguration().get("AZURE_COGNITIVE_SEARCH_API_KEY"); - - private static final String INDEX_NAME = "hotels-semantic-sample-index"; - - public static void main(String[] args) { - SearchIndexClient searchIndexClient = new SearchIndexClientBuilder() - .endpoint(ENDPOINT) - .credential(new AzureKeyCredential(API_KEY)) - .buildClient(); - - SearchClient searchClient = createSearchIndex(searchIndexClient); - - try { - semanticSearch(searchClient); - } finally { - // Cleanup the example index. - searchIndexClient.deleteIndex(INDEX_NAME); - } - } - - /** - * Creates a Cognitive Search index for the hotels example data. - *

- * This method will also upload a set of documents. - * - * @param searchIndexClient The {@link SearchIndexClient} to use for creating the index. - * @return The {@link SearchClient} to use for querying the index. - */ - public static SearchClient createSearchIndex(SearchIndexClient searchIndexClient) { - // Create the search index. - SearchIndex searchIndex = new SearchIndex(INDEX_NAME) - .setFields( - new SearchField("HotelId", SearchFieldDataType.STRING) - .setKey(true), - new SearchField("HotelName", SearchFieldDataType.STRING) - .setSearchable(true) - .setFilterable(true) - .setSortable(true), - new SearchField("Description", SearchFieldDataType.STRING) - .setSearchable(true), - new SearchField("Category", SearchFieldDataType.STRING) - .setSearchable(true) - .setFilterable(true) - .setSortable(true) - .setFacetable(true)) - .setSemanticSearch(new SemanticSearch().setConfigurations(Arrays.asList(new SemanticConfiguration( - "my-semantic-config", new SemanticPrioritizedFields() - .setTitleField(new SemanticField("HotelName")) - .setContentFields(new SemanticField("Description")) - .setKeywordsFields(new SemanticField("Category")))))); - - searchIndexClient.createOrUpdateIndex(searchIndex); - - SearchClient searchClient = searchIndexClient.getSearchClient(INDEX_NAME); - searchClient.uploadDocuments(getIndexDocuments()); - - waitForIndexing(); - - return searchClient; - } - - /** - * Example of using semantic search. - * - * @param searchClient The {@link SearchClient} to use for querying the index. - */ - public static void semanticSearch(SearchClient searchClient) { - SearchOptions searchOptions = new SearchOptions() - .setSemanticSearchOptions(new SemanticSearchOptions() - .setSemanticConfigurationName("my-semantic-config") - .setQueryAnswer(new QueryAnswer(QueryAnswerType.EXTRACTIVE)) - .setQueryCaption(new QueryCaption(QueryCaptionType.EXTRACTIVE)) - .setErrorMode(SemanticErrorMode.PARTIAL) - .setMaxWaitDuration(Duration.ofSeconds(5))); - - SearchPagedIterable results = searchClient.search( - "Is there any hotel located on the main commercial artery of the city in the heart of New York?", - searchOptions, Context.NONE); - - int count = 0; - System.out.println("Semantic Hybrid Search Results:"); - - SemanticSearchResults semanticSearchResults = results.getSemanticResults(); - - System.out.println("Semantic Query Rewrites Result Type: " + semanticSearchResults.getSemanticQueryRewritesResultType()); - - - - System.out.println("Semantic Results Type: " + semanticSearchResults.getResultsType()); - - if (semanticSearchResults.getErrorReason() != null) { - System.out.println("Semantic Error Reason: " + semanticSearchResults.getErrorReason()); - } - - System.out.println("Query Answers:"); - for (QueryAnswerResult result : semanticSearchResults.getQueryAnswers()) { - System.out.println("Answer Highlights: " + result.getHighlights()); - System.out.println("Answer Text: " + result.getText()); - } - - for (SearchResult result : results) { - count++; - Hotel doc = result.getDocument(Hotel.class); - System.out.printf("%s: %s%n", doc.getHotelId(), doc.getHotelName()); - - if (result.getSemanticSearch().getQueryCaptions() != null) { - QueryCaptionResult caption = result.getSemanticSearch().getQueryCaptions().get(0); - if (!CoreUtils.isNullOrEmpty(caption.getHighlights())) { - System.out.println("Caption Highlights: " + caption.getHighlights()); - } else { - System.out.println("Caption Text: " + caption.getText()); - } - } - } - - System.out.println("Total number of search results: " + count); - } - - /** - * Hotel model. - */ - public static final class Hotel implements JsonSerializable { - @SimpleField(isKey = true) - private String hotelId; - @SearchableField(isFilterable = true, analyzerName = "en.lucene") - private String hotelName; - @SearchableField(analyzerName = "en.lucene") - private String description; - @SearchableField(isFilterable = true, isFacetable = true, isSortable = true) - private String category; - - public Hotel() { - } - - public String getHotelId() { - return hotelId; - } - - public Hotel setHotelId(String hotelId) { - this.hotelId = hotelId; - return this; - } - - public String getHotelName() { - return hotelName; - } - - public Hotel setHotelName(String hotelName) { - this.hotelName = hotelName; - return this; - } - - public String getDescription() { - return description; - } - - public Hotel setDescription(String description) { - this.description = description; - return this; - } - - public String getCategory() { - return category; - } - - public Hotel setCategory(String category) { - this.category = category; - return this; - } - - @Override - public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { - return jsonWriter.writeStartObject() - .writeStringField("HotelId", hotelId) - .writeStringField("HotelName", hotelName) - .writeStringField("Description", description) - .writeStringField("Category", category) - .writeEndObject(); - } - - public static Hotel fromJson(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - Hotel hotel = new Hotel(); - - while (reader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = reader.getFieldName(); - reader.nextToken(); - - if ("HotelId".equals(fieldName)) { - hotel.hotelId = reader.getString(); - } else if ("HotelName".equals(fieldName)) { - hotel.hotelName = reader.getString(); - } else if ("Description".equals(fieldName)) { - hotel.description = reader.getString(); - } else if ("Category".equals(fieldName)) { - hotel.category = reader.getString(); - } else { - reader.skipChildren(); - } - } - - return hotel; - }); - } - } - - /** - * Gets a list of hotels. - * - * @return A list of hotels. - */ - public static List getIndexDocuments() { - return Arrays.asList( - new Hotel() - .setHotelId("1") - .setHotelName("Fancy Stay") - .setDescription("Best hotel in town if you like luxury hotels. They have an amazing infinity pool, a " - + "spa, and a really helpful concierge. The location is perfect -- right downtown, close to all " - + "the tourist attractions. We highly recommend this hotel.") - .setCategory("Luxury"), - new Hotel() - .setHotelId("2") - .setHotelName("Roach Motel") - .setDescription("Below average motel with a extremely rude staff, no complimentary breakfast, and " - + "noisy rooms riddled with cockroaches.") - .setCategory("Budget"), - new Hotel() - .setHotelId("3") - .setHotelName("EconoStay") - .setDescription("Very popular hotel in town. It's located downtown, close to all tourist attractions.") - .setCategory("Budget"), - new Hotel() - .setHotelId("4") - .setHotelName("Modern Stay") - .setDescription("Modern architecture, very polite staff and very clean. Also very affordable.") - .setCategory("Luxury"), - new Hotel() - .setHotelId("5") - .setHotelName("Secret Point") - .setDescription("The hotel is ideally located on the main commercial artery of the city in the heart " - + "of New York. A few minutes away is Time's Square and the historic centre of the city, as well " - + "as other places of interest that make New York one of America's most attractive and " - + "cosmopolitan cities.") - .setCategory("Boutique")); - - // Add more hotel documents here... - } -} diff --git a/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/SynonymMapsCreateExample.java b/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/SynonymMapsCreateExample.java deleted file mode 100644 index ce44ce814130..000000000000 --- a/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/SynonymMapsCreateExample.java +++ /dev/null @@ -1,66 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.search.documents; - -import com.azure.core.credential.AzureKeyCredential; -import com.azure.core.util.Configuration; -import com.azure.search.documents.indexes.SearchIndexClient; -import com.azure.search.documents.indexes.SearchIndexClientBuilder; -import com.azure.search.documents.indexes.models.SearchField; -import com.azure.search.documents.indexes.models.SearchFieldDataType; -import com.azure.search.documents.indexes.models.SearchIndex; -import com.azure.search.documents.indexes.models.SynonymMap; - -import java.util.Arrays; - -/** - * This example shows how to create an index with a synonym map - * See Search getting started portal - */ -public class SynonymMapsCreateExample { - - /** - * From the Azure portal, get your Azure AI Search service URL and API key, - * and set the values of these environment variables: - */ - private static final String ENDPOINT = Configuration.getGlobalConfiguration().get("AZURE_COGNITIVE_SEARCH_ENDPOINT"); - private static final String API_ADMIN_KEY = Configuration.getGlobalConfiguration().get("AZURE_COGNITIVE_SEARCH_ADMIN_KEY"); - - public static void main(String[] args) { - SearchIndexClient serviceClient = new SearchIndexClientBuilder() - .endpoint(ENDPOINT) - .credential(new AzureKeyCredential(API_ADMIN_KEY)) - .buildClient(); - - String synonymMapName = "desc-synonymmap"; - - System.out.println("Create synonym map...\n"); - createSynonymMap(serviceClient, synonymMapName); - - System.out.println("Create index and assign synonym map to it...\n"); - SearchIndex searchIndex = assignSynonymMapToIndex(synonymMapName); - System.out.println("Assigned synonym map: " + searchIndex.getFields().stream() - .filter(field -> field.getSynonymMapNames() != null) - .findFirst().get()); - - System.out.println("Complete....\n"); - - // Clean up resources - serviceClient.deleteSynonymMap(synonymMapName); - } - - private static void createSynonymMap(SearchIndexClient serviceClient, String synonymMapName) { - SynonymMap synonymMap = new SynonymMap(synonymMapName, - "hotel, motel\ninternet,wifi\nfive star=>luxury\neconomy,inexpensive=>budget"); - serviceClient.createSynonymMap(synonymMap); - } - - private static SearchIndex assignSynonymMapToIndex(String synonymMapName) { - return new SearchIndex("hotels", Arrays.asList( - new SearchField("HotelId", SearchFieldDataType.STRING) - .setKey(true), - new SearchField("HotelName", SearchFieldDataType.STRING) - .setSynonymMapNames(synonymMapName))); - } -} diff --git a/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/VectorSearchExample.java b/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/VectorSearchExample.java deleted file mode 100644 index 218fdf6f8c5d..000000000000 --- a/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/VectorSearchExample.java +++ /dev/null @@ -1,470 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.search.documents; - -import com.azure.core.credential.AzureKeyCredential; -import com.azure.core.util.Configuration; -import com.azure.core.util.Context; -import com.azure.core.util.CoreUtils; -import com.azure.json.JsonReader; -import com.azure.json.JsonSerializable; -import com.azure.json.JsonToken; -import com.azure.json.JsonWriter; -import com.azure.search.documents.indexes.SearchIndexClient; -import com.azure.search.documents.indexes.SearchIndexClientBuilder; -import com.azure.search.documents.indexes.SearchableField; -import com.azure.search.documents.indexes.SimpleField; -import com.azure.search.documents.indexes.models.HnswAlgorithmConfiguration; -import com.azure.search.documents.indexes.models.SearchField; -import com.azure.search.documents.indexes.models.SearchFieldDataType; -import com.azure.search.documents.indexes.models.SearchIndex; -import com.azure.search.documents.indexes.models.SemanticConfiguration; -import com.azure.search.documents.indexes.models.SemanticField; -import com.azure.search.documents.indexes.models.SemanticPrioritizedFields; -import com.azure.search.documents.indexes.models.SemanticSearch; -import com.azure.search.documents.indexes.models.VectorSearch; -import com.azure.search.documents.indexes.models.VectorSearchProfile; -import com.azure.search.documents.models.QueryAnswer; -import com.azure.search.documents.models.QueryAnswerResult; -import com.azure.search.documents.models.QueryAnswerType; -import com.azure.search.documents.models.QueryCaption; -import com.azure.search.documents.models.QueryCaptionResult; -import com.azure.search.documents.models.QueryCaptionType; -import com.azure.search.documents.models.QueryType; -import com.azure.search.documents.models.SearchOptions; -import com.azure.search.documents.models.SearchResult; -import com.azure.search.documents.models.SemanticSearchOptions; -import com.azure.search.documents.models.VectorFilterMode; -import com.azure.search.documents.models.VectorQuery; -import com.azure.search.documents.models.VectorSearchOptions; -import com.azure.search.documents.models.VectorizedQuery; -import com.azure.search.documents.util.SearchPagedIterable; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.List; - -import static com.azure.search.documents.TestHelpers.waitForIndexing; - -/** - * This example shows how to work with {@link VectorSearch} while performing searches. - *

- * This sample is based on the hotels-sample index available to install from the portal with an additional field for - * vector description. - *

- * See https://docs.microsoft.com/azure/search/search-get-started-portal - */ -public class VectorSearchExample { - /** - * From the Azure portal, get your Azure AI Search service URL and API key, - * and set the values of these environment variables: - */ - private static final String ENDPOINT = Configuration.getGlobalConfiguration().get("AZURE_COGNITIVE_SEARCH_ENDPOINT"); - private static final String API_KEY = Configuration.getGlobalConfiguration().get("AZURE_COGNITIVE_SEARCH_API_KEY"); - - private static final String INDEX_NAME = "hotels-vector-sample-index"; - - public static void main(String[] args) { - SearchIndexClient searchIndexClient = new SearchIndexClientBuilder() - .endpoint(ENDPOINT) - .credential(new AzureKeyCredential(API_KEY)) - .buildClient(); - - SearchClient searchClient = createSearchIndex(searchIndexClient); - - try { - singleVectorSearch(searchClient); - singleVectorSearchWithFilter(searchClient); - simpleHybridSearch(searchClient); - multiVectorSearch(searchClient); - semanticHybridSearch(searchClient); - } finally { - // Cleanup the example index. - searchIndexClient.deleteIndex(INDEX_NAME); - } - } - - /** - * Creates a Cognitive Search index for the hotels example data with an additional field for vector search, using - * the data type {@code SearchFieldDataType.collection(SearchFieldDataType.SINGLE)}. - *

- * This method will also upload a set of documents with pre-computed vector descriptions. - * - * @param searchIndexClient The {@link SearchIndexClient} to use for creating the index. - * @return The {@link SearchClient} to use for querying the index. - */ - public static SearchClient createSearchIndex(SearchIndexClient searchIndexClient) { - // Create the search index, including the new SearchFieldDataType.Single field for vector description. - SearchIndex searchIndex = new SearchIndex(INDEX_NAME) - .setFields( - new SearchField("HotelId", SearchFieldDataType.STRING) - .setKey(true) - .setFilterable(true) - .setSortable(true) - .setFacetable(true), - new SearchField("HotelName", SearchFieldDataType.STRING) - .setSearchable(true) - .setFilterable(true) - .setSortable(true), - new SearchField("Description", SearchFieldDataType.STRING) - .setSearchable(true) - .setFilterable(true), - new SearchField("DescriptionVector", SearchFieldDataType.collection(SearchFieldDataType.SINGLE)) - .setSearchable(true) - .setVectorSearchDimensions(1536) - // This must match a vector search configuration name. - .setVectorSearchProfileName("my-vector-profile"), - new SearchField("Category", SearchFieldDataType.STRING) - .setSearchable(true) - .setFilterable(true) - .setSortable(true) - .setFacetable(true)) - // VectorSearch configuration is required for a vector field. - // The name used for the vector search algorithm configuration must match the configuration used by the - // search field used for vector search. - .setVectorSearch(new VectorSearch() - .setProfiles(Collections.singletonList( - new VectorSearchProfile("my-vector-profile", "my-vector-config"))) - .setAlgorithms(Collections.singletonList( - new HnswAlgorithmConfiguration("my-vector-config")))) - .setSemanticSearch(new SemanticSearch().setConfigurations(Arrays.asList(new SemanticConfiguration( - "my-semantic-config", new SemanticPrioritizedFields() - .setTitleField(new SemanticField("HotelName")) - .setContentFields(new SemanticField("Description")) - .setKeywordsFields(new SemanticField("Category")))))); - - searchIndexClient.createOrUpdateIndex(searchIndex); - - SearchClient searchClient = searchIndexClient.getSearchClient(INDEX_NAME); - searchClient.uploadDocuments(getIndexDocuments()); - - waitForIndexing(); - - return searchClient; - } - - /** - * Example of using vector search without any other search parameters, such as a search query or filters. - * - * @param searchClient The {@link SearchClient} to use for querying the index. - */ - public static void singleVectorSearch(SearchClient searchClient) { - // Example of using vector search without using a search query or any filters. - List vectorizedResult = VectorSearchEmbeddings.SEARCH_VECTORIZE_DESCRIPTION; // "Top hotels in town" - VectorQuery vectorizableQuery = new VectorizedQuery(vectorizedResult) - .setKNearestNeighborsCount(3) - // Set the fields to compare the vector against. This is a comma-delimited list of field names. - .setFields("DescriptionVector"); - - SearchPagedIterable searchResults = searchClient.search(null, new SearchOptions() - .setVectorSearchOptions(new VectorSearchOptions().setQueries(vectorizableQuery)), - Context.NONE); - - int count = 0; - System.out.println("Single Vector Search Results:"); - for (SearchResult searchResult : searchResults) { - count++; - VectorHotel doc = searchResult.getDocument(VectorHotel.class); - System.out.printf("%s: %s%n", doc.getHotelId(), doc.getHotelName()); - } - System.out.println("Total number of search results: " + count); - } - - /** - * Example of using vector search with a post-search filter. - * - * @param searchClient The {@link SearchClient} to use for querying the index. - */ - public static void singleVectorSearchWithFilter(SearchClient searchClient) { - // Example of using vector search with a filter. - List vectorizedResult = VectorSearchEmbeddings.SEARCH_VECTORIZE_DESCRIPTION; // "Top hotels in town" - VectorQuery vectorizableQuery = new VectorizedQuery(vectorizedResult) - .setKNearestNeighborsCount(3) - // Set the fields to compare the vector against. This is a comma-delimited list of field names. - .setFields("DescriptionVector"); - - SearchPagedIterable searchResults = searchClient.search(null, new SearchOptions() - .setVectorSearchOptions(new VectorSearchOptions() - .setQueries(vectorizableQuery) - .setFilterMode(VectorFilterMode.POST_FILTER)) - .setFilter("Category eq 'Luxury'"), Context.NONE); - - int count = 0; - System.out.println("Single Vector Search With Filter Results:"); - for (SearchResult searchResult : searchResults) { - count++; - VectorHotel doc = searchResult.getDocument(VectorHotel.class); - System.out.printf("%s: %s%n", doc.getHotelId(), doc.getHotelName()); - } - System.out.println("Total number of search results: " + count); - } - - /** - * Example of using vector search with a query in addition to vectorization. - * - * @param searchClient The {@link SearchClient} to use for querying the index. - */ - public static void simpleHybridSearch(SearchClient searchClient) { - // Example of using vector search with a query in addition to vectorization. - List vectorizedResult = VectorSearchEmbeddings.SEARCH_VECTORIZE_DESCRIPTION; // "Top hotels in town" - VectorQuery vectorizableQuery = new VectorizedQuery(vectorizedResult) - .setKNearestNeighborsCount(3) - // Set the fields to compare the vector against. This is a comma-delimited list of field names. - .setFields("DescriptionVector"); - - SearchPagedIterable searchResults = searchClient.search("Top hotels in town", new SearchOptions() - .setVectorSearchOptions(new VectorSearchOptions().setQueries(vectorizableQuery)), Context.NONE); - - int count = 0; - System.out.println("Simple Hybrid Search Results:"); - for (SearchResult searchResult : searchResults) { - count++; - VectorHotel doc = searchResult.getDocument(VectorHotel.class); - System.out.printf("%s: %s%n", doc.getHotelId(), doc.getHotelName()); - } - System.out.println("Total number of search results: " + count); - } - - /** - * Example of using vector search with a semantic query in addition to vectorization. - *

- * Due to limited availability of Semantic Search this method isn't called in the example. If you know you have - * access to this feature, you can uncomment the line calling this method in the 'main' method. - * - * @param searchClient The {@link SearchClient} to use for querying the index. - */ - public static void semanticHybridSearch(SearchClient searchClient) { - // Example of using vector search with a semantic query in addition to vectorization. - List vectorizedResult = VectorSearchEmbeddings.SEARCH_VECTORIZE_DESCRIPTION; // "Top hotels in town" - VectorQuery vectorizableQuery = new VectorizedQuery(vectorizedResult) - .setKNearestNeighborsCount(3) - // Set the fields to compare the vector against. This is a comma-delimited list of field names. - .setFields("DescriptionVector"); - - SearchOptions searchOptions = new SearchOptions() - .setQueryType(QueryType.SEMANTIC) - .setVectorSearchOptions(new VectorSearchOptions() - .setQueries(vectorizableQuery)) - .setSemanticSearchOptions(new SemanticSearchOptions() - .setSemanticConfigurationName("my-semantic-config") - .setQueryAnswer(new QueryAnswer(QueryAnswerType.EXTRACTIVE)) - .setQueryCaption(new QueryCaption(QueryCaptionType.EXTRACTIVE))); - - SearchPagedIterable results = searchClient.search( - "Is there any hotel located on the main commercial artery of the city in the heart of New York?", - searchOptions, Context.NONE); - - int count = 0; - System.out.println("Semantic Hybrid Search Results:"); - - System.out.println("Query Answer:"); - for (QueryAnswerResult result : results.getSemanticResults().getQueryAnswers()) { - System.out.println("Answer Highlights: " + result.getHighlights()); - System.out.println("Answer Text: " + result.getText()); - } - - for (SearchResult result : results) { - count++; - VectorHotel doc = result.getDocument(VectorHotel.class); - System.out.printf("%s: %s%n", doc.getHotelId(), doc.getHotelName()); - - if (result.getSemanticSearch().getQueryCaptions() != null) { - QueryCaptionResult caption = result.getSemanticSearch().getQueryCaptions().get(0); - if (!CoreUtils.isNullOrEmpty(caption.getHighlights())) { - System.out.println("Caption Highlights: " + caption.getHighlights()); - } else { - System.out.println("Caption Text: " + caption.getText()); - } - } - } - - System.out.println("Total number of search results: " + count); - } - - public static void multiVectorSearch(SearchClient searchClient) { - // Example of using multiple vectors in search without using a search query or any filters. - List vectorizedResult = VectorSearchEmbeddings.HOTEL1_VECTORIZE_DESCRIPTION; - VectorQuery firstVectorizableQuery = new VectorizedQuery(vectorizedResult) - .setKNearestNeighborsCount(3) - // Set the fields to compare the vector against. This is a comma-delimited list of field names. - .setFields("DescriptionVector"); - - List secondVectorizedResult = VectorSearchEmbeddings.HOTEL2_VECTORIZE_DESCRIPTION; - VectorQuery secondVectorizableQuery = new VectorizedQuery(secondVectorizedResult) - .setKNearestNeighborsCount(3) - // Set the fields to compare the vector against. This is a comma-delimited list of field names. - .setFields("DescriptionVector"); - - List thirdVectorizedResult = VectorSearchEmbeddings.HOTEL3_VECTORIZE_DESCRIPTION; - VectorQuery thirdVectorizableQuery = new VectorizedQuery(thirdVectorizedResult) - .setKNearestNeighborsCount(3) - // Set the fields to compare the vector against. This is a comma-delimited list of field names. - .setFields("DescriptionVector"); - - SearchPagedIterable searchResults = searchClient.search(null, new SearchOptions() - .setVectorSearchOptions(new VectorSearchOptions() - .setQueries(firstVectorizableQuery, secondVectorizableQuery, thirdVectorizableQuery)), - Context.NONE); - - int count = 0; - System.out.println("Multi Vector Search Results:"); - for (SearchResult searchResult : searchResults) { - count++; - VectorHotel doc = searchResult.getDocument(VectorHotel.class); - System.out.printf("%s: %s%n", doc.getHotelId(), doc.getHotelName()); - } - System.out.println("Total number of search results: " + count); - } - - /** - * Hotel model with an additional field for the vector description. - */ - public static final class VectorHotel implements JsonSerializable { - @SimpleField(isKey = true) - private String hotelId; - @SearchableField(isFilterable = true, isSortable = true, analyzerName = "en.lucene") - private String hotelName; - @SearchableField(analyzerName = "en.lucene") - private String description; - @SearchableField(vectorSearchDimensions = 1536, vectorSearchProfileName = "my-vector-profile") - private List descriptionVector; - @SearchableField(isFilterable = true, isFacetable = true, isSortable = true) - private String category; - - public VectorHotel() { - } - - public String getHotelId() { - return hotelId; - } - - public VectorHotel setHotelId(String hotelId) { - this.hotelId = hotelId; - return this; - } - - public String getHotelName() { - return hotelName; - } - - public VectorHotel setHotelName(String hotelName) { - this.hotelName = hotelName; - return this; - } - - public String getDescription() { - return description; - } - - public VectorHotel setDescription(String description) { - this.description = description; - return this; - } - - public List getDescriptionVector() { - return descriptionVector == null ? null : Collections.unmodifiableList(descriptionVector); - } - - public VectorHotel setDescriptionVector(List descriptionVector) { - this.descriptionVector = descriptionVector == null ? null : new ArrayList<>(descriptionVector); - return this; - } - - public String getCategory() { - return category; - } - - public VectorHotel setCategory(String category) { - this.category = category; - return this; - } - - @Override - public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { - return jsonWriter.writeStartObject() - .writeStringField("HotelId", hotelId) - .writeStringField("HotelName", hotelName) - .writeStringField("Description", description) - .writeArrayField("DescriptionVector", descriptionVector, JsonWriter::writeFloat) - .writeStringField("Category", category) - .writeEndObject(); - } - - public static VectorHotel fromJson(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - VectorHotel vectorHotel = new VectorHotel(); - - while (reader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = reader.getFieldName(); - reader.nextToken(); - - if ("HotelId".equals(fieldName)) { - vectorHotel.hotelId = reader.getString(); - } else if ("HotelName".equals(fieldName)) { - vectorHotel.hotelName = reader.getString(); - } else if ("Description".equals(fieldName)) { - vectorHotel.description = reader.getString(); - } else if ("DescriptionVector".equals(fieldName)) { - vectorHotel.descriptionVector = reader.readArray(JsonReader::getFloat); - } else if ("Category".equals(fieldName)) { - vectorHotel.category = reader.getString(); - } else { - reader.skipChildren(); - } - } - - return vectorHotel; - }); - } - } - - /** - * Gets a list of hotels with vectorized descriptions. - * - * @return A list of hotels. - */ - public static List getIndexDocuments() { - return Arrays.asList( - new VectorHotel() - .setHotelId("1") - .setHotelName("Fancy Stay") - .setDescription("Best hotel in town if you like luxury hotels. They have an amazing infinity pool, a " - + "spa, and a really helpful concierge. The location is perfect -- right downtown, close to all " - + "the tourist attractions. We highly recommend this hotel.") - .setDescriptionVector(VectorSearchEmbeddings.HOTEL1_VECTORIZE_DESCRIPTION) - .setCategory("Luxury"), - new VectorHotel() - .setHotelId("2") - .setHotelName("Roach Motel") - .setDescription("Below average motel with a extremely rude staff, no complimentary breakfast, and " - + "noisy rooms riddled with cockroaches.") - .setDescriptionVector(VectorSearchEmbeddings.HOTEL2_VECTORIZE_DESCRIPTION) - .setCategory("Budget"), - new VectorHotel() - .setHotelId("3") - .setHotelName("EconoStay") - .setDescription("Very popular hotel in town. It's located downtown, close to all tourist attractions.") - .setDescriptionVector(VectorSearchEmbeddings.HOTEL3_VECTORIZE_DESCRIPTION) - .setCategory("Budget"), - new VectorHotel() - .setHotelId("4") - .setHotelName("Modern Stay") - .setDescription("Modern architecture, very polite staff and very clean. Also very affordable.") - .setDescriptionVector(VectorSearchEmbeddings.HOTEL4_VECTORIZE_DESCRIPTION) - .setCategory("Luxury"), - new VectorHotel() - .setHotelId("5") - .setHotelName("Secret Point") - .setDescription("The hotel is ideally located on the main commercial artery of the city in the heart " - + "of New York. A few minutes away is Time's Square and the historic centre of the city, as well " - + "as other places of interest that make New York one of America's most attractive and " - + "cosmopolitan cities.") - .setDescriptionVector(VectorSearchEmbeddings.HOTEL9_VECTORIZE_DESCRIPTION) - .setCategory("Boutique")); - - // Add more hotel documents here... - } -} diff --git a/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/VectorSearchReducedEmbeddings.java b/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/VectorSearchReducedEmbeddings.java deleted file mode 100644 index 0777707dd1ac..000000000000 --- a/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/VectorSearchReducedEmbeddings.java +++ /dev/null @@ -1,340 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -package com.azure.search.documents; - -import com.azure.ai.openai.OpenAIClient; -import com.azure.ai.openai.OpenAIClientBuilder; -import com.azure.ai.openai.models.Embeddings; -import com.azure.ai.openai.models.EmbeddingsOptions; -import com.azure.core.credential.AzureKeyCredential; -import com.azure.core.credential.KeyCredential; -import com.azure.core.util.Configuration; -import com.azure.core.util.Context; -import com.azure.json.JsonReader; -import com.azure.json.JsonSerializable; -import com.azure.json.JsonToken; -import com.azure.json.JsonWriter; -import com.azure.search.documents.indexes.SearchIndexClient; -import com.azure.search.documents.indexes.SearchIndexClientBuilder; -import com.azure.search.documents.indexes.SearchableField; -import com.azure.search.documents.indexes.SimpleField; -import com.azure.search.documents.indexes.models.AzureOpenAIModelName; -import com.azure.search.documents.indexes.models.AzureOpenAIVectorizer; -import com.azure.search.documents.indexes.models.AzureOpenAIVectorizerParameters; -import com.azure.search.documents.indexes.models.HnswAlgorithmConfiguration; -import com.azure.search.documents.indexes.models.IndexDocumentsBatch; -import com.azure.search.documents.indexes.models.SearchField; -import com.azure.search.documents.indexes.models.SearchFieldDataType; -import com.azure.search.documents.indexes.models.SearchIndex; -import com.azure.search.documents.indexes.models.VectorSearch; -import com.azure.search.documents.indexes.models.VectorSearchProfile; -import com.azure.search.documents.models.SearchOptions; -import com.azure.search.documents.models.SearchResult; -import com.azure.search.documents.models.VectorSearchOptions; -import com.azure.search.documents.models.VectorizableTextQuery; -import com.azure.search.documents.util.SearchPagedIterable; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.List; - -/** - * This sample demonstrates how to create a vector fields index with reduced dimensions, upload reduced embeddings into - * the index, and query the documents. To accomplish this, you can utilize Azure OpenAI embedding models: a smaller and - * highly efficient {@code text-embedding-3-small} model or a larger and more powerful {@code text-embedding-3-large} - * model. These models are significantly more efficient and require less storage space. - */ -public class VectorSearchReducedEmbeddings { - public static void main(String[] args) { - SearchIndex vectorIndex = defineVectorIndex(); - - // After creating an instance of the 'SearchIndex',we need to instantiate the 'SearchIndexClient' and call the - // 'createIndex' method to create the search index. - createVectorIndex(vectorIndex); - - // Now, we can instantiate the 'SearchClient' and upload the documents to the 'Hotel' index we created earlier. - SearchClient searchClient = new SearchClientBuilder().endpoint( - Configuration.getGlobalConfiguration().get("SEARCH_ENDPOINT")) - .indexName("hotel") - .credential(new AzureKeyCredential(Configuration.getGlobalConfiguration().get("SEARCH_API_KEY"))) - .buildClient(); - - // Next, we will create sample hotel documents. The vector field requires submitting text input to an embedding - // model that converts human-readable text into a vector representation. To convert a text query string provided - // by a user into a vector representation, your application should utilize an embedding library that offers this - // functionality. - indexDocuments(searchClient, getHotelDocuments()); - - // When using 'VectorizableTextQuery', the query for a vector field should be the text that will be vectorized - // based on the 'Vectorizer' configuration in order to perform a vector search. - // - // Let's query the index and make sure everything works as implemented. You can also refer to - // https://learn.microsoft.com/azure/search/vector-search-how-to-query for more information on querying vector - // data. - } - - /** - * Let's consider the example of a 'Hotel'. First, we need to create an index for storing hotel information. In this - * index, we will define vector fields called 'DescriptionVector' and 'CategoryVector'. To configure the vector - * field, you need to provide the model dimensions, which indicate the size of the embeddings generated for this - * field. You can pass reduced dimensions and the name of the vector search profile that specifies the algorithm - * configuration, along with 'Vectorizer'. - *

- * In order to get the reduced embeddings using either the {@code text-embedding-3-small} or - * {@code text-embedding-3-large} models, it is necessary to include the 'Dimensions' parameter. This parameter - * configures the desired number of dimensions for the output vector. Therefore, for {@link AzureOpenAIVectorizer}, - * we will retrieve the 'VectorSearchDimensions' that is already specified in the corresponding index field - * definition. However, to ensure that dimensions are only passed along in the vectorizer for a model that supports - * it, we need to pass a required property named 'ModelName'. This property enables the service to determine which - * model we are using, and dimensions will only be passed along when it is for a known supported model name. - *

- * We will create an instace of {@code SearchIndex} and define 'Hotel' fields. - */ - public static SearchIndex defineVectorIndex() { - String vectorSearchProfileName = "my-vector-profile"; - String vectorSearchHnswConfig = "my-hnsw-vector-config"; - String deploymentId = "my-text-embedding-3-small"; - int modelDimensions = 256; // Here's the reduced model dimensions - String indexName = "hotel"; - return new SearchIndex(indexName).setFields(new SearchField("HotelId", SearchFieldDataType.STRING).setKey(true) - .setFilterable(true) - .setSortable(true) - .setFacetable(true), new SearchField("HotelName", SearchFieldDataType.STRING).setSearchable(true) - .setFilterable(true) - .setSortable(true), - new SearchField("Description", SearchFieldDataType.STRING).setSearchable(true).setFilterable(true), - new SearchField("DescriptionVector", - SearchFieldDataType.collection(SearchFieldDataType.SINGLE)).setSearchable(true) - .setFilterable(true) - .setVectorSearchDimensions(modelDimensions) - .setVectorSearchProfileName(vectorSearchProfileName), - new SearchField("Category", SearchFieldDataType.STRING).setSearchable(true) - .setFilterable(true) - .setSortable(true) - .setFacetable(true), - new SearchField("CategoryVector", SearchFieldDataType.collection(SearchFieldDataType.SINGLE)).setSearchable( - true) - .setFilterable(true) - .setVectorSearchDimensions(modelDimensions) - .setVectorSearchProfileName(vectorSearchProfileName)) - .setVectorSearch(new VectorSearch().setProfiles( - new VectorSearchProfile(vectorSearchProfileName, vectorSearchHnswConfig).setVectorizerName("openai")) - .setAlgorithms(new HnswAlgorithmConfiguration(vectorSearchHnswConfig)) - .setVectorizers(Collections.singletonList(new AzureOpenAIVectorizer("openai").setParameters( - new AzureOpenAIVectorizerParameters().setResourceUrl( - Configuration.getGlobalConfiguration().get("OPENAI_ENDPOINT")) - .setApiKey(Configuration.getGlobalConfiguration().get("OPENAI_KEY")) - .setDeploymentName(deploymentId) - .setModelName(AzureOpenAIModelName.TEXT_EMBEDDING_3_LARGE))))); - } - - public static void createVectorIndex(SearchIndex vectorIndex) { - // Instantiate the 'SearchIndexClient' and call the 'createIndex' method to create the search index. - String endpoint = Configuration.getGlobalConfiguration().get("SEARCH_ENDPOINT"); - String key = Configuration.getGlobalConfiguration().get("SEARCH_API_KEY"); - AzureKeyCredential credential = new AzureKeyCredential(key); - - SearchIndexClient indexClient = new SearchIndexClientBuilder().endpoint(endpoint) - .credential(credential) - .buildClient(); - - indexClient.createIndex(vectorIndex); - } - - // Simple model type for Hotel - - /** - * Hotel model with an additional field for the vector description. - */ - public static final class VectorHotel implements JsonSerializable { - @SimpleField(isKey = true) - private String hotelId; - @SearchableField(isFilterable = true, isSortable = true, analyzerName = "en.lucene") - private String hotelName; - @SearchableField(analyzerName = "en.lucene") - private String description; - @SearchableField(vectorSearchDimensions = 256, vectorSearchProfileName = "my-vector-profile") - private List descriptionVector; - @SearchableField(isFilterable = true, isFacetable = true, isSortable = true) - private String category; - @SearchableField(vectorSearchDimensions = 256, vectorSearchProfileName = "my-vector-profile") - private List categoryVector; - - public VectorHotel() { - } - - public String getHotelId() { - return hotelId; - } - - public VectorHotel setHotelId(String hotelId) { - this.hotelId = hotelId; - return this; - } - - public String getHotelName() { - return hotelName; - } - - public VectorHotel setHotelName(String hotelName) { - this.hotelName = hotelName; - return this; - } - - public String getDescription() { - return description; - } - - public VectorHotel setDescription(String description) { - this.description = description; - return this; - } - - public List getDescriptionVector() { - return descriptionVector == null ? null : Collections.unmodifiableList(descriptionVector); - } - - public VectorHotel setDescriptionVector(List descriptionVector) { - this.descriptionVector = descriptionVector == null ? null : new ArrayList<>(descriptionVector); - return this; - } - - public String getCategory() { - return category; - } - - public VectorHotel setCategory(String category) { - this.category = category; - return this; - } - - public List getCategoryVector() { - return categoryVector == null ? null : Collections.unmodifiableList(categoryVector); - } - - public VectorHotel setCategoryVector(List categoryVector) { - this.categoryVector = categoryVector == null ? null : new ArrayList<>(categoryVector); - return this; - } - - @Override - public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { - return jsonWriter.writeStartObject() - .writeStringField("HotelId", hotelId) - .writeStringField("HotelName", hotelName) - .writeStringField("Description", description) - .writeArrayField("DescriptionVector", descriptionVector, JsonWriter::writeFloat) - .writeStringField("Category", category) - .writeArrayField("DescriptionVector", categoryVector, JsonWriter::writeFloat) - .writeEndObject(); - } - - public static VectorHotel fromJson(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - VectorHotel vectorHotel = new VectorHotel(); - - while (reader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = reader.getFieldName(); - reader.nextToken(); - - if ("HotelId".equals(fieldName)) { - vectorHotel.hotelId = reader.getString(); - } else if ("HotelName".equals(fieldName)) { - vectorHotel.hotelName = reader.getString(); - } else if ("Description".equals(fieldName)) { - vectorHotel.description = reader.getString(); - } else if ("DescriptionVector".equals(fieldName)) { - vectorHotel.descriptionVector = reader.readArray(JsonReader::getFloat); - } else if ("Category".equals(fieldName)) { - vectorHotel.category = reader.getString(); - } else if ("CategoryVector".equals(fieldName)) { - vectorHotel.categoryVector = reader.readArray(JsonReader::getFloat); - } else { - reader.skipChildren(); - } - } - - return vectorHotel; - }); - } - } - - /** - * Get Embeddings using {@code azure-ai-openai} library. - *

- * You can use Azure OpenAI embedding models, {@code text-embedding-3-small} or {@code text-embedding-3-large}, to - * get the reduced embeddings. With these models, you can specify the desired number of dimensions for the output - * vector by passing the 'Dimensions' property. This enables you to customize the output according to your needs. - *

- * For more details about how to generate embeddings, refer to the - * documentation. - * Here's an example of how you can get embeddings using - * azure-ai-openai - * library. - */ - public static List getEmbeddings(String input) { - // Get embeddings using Azure OpenAI - String endpoint = Configuration.getGlobalConfiguration().get("OPENAI_ENDPOINT"); - String key = Configuration.getGlobalConfiguration().get("OPENAI_API_KEY"); - KeyCredential credential = new KeyCredential(key); - - OpenAIClient openAIClient = new OpenAIClientBuilder().endpoint(endpoint).credential(credential).buildClient(); - EmbeddingsOptions embeddingsOptions = new EmbeddingsOptions(Collections.singletonList(input)).setModel( - "my-text-embedding-3-small").setDimensions(256); - - Embeddings embeddings = openAIClient.getEmbeddings("my-text-embedding-3-small", embeddingsOptions); - return embeddings.getData().get(0).getEmbedding(); - } - - public static List getHotelDocuments() { - // In the sample code below, we are using 'getEmbeddings' method mentioned above to get embeddings for the - // vector fields named 'DescriptionVector' and 'CategoryVector'. - return Arrays.asList(new VectorHotel().setHotelId("1") - .setHotelName("Fancy Stay") - .setDescription("Best hotel in town if you like luxury hotels. They have an amazing infinity pool, a " - + "spa, and a really helpful concierge. The location is perfect -- right downtown, close to " - + "all the tourist attractions. We highly recommend this hotel.") - .setDescriptionVector(getEmbeddings( - "Best hotel in town if you like luxury hotels. They have an amazing infinity pool, a spa, " - + "and a really helpful concierge. The location is perfect -- right downtown, close to all " - + "the tourist attractions. We highly recommend this hotel.")) - .setCategory("Luxury") - .setCategoryVector(getEmbeddings("Luxury")), new VectorHotel().setHotelId("2") - .setHotelName("Roach Motel") - .setDescription("Cheapest hotel in town. Infact, a motel.") - .setDescriptionVector(getEmbeddings("Cheapest hotel in town. Infact, a motel.")) - .setCategory("Budget") - .setCategoryVector(getEmbeddings("Budget")) - // Add more hotel documents here... - ); - } - - public static void indexDocuments(SearchClient searchClient, List hotelDocuments) { - searchClient.indexDocuments(new IndexDocumentsBatch().addUploadActions(hotelDocuments)); - } - - /** - * In this vector query, the 'VectorQueries' contains the vectorizable text of the query input. The 'Fields' - * property specifies which vector fields are searched. The 'KNearestNeighborsCount' property specifies the number - * of nearest neighbors to return as top hits. - */ - public static void vectorSearch(SearchClient searchClient) { - SearchPagedIterable response = searchClient.search(null, new SearchOptions().setVectorSearchOptions( - new VectorSearchOptions().setQueries( - new VectorizableTextQuery("Luxury hotels in town").setKNearestNeighborsCount(3) - .setFields("DescriptionVector"))), Context.NONE); - - int count = 0; - System.out.println("Vector Search Results:"); - - for (SearchResult result : response) { - count++; - VectorHotel doc = result.getDocument(VectorHotel.class); - System.out.println(doc.getHotelId() + ": " + doc.getHotelName()); - } - - System.out.println("Total number of search results: " + count); - } -} diff --git a/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/codesnippets/SearchAsyncClientJavaDocSnippets.java b/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/codesnippets/SearchAsyncClientJavaDocSnippets.java deleted file mode 100644 index 43f73403d16c..000000000000 --- a/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/codesnippets/SearchAsyncClientJavaDocSnippets.java +++ /dev/null @@ -1,138 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -package com.azure.search.documents.codesnippets; - -import com.azure.core.credential.AzureKeyCredential; -import com.azure.search.documents.SearchAsyncClient; -import com.azure.search.documents.SearchClientBuilder; -import com.azure.search.documents.SearchDocument; -import com.azure.search.documents.models.Hotel; -import com.azure.search.documents.util.AutocompletePagedFlux; -import com.azure.search.documents.util.SearchPagedFlux; -import com.azure.search.documents.util.SuggestPagedFlux; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; - -@SuppressWarnings("unused") -public class SearchAsyncClientJavaDocSnippets { - - private static SearchAsyncClient searchAsyncClient; - - private static SearchAsyncClient createSearchAsyncClientWithSearchClientBuilder() { - // BEGIN: com.azure.search.documents.SearchAsyncClient-classLevelJavaDoc.instantiationWithSearchClientBuilder - SearchAsyncClient searchAsyncClient = new SearchClientBuilder() - .credential(new AzureKeyCredential("{key}")) - .endpoint("{endpoint}") - .indexName("{indexName}") - .buildAsyncClient(); - // END: com.azure.search.documents.SearchAsyncClient-classLevelJavaDoc.instantiationWithSearchClientBuilder - return searchAsyncClient; - } - - /** - * Uploading a document to a SearchAsyncClient index. - */ - public static void uploadDocument() { - searchAsyncClient = createSearchAsyncClientWithSearchClientBuilder(); - // BEGIN: com.azure.search.documents.SearchAsyncClient-classLevelJavaDoc.uploadDocument#Map-boolean - List hotels = new ArrayList<>(); - hotels.add(new Hotel().setHotelId("100")); - hotels.add(new Hotel().setHotelId("200")); - hotels.add(new Hotel().setHotelId("300")); - searchAsyncClient.uploadDocuments(hotels).block(); - // END: com.azure.search.documents.SearchAsyncClient-classLevelJavaDoc.uploadDocument#Map-boolean - } - - /** - * Merge a document in a SearchAsyncClient index. - */ - public static void mergeDocument() { - searchAsyncClient = createSearchAsyncClientWithSearchClientBuilder(); - // BEGIN: com.azure.search.documents.SearchAsyncClient-classLevelJavaDoc.mergeDocument#Map - List hotels = new ArrayList<>(); - hotels.add(new Hotel().setHotelId("100")); - hotels.add(new Hotel().setHotelId("200")); - searchAsyncClient.mergeDocuments(hotels).block(); - // END: com.azure.search.documents.SearchAsyncClient-classLevelJavaDoc.mergeDocument#Map - } - - /** - * Delete a document in a SearchAsyncClient index. - */ - public static void deleteDocument() { - searchAsyncClient = createSearchAsyncClientWithSearchClientBuilder(); - // BEGIN: com.azure.search.documents.SearchAsyncClient-classLevelJavaDoc.deleteDocument#String - SearchDocument documentId = new SearchDocument(); - documentId.put("hotelId", "100"); - searchAsyncClient.deleteDocuments(Collections.singletonList(documentId)); - // END: com.azure.search.documents.SearchAsyncClient-classLevelJavaDoc.deleteDocument#String - } - - /** - * Retrieve a document from a SearchAsyncClient index. - */ - public static void getDocument() { - searchAsyncClient = createSearchAsyncClientWithSearchClientBuilder(); - // BEGIN: com.azure.search.documents.SearchAsyncClient-classLevelJavaDoc.getDocument#String-Class - Hotel hotel = searchAsyncClient.getDocument("100", Hotel.class).block(); - if (hotel != null) { - System.out.printf("Retrieved Hotel %s%n", hotel.getHotelId()); - } - // END: com.azure.search.documents.SearchAsyncClient-classLevelJavaDoc.getDocument#String-Class - } - - /** - * Search documents in a SearchAsyncClient index. - */ - public static void searchDocuments() { - searchAsyncClient = createSearchAsyncClientWithSearchClientBuilder(); - // BEGIN: com.azure.search.documents.SearchAsyncClient-classLevelJavaDoc.searchDocuments#String - SearchDocument searchDocument = new SearchDocument(); - searchDocument.put("hotelId", "8"); - searchDocument.put("description", "budget"); - searchDocument.put("descriptionFr", "motel"); - - SearchDocument searchDocument1 = new SearchDocument(); - searchDocument1.put("hotelId", "9"); - searchDocument1.put("description", "budget"); - searchDocument1.put("descriptionFr", "motel"); - - List searchDocuments = new ArrayList<>(); - searchDocuments.add(searchDocument); - searchDocuments.add(searchDocument1); - searchAsyncClient.uploadDocuments(searchDocuments); - - SearchPagedFlux results = searchAsyncClient.search("SearchText"); - results.getTotalCount().subscribe(total -> System.out.printf("There are %s results", total)); - // END: com.azure.search.documents.SearchAsyncClient-classLevelJavaDoc.searchDocuments#String - } - - /** - * Make a suggestion query to a SearchAsyncClient index. - */ - public static void suggestDocuments() { - searchAsyncClient = createSearchAsyncClientWithSearchClientBuilder(); - // BEGIN: com.azure.search.documents.SearchAsyncClient-classLevelJavaDoc.suggestDocuments#String-String - SuggestPagedFlux results = searchAsyncClient.suggest("searchText", "sg"); - results.subscribe(item -> { - System.out.printf("The text '%s' was found.%n", item.getText()); - }); - // END: com.azure.search.documents.SearchAsyncClient-classLevelJavaDoc.suggestDocuments#String-String - } - - /** - * Autocomplete a query in a SearchAsyncClient index. - */ - public static void autocompleteDocuments() { - searchAsyncClient = createSearchAsyncClientWithSearchClientBuilder(); - // BEGIN: com.azure.search.documents.SearchAsyncClient-classLevelJavaDoc.autocomplete#String-String - AutocompletePagedFlux results = searchAsyncClient.autocomplete("searchText", "sg"); - results.subscribe(item -> { - System.out.printf("The text '%s' was found.%n", item.getText()); - }); - // END: com.azure.search.documents.SearchAsyncClient-classLevelJavaDoc.autocomplete#String-String - } - -} diff --git a/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/codesnippets/SearchClientBuilderJavaDocSnippets.java b/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/codesnippets/SearchClientBuilderJavaDocSnippets.java deleted file mode 100644 index 75058fce732e..000000000000 --- a/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/codesnippets/SearchClientBuilderJavaDocSnippets.java +++ /dev/null @@ -1,78 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -package com.azure.search.documents.codesnippets; - -import com.azure.core.credential.AzureKeyCredential; -// BEGIN: DefaultAzureCredentialImports -import com.azure.identity.DefaultAzureCredential; -import com.azure.identity.DefaultAzureCredentialBuilder; -// END: DefaultAzureCredentialImports -import com.azure.search.documents.SearchAsyncClient; -import com.azure.search.documents.SearchClient; -import com.azure.search.documents.SearchClientBuilder; - -@SuppressWarnings("unused") -public class SearchClientBuilderJavaDocSnippets { - - /** - * Code snippet for creating {@link SearchClient} using a {@link SearchClientBuilder}. - */ - public SearchClient createSearchClientFromBuilder() { - // BEGIN: com.azure.search.documents.SearchClientBuilder-classLevelJavaDoc.instantiation.SearchClient - SearchClient searchClient = new SearchClientBuilder() - .credential(new AzureKeyCredential("{key}")) - .endpoint("{endpoint}") - .indexName("{indexName}") - .buildClient(); - // END: com.azure.search.documents.SearchClientBuilder-classLevelJavaDoc.instantiation.SearchClient - return searchClient; - } - - /** - * Code snippet for creating a {@link SearchAsyncClient}. - */ - public SearchAsyncClient createSearchAsyncClientFromBuilder() { - // BEGIN: com.azure.search.documents.SearchClientBuilder-classLevelJavaDoc.instantiation.SearchAsyncClient - SearchAsyncClient searchAsyncClient = new SearchClientBuilder() - .credential(new AzureKeyCredential("{key}")) - .endpoint("{endpoint}") - .indexName("{indexName}") - .buildAsyncClient(); - // END: com.azure.search.documents.SearchClientBuilder-classLevelJavaDoc.instantiation.SearchAsyncClient - return searchAsyncClient; - } - - /** - * Instantiate a synchronous client using DefaultAzureCredential. - */ - public SearchClient createSearchClientWithDefaultAzureCredential() { - // BEGIN: com.azure.search.documents.SearchClientBuilder-classLevelJavaDoc.credential - DefaultAzureCredential credential = new DefaultAzureCredentialBuilder().build(); - - SearchClient searchClient = new SearchClientBuilder() - .credential(credential) - .endpoint("{endpoint}") - .indexName("{indexName}") - .buildClient(); - // END: com.azure.search.documents.SearchClientBuilder-classLevelJavaDoc.credential - return searchClient; - } - - /** - * Instantiate an asynchronous client using DefaultAzureCredential. - */ - public SearchAsyncClient createSearchAsyncClientWithDefaultAzureCredential() { - // BEGIN: com.azure.search.documents.SearchClientBuilder-classLevelJavaDoc.async.credential - DefaultAzureCredential credential = new DefaultAzureCredentialBuilder().build(); - - SearchAsyncClient searchAsyncClient = new SearchClientBuilder() - .credential(credential) - .endpoint("{endpoint}") - .indexName("{indexName}") - .buildAsyncClient(); - // END: com.azure.search.documents.SearchClientBuilder-classLevelJavaDoc.async.credential - return searchAsyncClient; - } - - -} diff --git a/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/codesnippets/SearchClientJavaDocSnippets.java b/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/codesnippets/SearchClientJavaDocSnippets.java deleted file mode 100644 index 00a3b5a83e6c..000000000000 --- a/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/codesnippets/SearchClientJavaDocSnippets.java +++ /dev/null @@ -1,137 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -package com.azure.search.documents.codesnippets; - -import com.azure.core.credential.AzureKeyCredential; -import com.azure.search.documents.SearchClient; -import com.azure.search.documents.SearchClientBuilder; -import com.azure.search.documents.SearchDocument; -import com.azure.search.documents.models.AutocompleteItem; -import com.azure.search.documents.models.Hotel; -import com.azure.search.documents.models.SuggestResult; -import com.azure.search.documents.util.AutocompletePagedIterable; -import com.azure.search.documents.util.SearchPagedIterable; -import com.azure.search.documents.util.SuggestPagedIterable; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -@SuppressWarnings("unused") -public class SearchClientJavaDocSnippets { - - private static SearchClient searchClient; - - private static SearchClient createSearchClientWithSearchClientBuilder() { - // BEGIN: com.azure.search.documents.SearchClient-classLevelJavaDoc.instantiationWithSearchClientBuilder - SearchClient searchClient = new SearchClientBuilder() - .credential(new AzureKeyCredential("{key}")) - .endpoint("{endpoint}") - .indexName("{indexName}") - .buildClient(); - // END: com.azure.search.documents.SearchClient-classLevelJavaDoc.instantiationWithSearchClientBuilder - return searchClient; - } - - /** - * Uploading a document to a SearchClient index. - */ - public static void uploadDocument() { - searchClient = createSearchClientWithSearchClientBuilder(); - // BEGIN: com.azure.search.documents.SearchClient-classLevelJavaDoc.uploadDocument#Map-boolean - List hotels = new ArrayList<>(); - hotels.add(new Hotel().setHotelId("100")); - hotels.add(new Hotel().setHotelId("200")); - hotels.add(new Hotel().setHotelId("300")); - searchClient.uploadDocuments(hotels); - // END: com.azure.search.documents.SearchClient-classLevelJavaDoc.uploadDocument#Map-boolean - } - - /** - * Merge a document in a SearchClient index. - */ - public static void mergeDocument() { - searchClient = createSearchClientWithSearchClientBuilder(); - // BEGIN: com.azure.search.documents.SearchClient-classLevelJavaDoc.mergeDocument#Map - List hotels = new ArrayList<>(); - hotels.add(new Hotel().setHotelId("100")); - hotels.add(new Hotel().setHotelId("200")); - searchClient.mergeDocuments(hotels); - // END: com.azure.search.documents.SearchClient-classLevelJavaDoc.mergeDocument#Map - } - - /** - * Delete a document in a SearchClient index. - */ - public static void deleteDocument() { - searchClient = createSearchClientWithSearchClientBuilder(); - // BEGIN: com.azure.search.documents.SearchClient-classLevelJavaDoc.deleteDocument#String - SearchDocument documentId = new SearchDocument(); - documentId.put("hotelId", "100"); - searchClient.deleteDocuments(Collections.singletonList(documentId)); - // END: com.azure.search.documents.SearchClient-classLevelJavaDoc.deleteDocument#String - } - - /** - * Retrieve a document from a SearchClient index. - */ - public static void getDocument() { - searchClient = createSearchClientWithSearchClientBuilder(); - // BEGIN: com.azure.search.documents.SearchClient-classLevelJavaDoc.getDocument#String-Class - Hotel hotel = searchClient.getDocument("100", Hotel.class); - System.out.printf("Retrieved Hotel %s%n", hotel.getHotelId()); - // END: com.azure.search.documents.SearchClient-classLevelJavaDoc.getDocument#String-Class - } - - /** - * Search documents in a SearchClient index. - */ - public static void searchDocuments() { - searchClient = createSearchClientWithSearchClientBuilder(); - // BEGIN: com.azure.search.documents.SearchClient-classLevelJavaDoc.searchDocuments#String - SearchDocument searchDocument = new SearchDocument(); - searchDocument.put("hotelId", "8"); - searchDocument.put("description", "budget"); - searchDocument.put("descriptionFr", "motel"); - - SearchDocument searchDocument1 = new SearchDocument(); - searchDocument1.put("hotelId", "9"); - searchDocument1.put("description", "budget"); - searchDocument1.put("descriptionFr", "motel"); - - List searchDocuments = new ArrayList<>(); - searchDocuments.add(searchDocument); - searchDocuments.add(searchDocument1); - searchClient.uploadDocuments(searchDocuments); - - SearchPagedIterable results = searchClient.search("SearchText"); - System.out.printf("There are %s results.%n", results.getTotalCount()); - // END: com.azure.search.documents.SearchClient-classLevelJavaDoc.searchDocuments#String - } - - /** - * Make a suggestion query to a SearchClient index. - */ - public static void suggestDocuments() { - searchClient = createSearchClientWithSearchClientBuilder(); - // BEGIN: com.azure.search.documents.SearchClient-classLevelJavaDoc.suggestDocuments#String-String - SuggestPagedIterable suggestPagedIterable = searchClient.suggest("searchText", "sg"); - for (SuggestResult result: suggestPagedIterable) { - System.out.printf("The suggested text is %s", result.getText()); - } - // END: com.azure.search.documents.SearchClient-classLevelJavaDoc.suggestDocuments#String-String - } - - /** - * Autocomplete a query in a SearchClient index. - */ - public static void autocompleteDocuments() { - searchClient = createSearchClientWithSearchClientBuilder(); - // BEGIN: com.azure.search.documents.SearchClient-classLevelJavaDoc.autocomplete#String-String - AutocompletePagedIterable autocompletePagedIterable = searchClient.autocomplete("searchText", "sg"); - for (AutocompleteItem result: autocompletePagedIterable) { - System.out.printf("The complete term is %s", result.getText()); - } - // END: com.azure.search.documents.SearchClient-classLevelJavaDoc.autocomplete#String-String - } -} - diff --git a/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/codesnippets/SearchIndexAsyncClientJavaDocSnippets.java b/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/codesnippets/SearchIndexAsyncClientJavaDocSnippets.java deleted file mode 100644 index 9fd2afd7f9ee..000000000000 --- a/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/codesnippets/SearchIndexAsyncClientJavaDocSnippets.java +++ /dev/null @@ -1,197 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -package com.azure.search.documents.codesnippets; - -import com.azure.core.credential.AzureKeyCredential; -import com.azure.search.documents.indexes.SearchIndexAsyncClient; -import com.azure.search.documents.indexes.SearchIndexClientBuilder; -import com.azure.search.documents.indexes.models.LexicalAnalyzerName; -import com.azure.search.documents.indexes.models.SearchField; -import com.azure.search.documents.indexes.models.SearchFieldDataType; -import com.azure.search.documents.indexes.models.SearchIndex; -import com.azure.search.documents.indexes.models.SynonymMap; - -import java.util.Arrays; -@SuppressWarnings("unused") -public class SearchIndexAsyncClientJavaDocSnippets { - - private static SearchIndexAsyncClient searchIndexAsyncClient; - - /** - * Code snippet for creating a {@link com.azure.search.documents.indexes.SearchIndexAsyncClient} - */ - private static SearchIndexAsyncClient createSearchIndexAsyncClient() { - // BEGIN: com.azure.search.documents.indexes.SearchIndexAsyncClient-classLevelJavaDoc.instantiation - SearchIndexAsyncClient searchIndexAsyncClient = new SearchIndexClientBuilder() - .credential(new AzureKeyCredential("{key}")) - .endpoint("{endpoint}") - .buildAsyncClient(); - // END: com.azure.search.documents.indexes.SearchIndexAsyncClient-classLevelJavaDoc.instantiation - return searchIndexAsyncClient; - } - - /** - * Code snippet for creating an index. - */ - public static void createIndex() { - searchIndexAsyncClient = createSearchIndexAsyncClient(); - // BEGIN: com.azure.search.documents.indexes.SearchIndexAsyncClient-classLevelJavaDoc.createIndex#SearchIndex - SearchIndex searchIndex = new SearchIndex("indexName", Arrays.asList( - new SearchField("hotelId", SearchFieldDataType.STRING) - .setKey(true) - .setFilterable(true) - .setSortable(true), - new SearchField("hotelName", SearchFieldDataType.STRING) - .setSearchable(true) - .setFilterable(true) - .setSortable(true), - new SearchField("description", SearchFieldDataType.STRING) - .setSearchable(true) - .setAnalyzerName(LexicalAnalyzerName.EN_LUCENE), - new SearchField("descriptionFr", SearchFieldDataType.STRING) - .setSearchable(true) - .setAnalyzerName(LexicalAnalyzerName.FR_LUCENE), - new SearchField("tags", SearchFieldDataType.collection(SearchFieldDataType.STRING)) - .setSearchable(true) - .setFilterable(true) - .setFacetable(true), - new SearchField("address", SearchFieldDataType.COMPLEX) - .setFields( - new SearchField("streetAddress", SearchFieldDataType.STRING) - .setSearchable(true), - new SearchField("city", SearchFieldDataType.STRING) - .setFilterable(true) - .setSortable(true) - .setFacetable(true), - new SearchField("stateProvince", SearchFieldDataType.STRING) - .setSearchable(true) - .setFilterable(true) - .setSortable(true) - .setFacetable(true), - new SearchField("country", SearchFieldDataType.STRING) - .setSearchable(true) - .setSynonymMapNames("synonymMapName") - .setFilterable(true) - .setSortable(true) - .setFacetable(true), - new SearchField("postalCode", SearchFieldDataType.STRING) - .setSearchable(true) - .setFilterable(true) - .setSortable(true) - .setFacetable(true)) - )); - - searchIndexAsyncClient.createIndex(searchIndex).block(); - // END: com.azure.search.documents.indexes.SearchIndexAsyncClient-classLevelJavaDoc.createIndex#SearchIndex - } - - /** - * Code Snippet for listing all indexes - */ - public static void listIndexes() { - searchIndexAsyncClient = createSearchIndexAsyncClient(); - // BEGIN: com.azure.search.documents.indexes.SearchIndexAsyncClient-classLevelJavaDoc.listIndexes - searchIndexAsyncClient.listIndexes().subscribe(index -> System.out.println("The index name is " + index.getName())); - // END: com.azure.search.documents.indexes.SearchIndexAsyncClient-classLevelJavaDoc.listIndexes - } - - /** - * Code snippet for retrieving an index - */ - public static void getIndex() { - searchIndexAsyncClient = createSearchIndexAsyncClient(); - // BEGIN: com.azure.search.documents.indexes.SearchIndexAsyncClient-classLevelJavaDoc.getIndex#String - SearchIndex searchIndex = searchIndexAsyncClient.getIndex("indexName").block(); - if (searchIndex != null) { - System.out.println("The index name is " + searchIndex.getName()); - } - // END: com.azure.search.documents.indexes.SearchIndexAsyncClient-classLevelJavaDoc.getIndex#String - } - - /** - * Code snippet for updating an index - */ - public static void updateIndex() { - searchIndexAsyncClient = createSearchIndexAsyncClient(); - // BEGIN: com.azure.search.documents.indexes.SearchIndexAsyncClient-classLevelJavaDoc.updateIndex#SearchIndex - SearchIndex searchIndex = searchIndexAsyncClient.getIndex("indexName").block(); - if (searchIndex != null) { - searchIndex.setFields(new SearchField("newField", SearchFieldDataType.STRING)); - searchIndexAsyncClient.createOrUpdateIndex(searchIndex); - } - // END: com.azure.search.documents.indexes.SearchIndexAsyncClient-classLevelJavaDoc.updateIndex#SearchIndex - } - - /** - * Code snippet for deleting an index - */ - public static void deleteIndex() { - searchIndexAsyncClient = createSearchIndexAsyncClient(); - // BEGIN: com.azure.search.documents.indexes.SearchIndexAsyncClient-classLevelJavaDoc.deleteIndex#String - String indexName = "indexName"; - searchIndexAsyncClient.deleteIndex(indexName).block(); - // END: com.azure.search.documents.indexes.SearchIndexAsyncClient-classLevelJavaDoc.deleteIndex#String - } - - /** - * Code snippet for creating a synonym map - */ - public static void createSynonymMap() { - searchIndexAsyncClient = createSearchIndexAsyncClient(); - // BEGIN: com.azure.search.documents.indexes.SearchIndexAsyncClient-classLevelJavaDoc.createSynonymMap#SynonymMap - SynonymMap synonymMap = new SynonymMap("synonymMapName", "hotel, motel, \"motor inn\""); - searchIndexAsyncClient.createSynonymMap(synonymMap).block(); - // END: com.azure.search.documents.indexes.SearchIndexAsyncClient-classLevelJavaDoc.createSynonymMap#SynonymMap - } - - /** - * Code snippet for listing all synonym maps - */ - public static void listSynonymMaps() { - searchIndexAsyncClient = createSearchIndexAsyncClient(); - // BEGIN: com.azure.search.documents.indexes.SearchIndexAsyncClient-classLevelJavaDoc.listSynonymMaps - searchIndexAsyncClient.listSynonymMaps().subscribe(synonymMap -> - System.out.println("The synonymMap name is " + synonymMap.getName()) - ); - // END: com.azure.search.documents.indexes.SearchIndexAsyncClient-classLevelJavaDoc.listSynonymMaps - } - - /** - * Code snippet for retrieving a synonym map - */ - public static void getSynonymMap() { - searchIndexAsyncClient = createSearchIndexAsyncClient(); - // BEGIN: com.azure.search.documents.indexes.SearchIndexAsyncClient-classLevelJavaDoc.getSynonymMap#String - SynonymMap synonymMap = searchIndexAsyncClient.getSynonymMap("synonymMapName").block(); - if (synonymMap != null) { - System.out.println("The synonymMap name is " + synonymMap.getName()); - } - // END: com.azure.search.documents.indexes.SearchIndexAsyncClient-classLevelJavaDoc.getSynonymMap#String - } - - /** - * Code snippet for updating a synonym map - */ - public static void updateSynonymMap() { - searchIndexAsyncClient = createSearchIndexAsyncClient(); - // BEGIN: com.azure.search.documents.indexes.SearchIndexAsyncClient-classLevelJavaDoc.updateSynonymMap#SynonymMap - SynonymMap synonymMap = searchIndexAsyncClient.getSynonymMap("synonymMapName").block(); - if (synonymMap != null) { - synonymMap.setSynonyms("hotel, motel, inn"); - searchIndexAsyncClient.createOrUpdateSynonymMap(synonymMap).block(); - } - // END: com.azure.search.documents.indexes.SearchIndexAsyncClient-classLevelJavaDoc.updateSynonymMap#SynonymMap - } - - /** - * Code snippet for deleting a synonym map - */ - public static void deleteSynonymMap() { - searchIndexAsyncClient = createSearchIndexAsyncClient(); - // BEGIN: com.azure.search.documents.indexes.SearchIndexAsyncClient-classLevelJavaDoc.deleteSynonymMap#String - String synonymMapName = "synonymMapName"; - searchIndexAsyncClient.deleteSynonymMap(synonymMapName).block(); - // END: com.azure.search.documents.indexes.SearchIndexAsyncClient-classLevelJavaDoc.deleteSynonymMap#String - } - -} diff --git a/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/codesnippets/SearchIndexClientBuilderJavaDocSnippets.java b/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/codesnippets/SearchIndexClientBuilderJavaDocSnippets.java deleted file mode 100644 index c35485e9b81a..000000000000 --- a/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/codesnippets/SearchIndexClientBuilderJavaDocSnippets.java +++ /dev/null @@ -1,70 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -package com.azure.search.documents.codesnippets; - -import com.azure.core.credential.AzureKeyCredential; -import com.azure.identity.DefaultAzureCredential; -import com.azure.identity.DefaultAzureCredentialBuilder; -import com.azure.search.documents.indexes.SearchIndexAsyncClient; -import com.azure.search.documents.indexes.SearchIndexClient; -import com.azure.search.documents.indexes.SearchIndexClientBuilder; -@SuppressWarnings("unused") -public class SearchIndexClientBuilderJavaDocSnippets { - - /** - * Create SearchIndexClient from SearchIndexClientBuilder. - */ - public static SearchIndexClient createSearchIndexClientFromBuilder() { - // BEGIN: com.azure.search.documents.SearchIndexClientBuilder.instantiation.SearchIndexClient - SearchIndexClient searchIndexClient = new SearchIndexClientBuilder() - .credential(new AzureKeyCredential("{key}")) - .endpoint("{endpoint}") - .buildClient(); - // END: com.azure.search.documents.SearchIndexClientBuilder.instantiation.SearchIndexClient - return searchIndexClient; - } - - - /** - * Create SearchIndexAsyncClient from SearchIndexClientBuilder. - */ - public static SearchIndexAsyncClient createSearchIndexAsyncClientFromBuilder() { - // BEGIN: com.azure.search.documents.SearchIndexClientBuilder.instantiation.SearchIndexAsyncClient - SearchIndexAsyncClient searchIndexAsyncClient = new SearchIndexClientBuilder() - .credential(new AzureKeyCredential("{key}")) - .endpoint("{endpoint}") - .buildAsyncClient(); - // END: com.azure.search.documents.SearchIndexClientBuilder.instantiation.SearchIndexAsyncClient - return searchIndexAsyncClient; - } - - /** - * Instantiate a synchronous client using DefaultAzureCredential. - */ - public static SearchIndexClient createSearchIndexClientWithDefaultAzureCredential() { - // BEGIN: com.azure.search.documents.SearchIndexClientBuilder.credential - DefaultAzureCredential credential = new DefaultAzureCredentialBuilder().build(); - - SearchIndexClient searchIndexClient = new SearchIndexClientBuilder() - .credential(credential) - .endpoint("{endpoint}") - .buildClient(); - // END: com.azure.search.documents.SearchIndexClientBuilder.credential - return searchIndexClient; - } - - /** - * Instantiate an asynchronous client using DefaultAzureCredential. - */ - public static SearchIndexAsyncClient createSearchIndexAsyncClientWithDefaultAzureCredential() { - // BEGIN: com.azure.search.documents.SearchIndexClientBuilder.async.credential - DefaultAzureCredential credential = new DefaultAzureCredentialBuilder().build(); - - SearchIndexAsyncClient searchIndexAsyncClient = new SearchIndexClientBuilder() - .credential(credential) - .endpoint("{endpoint}") - .buildAsyncClient(); - // END: com.azure.search.documents.SearchIndexClientBuilder.async.credential - return searchIndexAsyncClient; - } -} diff --git a/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/codesnippets/SearchIndexClientJavaDocSnippets.java b/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/codesnippets/SearchIndexClientJavaDocSnippets.java deleted file mode 100644 index c43f6ae6335d..000000000000 --- a/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/codesnippets/SearchIndexClientJavaDocSnippets.java +++ /dev/null @@ -1,194 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -package com.azure.search.documents.codesnippets; - -import com.azure.core.credential.AzureKeyCredential; -import com.azure.search.documents.indexes.SearchIndexClient; -import com.azure.search.documents.indexes.SearchIndexClientBuilder; -import com.azure.search.documents.indexes.models.LexicalAnalyzerName; -import com.azure.search.documents.indexes.models.SearchField; -import com.azure.search.documents.indexes.models.SearchFieldDataType; -import com.azure.search.documents.indexes.models.SearchIndex; -import com.azure.search.documents.indexes.models.SynonymMap; - -import java.util.Arrays; -@SuppressWarnings("unused") -public class SearchIndexClientJavaDocSnippets { - - private static SearchIndexClient searchIndexClient; - - /** - * Code snippet for creating a {@link com.azure.search.documents.indexes.SearchIndexClient} - */ - private static SearchIndexClient createSearchIndexClient() { - // BEGIN: com.azure.search.documents.indexes.SearchIndexClient-classLevelJavaDoc.instantiation - SearchIndexClient searchIndexClient = new SearchIndexClientBuilder() - .credential(new AzureKeyCredential("{key}")) - .endpoint("{endpoint}") - .buildClient(); - // END: com.azure.search.documents.indexes.SearchIndexClient-classLevelJavaDoc.instantiation - return searchIndexClient; - } - - /** - * Code snippet for creating an index. - */ - public static void createIndex() { - searchIndexClient = createSearchIndexClient(); - // BEGIN: com.azure.search.documents.indexes.SearchIndexClient-classLevelJavaDoc.createIndex#SearchIndex - SearchIndex searchIndex = new SearchIndex("indexName", Arrays.asList( - new SearchField("hotelId", SearchFieldDataType.STRING) - .setKey(true) - .setFilterable(true) - .setSortable(true), - new SearchField("hotelName", SearchFieldDataType.STRING) - .setSearchable(true) - .setFilterable(true) - .setSortable(true), - new SearchField("description", SearchFieldDataType.STRING) - .setSearchable(true) - .setAnalyzerName(LexicalAnalyzerName.EN_LUCENE), - new SearchField("descriptionFr", SearchFieldDataType.STRING) - .setSearchable(true) - .setAnalyzerName(LexicalAnalyzerName.FR_LUCENE), - new SearchField("tags", SearchFieldDataType.collection(SearchFieldDataType.STRING)) - .setSearchable(true) - .setFilterable(true) - .setFacetable(true), - new SearchField("address", SearchFieldDataType.COMPLEX) - .setFields( - new SearchField("streetAddress", SearchFieldDataType.STRING) - .setSearchable(true), - new SearchField("city", SearchFieldDataType.STRING) - .setFilterable(true) - .setSortable(true) - .setFacetable(true), - new SearchField("stateProvince", SearchFieldDataType.STRING) - .setSearchable(true) - .setFilterable(true) - .setSortable(true) - .setFacetable(true), - new SearchField("country", SearchFieldDataType.STRING) - .setSearchable(true) - .setSynonymMapNames("synonymMapName") - .setFilterable(true) - .setSortable(true) - .setFacetable(true), - new SearchField("postalCode", SearchFieldDataType.STRING) - .setSearchable(true) - .setFilterable(true) - .setSortable(true) - .setFacetable(true)) - )); - - searchIndexClient.createIndex(searchIndex); - // END: com.azure.search.documents.indexes.SearchIndexClient-classLevelJavaDoc.createIndex#SearchIndex - } - - /** - * Code Snippet for listing all indexes - */ - public static void listIndexes() { - searchIndexClient = createSearchIndexClient(); - // BEGIN: com.azure.search.documents.indexes.SearchIndexClient-classLevelJavaDoc.listIndexes - searchIndexClient.listIndexes().forEach(index -> System.out.println(index.getName())); - // END: com.azure.search.documents.indexes.SearchIndexClient-classLevelJavaDoc.listIndexes - } - - /** - * Code snippet for retrieving an index - */ - public static void getIndex() { - searchIndexClient = createSearchIndexClient(); - // BEGIN: com.azure.search.documents.indexes.SearchIndexClient-classLevelJavaDoc.getIndex#String - SearchIndex searchIndex = searchIndexClient.getIndex("indexName"); - if (searchIndex != null) { - System.out.println("The ETag of the index is " + searchIndex.getETag()); - } - // END: com.azure.search.documents.indexes.SearchIndexClient-classLevelJavaDoc.getIndex#String - } - - /** - * Code snippet for updating an index - */ - public static void updateIndex() { - searchIndexClient = createSearchIndexClient(); - // BEGIN: com.azure.search.documents.indexes.SearchIndexClient-classLevelJavaDoc.updateIndex#SearchIndex - SearchIndex searchIndex = searchIndexClient.getIndex("indexName"); - if (searchIndex != null) { - searchIndex.setFields(new SearchField("newField", SearchFieldDataType.STRING)); - searchIndexClient.createOrUpdateIndex(searchIndex); - } - // END: com.azure.search.documents.indexes.SearchIndexClient-classLevelJavaDoc.updateIndex#SearchIndex - } - - /** - * Code snippet for deleting an index - */ - public static void deleteIndex() { - searchIndexClient = createSearchIndexClient(); - // BEGIN: com.azure.search.documents.indexes.SearchIndexClient-classLevelJavaDoc.deleteIndex#String - String indexName = "indexName"; - searchIndexClient.deleteIndex(indexName); - // END: com.azure.search.documents.indexes.SearchIndexClient-classLevelJavaDoc.deleteIndex#String - } - - /** - * Code snippet for creating a synonym map - */ - public static void createSynonymMap() { - searchIndexClient = createSearchIndexClient(); - // BEGIN: com.azure.search.documents.indexes.SearchIndexClient-classLevelJavaDoc.createSynonymMap#SynonymMap - SynonymMap synonymMap = new SynonymMap("synonymMapName", "hotel, motel, \"motor inn\""); - searchIndexClient.createSynonymMap(synonymMap); - // END: com.azure.search.documents.indexes.SearchIndexClient-classLevelJavaDoc.createSynonymMap#SynonymMap - } - - /** - * Code snippet for listing all synonym maps - */ - public static void listSynonymMaps() { - searchIndexClient = createSearchIndexClient(); - // BEGIN: com.azure.search.documents.indexes.SearchIndexClient-classLevelJavaDoc.listSynonymMaps - searchIndexClient.listSynonymMaps().forEach(synonymMap -> System.out.println(synonymMap.getName())); - // END: com.azure.search.documents.indexes.SearchIndexClient-classLevelJavaDoc.listSynonymMaps - } - - /** - * Code snippet for retrieving a synonym map - */ - public static void getSynonymMap() { - searchIndexClient = createSearchIndexClient(); - // BEGIN: com.azure.search.documents.indexes.SearchIndexClient-classLevelJavaDoc.getSynonymMap#String - SynonymMap synonymMap = searchIndexClient.getSynonymMap("synonymMapName"); - if (synonymMap != null) { - System.out.println("The ETag of the synonymMap is " + synonymMap.getETag()); - } - // END: com.azure.search.documents.indexes.SearchIndexClient-classLevelJavaDoc.getSynonymMap#String - } - - /** - * Code snippet for updating a synonym map - */ - public static void updateSynonymMap() { - searchIndexClient = createSearchIndexClient(); - // BEGIN: com.azure.search.documents.indexes.SearchIndexClient-classLevelJavaDoc.updateSynonymMap#SynonymMap - SynonymMap synonymMap = searchIndexClient.getSynonymMap("synonymMapName"); - if (synonymMap != null) { - synonymMap.setSynonyms("inn,hotel,motel"); - searchIndexClient.createOrUpdateSynonymMap(synonymMap); - } - // END: com.azure.search.documents.indexes.SearchIndexClient-classLevelJavaDoc.updateSynonymMap#SynonymMap - } - - /** - * Code snippet for deleting a synonym map - */ - public static void deleteSynonymMap() { - searchIndexClient = createSearchIndexClient(); - // BEGIN: com.azure.search.documents.indexes.SearchIndexClient-classLevelJavaDoc.deleteSynonymMap#String - String synonymMapName = "synonymMapName"; - searchIndexClient.deleteSynonymMap(synonymMapName); - // END: com.azure.search.documents.indexes.SearchIndexClient-classLevelJavaDoc.deleteSynonymMap#String - } -} diff --git a/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/codesnippets/SearchIndexerAsyncClientJavaDocSnippets.java b/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/codesnippets/SearchIndexerAsyncClientJavaDocSnippets.java deleted file mode 100644 index cd5e59a21150..000000000000 --- a/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/codesnippets/SearchIndexerAsyncClientJavaDocSnippets.java +++ /dev/null @@ -1,225 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -package com.azure.search.documents.codesnippets; - -import com.azure.core.credential.AzureKeyCredential; -import com.azure.search.documents.indexes.SearchIndexerAsyncClient; -import com.azure.search.documents.indexes.SearchIndexerClientBuilder; -import com.azure.search.documents.indexes.models.InputFieldMappingEntry; -import com.azure.search.documents.indexes.models.OcrSkill; -import com.azure.search.documents.indexes.models.OutputFieldMappingEntry; -import com.azure.search.documents.indexes.models.SearchIndexer; -import com.azure.search.documents.indexes.models.SearchIndexerSkill; -import com.azure.search.documents.indexes.models.SearchIndexerSkillset; - -import java.util.Arrays; -import java.util.Collections; -import java.util.List; -@SuppressWarnings("unused") -public class SearchIndexerAsyncClientJavaDocSnippets { - - private static SearchIndexerAsyncClient searchIndexerAsyncClient; - - /** - * Code snippet for creating a {@link SearchIndexerAsyncClient} - */ - private static SearchIndexerAsyncClient createSearchIndexerAsyncClient() { - // BEGIN: com.azure.search.documents.indexes.SearchIndexerAsyncClient-classLevelJavaDoc.instantiation - SearchIndexerAsyncClient searchIndexerAsyncClient = new SearchIndexerClientBuilder() - .endpoint("{endpoint}") - .credential(new AzureKeyCredential("{admin-key}")) - .buildAsyncClient(); - // END: com.azure.search.documents.indexes.SearchIndexerAsyncClient-classLevelJavaDoc.instantiation - return searchIndexerAsyncClient; - } - - /** - * Code snippet for creating an indexer using {@link SearchIndexerAsyncClient} - */ - public static void createIndexer() { - - - searchIndexerAsyncClient = createSearchIndexerAsyncClient(); - // BEGIN: com.azure.search.documents.SearchIndexerAsyncClient-classLevelJavaDoc.createIndexer#SearchIndexer - SearchIndexer indexer = new SearchIndexer("example-indexer", "example-datasource", "example-index"); - SearchIndexer createdIndexer = searchIndexerAsyncClient.createIndexer(indexer).block(); - if (createdIndexer != null) { - System.out.printf("Created indexer name: %s%n", createdIndexer.getName()); - } - // END: com.azure.search.documents.SearchIndexerAsyncClient-classLevelJavaDoc.createIndexer#SearchIndexer - - } - - /** - * Code snippet for listing all indexers using {@link SearchIndexerAsyncClient} - */ - public static void listIndexers() { - searchIndexerAsyncClient = createSearchIndexerAsyncClient(); - // BEGIN: com.azure.search.documents.SearchIndexerAsyncClient-classLevelJavaDoc.listIndexers - searchIndexerAsyncClient.listIndexers().subscribe(indexer -> - System.out.printf("Retrieved indexer name: %s%n", indexer.getName()) - ); - // END: com.azure.search.documents.SearchIndexerAsyncClient-classLevelJavaDoc.listIndexers - } - - /** - * Code snippet for getting an indexer using {@link SearchIndexerAsyncClient} - */ - public static void getIndexer() { - searchIndexerAsyncClient = createSearchIndexerAsyncClient(); - // BEGIN: com.azure.search.documents.SearchIndexerAsyncClient-classLevelJavaDoc.getIndexer#String - SearchIndexer indexer = searchIndexerAsyncClient.getIndexer("example-indexer").block(); - if (indexer != null) { - System.out.printf("Retrieved indexer name: %s%n", indexer.getName()); - } - // END: com.azure.search.documents.SearchIndexerAsyncClient-classLevelJavaDoc.getIndexer#String - } - - /** - * Code snippet for updating an indexer using {@link SearchIndexerAsyncClient} - */ - public static void updateIndexer() { - searchIndexerAsyncClient = createSearchIndexerAsyncClient(); - // BEGIN: com.azure.search.documents.indexes.SearchIndexerAsyncClient-classLevelJavaDoc.updateIndexer#SearchIndexer - SearchIndexer indexer = searchIndexerAsyncClient.getIndexer("example-indexer").block(); - if (indexer != null) { - System.out.printf("Retrieved indexer name: %s%n", indexer.getName()); - indexer.setDescription("This is a new description for this indexer"); - SearchIndexer updatedIndexer = searchIndexerAsyncClient.createOrUpdateIndexer(indexer).block(); - - if (updatedIndexer != null) { - System.out.printf("Updated indexer name: %s, description: %s%n", updatedIndexer.getName(), - updatedIndexer.getDescription()); - } - } - - // END: com.azure.search.documents.indexes.SearchIndexerAsyncClient-classLevelJavaDoc.updateIndexer#SearchIndexer - } - - /** - * Code snippet for deleting an indexer using {@link SearchIndexerAsyncClient} - */ - public static void deleteIndexer() { - searchIndexerAsyncClient = createSearchIndexerAsyncClient(); - // BEGIN: com.azure.search.documents.SearchIndexerAsyncClient-classLevelJavaDoc.deleteIndexer#String - searchIndexerAsyncClient.deleteIndexer("example-indexer"); - // END: com.azure.search.documents.SearchIndexerAsyncClient-classLevelJavaDoc.deleteIndexer#String - } - - /** - * Code snippet for running an indexer using {@link SearchIndexerAsyncClient} - */ - public static void runIndexer() { - searchIndexerAsyncClient = createSearchIndexerAsyncClient(); - // BEGIN: com.azure.search.documents.SearchIndexerAsyncClient-classLevelJavaDoc.runIndexer#String - searchIndexerAsyncClient.runIndexer("example-indexer"); - // END: com.azure.search.documents.SearchIndexerAsyncClient-classLevelJavaDoc.runIndexer#String - } - - /** - * Code snippet for resetting an indexer using {@link SearchIndexerAsyncClient} - */ - public static void resetIndexer() { - searchIndexerAsyncClient = createSearchIndexerAsyncClient(); - // BEGIN: com.azure.search.documents.SearchIndexerAsyncClient-classLevelJavaDoc.resetIndexer#String - searchIndexerAsyncClient.resetIndexer("example-indexer"); - // END: com.azure.search.documents.SearchIndexerAsyncClient-classLevelJavaDoc.resetIndexer#String - } - - /** - * Code snippet for creating a skillset using {@link SearchIndexerAsyncClient} - */ - public static void createSkillset() { - searchIndexerAsyncClient = createSearchIndexerAsyncClient(); - // BEGIN: com.azure.search.documents.SearchIndexerAsyncClient-classLevelJavaDoc.createSkillset#SearchIndexerSkillset - List inputs = Collections.singletonList( - new InputFieldMappingEntry("image") - .setSource("/document/normalized_images/*") - ); - - List outputs = Arrays.asList( - new OutputFieldMappingEntry("text") - .setTargetName("mytext"), - new OutputFieldMappingEntry("layoutText") - .setTargetName("myLayoutText") - ); - - List skills = Collections.singletonList( - new OcrSkill(inputs, outputs) - .setShouldDetectOrientation(true) - .setDefaultLanguageCode(null) - .setName("myocr") - .setDescription("Extracts text (plain and structured) from image.") - .setContext("/document/normalized_images/*") - ); - - SearchIndexerSkillset skillset = new SearchIndexerSkillset("skillsetName", skills) - .setDescription("Extracts text (plain and structured) from image."); - - System.out.println(String.format("Creating OCR skillset '%s'", skillset.getName())); - - SearchIndexerSkillset createdSkillset = searchIndexerAsyncClient.createSkillset(skillset).block(); - - if (createdSkillset != null) { - System.out.println("Created OCR skillset"); - System.out.println(String.format("Name: %s", createdSkillset.getName())); - System.out.println(String.format("ETag: %s", createdSkillset.getETag())); - } - // END: com.azure.search.documents.SearchIndexerAsyncClient-classLevelJavaDoc.createSkillset#SearchIndexerSkillset - } - - /** - * Code snippet for listing all skillsets using {@link SearchIndexerAsyncClient} - */ - public static void listSkillsets() { - searchIndexerAsyncClient = createSearchIndexerAsyncClient(); - // BEGIN: com.azure.search.documents.SearchIndexerAsyncClient-classLevelJavaDoc.listSkillsets - searchIndexerAsyncClient.listSkillsets().subscribe(skillset -> - System.out.printf("Retrieved skillset name: %s%n", skillset.getName()) - ); - // END: com.azure.search.documents.SearchIndexerAsyncClient-classLevelJavaDoc.listSkillsets - } - - /** - * Code snippet for getting a skillset using {@link SearchIndexerAsyncClient} - */ - public static void getSkillset() { - searchIndexerAsyncClient = createSearchIndexerAsyncClient(); - // BEGIN: com.azure.search.documents.indexes.SearchIndexerAsyncClient-classLevelJavaDoc.getSkillset#String - SearchIndexerSkillset skillset = searchIndexerAsyncClient.getSkillset("example-skillset").block(); - if (skillset != null) { - System.out.printf("Retrieved skillset name: %s%n", skillset.getName()); - } - // END: com.azure.search.documents.indexes.SearchIndexerAsyncClient-classLevelJavaDoc.getSkillset#String - } - - /** - * Code snippet for updating a skillset using {@link SearchIndexerAsyncClient} - */ - public static void updateSkillset() { - searchIndexerAsyncClient = createSearchIndexerAsyncClient(); - // BEGIN: com.azure.search.documents.indexes.SearchIndexerAsyncClient-classLevelJavaDoc.updateSkillset#SearchIndexerSkillset - SearchIndexerSkillset skillset = searchIndexerAsyncClient.getSkillset("example-skillset").block(); - if (skillset != null) { - System.out.printf("Retrieved skillset name: %s%n", skillset.getName()); - SearchIndexerSkillset updatedSkillset = searchIndexerAsyncClient.createOrUpdateSkillset(skillset).block(); - - if (updatedSkillset != null) { - System.out.printf("Updated skillset name: %s, description: %s%n", updatedSkillset.getName(), - updatedSkillset.getDescription()); - } - } - // END: com.azure.search.documents.indexes.SearchIndexerAsyncClient-classLevelJavaDoc.updateSkillset#SearchIndexerSkillset - } - - /** - * Code snippet for deleting a skillset using {@link SearchIndexerAsyncClient} - */ - public static void deleteSkillset() { - searchIndexerAsyncClient = createSearchIndexerAsyncClient(); - // BEGIN: com.azure.search.documents.SearchIndexerAsyncClient-classLevelJavaDoc.deleteSkillset#String - searchIndexerAsyncClient.deleteSkillset("example-skillset"); - // END: com.azure.search.documents.SearchIndexerAsyncClient-classLevelJavaDoc.deleteSkillset#String - } - -} diff --git a/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/codesnippets/SearchIndexerClientBuilderJavaDocsSnippets.java b/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/codesnippets/SearchIndexerClientBuilderJavaDocsSnippets.java deleted file mode 100644 index d8213da923a4..000000000000 --- a/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/codesnippets/SearchIndexerClientBuilderJavaDocsSnippets.java +++ /dev/null @@ -1,69 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -package com.azure.search.documents.codesnippets; - -import com.azure.core.credential.AzureKeyCredential; -import com.azure.identity.DefaultAzureCredential; -import com.azure.identity.DefaultAzureCredentialBuilder; -import com.azure.search.documents.indexes.SearchIndexerAsyncClient; -import com.azure.search.documents.indexes.SearchIndexerClient; -import com.azure.search.documents.indexes.SearchIndexerClientBuilder; -@SuppressWarnings("unused") -public class SearchIndexerClientBuilderJavaDocsSnippets { - - /** - * Code snippet for creating a {@link com.azure.search.documents.indexes.SearchIndexerClient} - */ - public SearchIndexerClient createSearchIndexerClient() { - // BEGIN: com.azure.search.documents.indexes.SearchIndexerClientBuilder.instantiation.SearchIndexerClient - SearchIndexerClient searchIndexerClient = new SearchIndexerClientBuilder() - .credential(new AzureKeyCredential("{key}")) - .endpoint("{endpoint}") - .buildClient(); - // END: com.azure.search.documents.indexes.SearchIndexerClientBuilder.instantiation.SearchIndexerClient - return searchIndexerClient; - } - - /** - * Code snippet for creating a {@link com.azure.search.documents.indexes.SearchIndexerAsyncClient} - */ - public SearchIndexerAsyncClient createSearchIndexerAsyncClient() { - // BEGIN: com.azure.search.documents.indexes.SearchIndexerClientBuilder.instantiation.SearchIndexerAsyncClient - SearchIndexerAsyncClient searchIndexerAsyncClient = new SearchIndexerClientBuilder() - .credential(new AzureKeyCredential("{key}")) - .endpoint("{endpoint}") - .buildAsyncClient(); - // END: com.azure.search.documents.indexes.SearchIndexerClientBuilder.instantiation.SearchIndexerAsyncClient - return searchIndexerAsyncClient; - } - - /** - * Code snippet for authenticating a synchronous client with Default Azure Credential. - */ - public SearchIndexerClient createSearchIndexerClientWithDefaultAzureCredential() { - // BEGIN: com.azure.search.documents.indexes.SearchIndexerClientBuilder-classLevelJavaDoc.DefaultAzureCredential - DefaultAzureCredential credential = new DefaultAzureCredentialBuilder().build(); - - SearchIndexerClient searchIndexerClient = new SearchIndexerClientBuilder() - .endpoint("{endpoint}") - .credential(credential) - .buildClient(); - // END: com.azure.search.documents.indexes.SearchIndexerClientBuilder-classLevelJavaDoc.DefaultAzureCredential - return searchIndexerClient; - } - - /** - * Code snippet for authenticating an asynchronous client with Default Azure Credential. - */ - public SearchIndexerAsyncClient createSearchIndexerAsyncClientWithDefaultAzureCredential() { - // BEGIN: com.azure.search.documents.indexes.SearchIndexerClientBuilder-classLevelJavaDoc.async.DefaultAzureCredential - DefaultAzureCredential credential = new DefaultAzureCredentialBuilder().build(); - - SearchIndexerAsyncClient searchIndexerAsyncClient = new SearchIndexerClientBuilder() - .endpoint("{endpoint}") - .credential(credential) - .buildAsyncClient(); - // END: com.azure.search.documents.indexes.SearchIndexerClientBuilder-classLevelJavaDoc.async.DefaultAzureCredential - return searchIndexerAsyncClient; - } -} diff --git a/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/codesnippets/SearchIndexerClientJavaDocSnippets.java b/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/codesnippets/SearchIndexerClientJavaDocSnippets.java deleted file mode 100644 index 57e48b2b42e5..000000000000 --- a/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/codesnippets/SearchIndexerClientJavaDocSnippets.java +++ /dev/null @@ -1,206 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -package com.azure.search.documents.codesnippets; - -import com.azure.core.credential.AzureKeyCredential; -import com.azure.search.documents.indexes.SearchIndexerClient; -import com.azure.search.documents.indexes.SearchIndexerClientBuilder; -import com.azure.search.documents.indexes.models.InputFieldMappingEntry; -import com.azure.search.documents.indexes.models.OcrSkill; -import com.azure.search.documents.indexes.models.OutputFieldMappingEntry; -import com.azure.search.documents.indexes.models.SearchIndexer; -import com.azure.search.documents.indexes.models.SearchIndexerSkill; -import com.azure.search.documents.indexes.models.SearchIndexerSkillset; - -import java.util.Arrays; -import java.util.Collections; -import java.util.List; -@SuppressWarnings("unused") -public class SearchIndexerClientJavaDocSnippets { - - - private static SearchIndexerClient searchIndexerClient; - - /** - * Code snippet for creating a {@link SearchIndexerClient} - */ - private static SearchIndexerClient createSearchIndexerClient() { - // BEGIN: com.azure.search.documents.SearchIndexerClient-classLevelJavaDoc.instantiation - SearchIndexerClient searchIndexerClient = new SearchIndexerClientBuilder() - .endpoint("{endpoint}") - .credential(new AzureKeyCredential("{admin-key}")) - .buildClient(); - // END: com.azure.search.documents.SearchIndexerClient-classLevelJavaDoc.instantiation - return searchIndexerClient; - } - - /** - * Code snippet for creating an indexer using {@link SearchIndexerClient} - */ - public static void createIndexer() { - searchIndexerClient = createSearchIndexerClient(); - // BEGIN: com.azure.search.documents.SearchIndexerClient-classLevelJavaDoc.createIndexer#SearchIndexer - SearchIndexer indexer = new SearchIndexer("example-indexer", "example-datasource", "example-index"); - SearchIndexer createdIndexer = searchIndexerClient.createIndexer(indexer); - System.out.printf("Created indexer name: %s%n", createdIndexer.getName()); - // END: com.azure.search.documents.SearchIndexerClient-classLevelJavaDoc.createIndexer#SearchIndexer - } - - /** - * Code snippet for listing all indexers using {@link SearchIndexerClient} - */ - public static void listIndexers() { - searchIndexerClient = createSearchIndexerClient(); - // BEGIN: com.azure.search.documents.SearchIndexerClient-classLevelJavaDoc.listIndexers - searchIndexerClient.listIndexers().forEach(indexer -> - System.out.printf("Retrieved indexer name: %s%n", indexer.getName()) - ); - // END: com.azure.search.documents.SearchIndexerClient-classLevelJavaDoc.listIndexers - } - - /** - * Code snippet for getting an indexer using {@link SearchIndexerClient} - */ - public static void getIndexer() { - searchIndexerClient = createSearchIndexerClient(); - // BEGIN: com.azure.search.documents.SearchIndexerClient-classLevelJavaDoc.getIndexer#String - SearchIndexer indexer = searchIndexerClient.getIndexer("example-indexer"); - System.out.printf("Retrieved indexer name: %s%n", indexer.getName()); - // END: com.azure.search.documents.SearchIndexerClient-classLevelJavaDoc.getIndexer#String - } - - /** - * Code snippet for updating an indexer using {@link SearchIndexerClient} - */ - public static void updateIndexer() { - searchIndexerClient = createSearchIndexerClient(); - // BEGIN: com.azure.search.documents.SearchIndexerClient-classLevelJavaDoc.updateIndexer#SearchIndexer - SearchIndexer indexer = searchIndexerClient.getIndexer("example-indexer"); - indexer.setDescription("This is a new description for this indexer"); - SearchIndexer updatedIndexer = searchIndexerClient.createOrUpdateIndexer(indexer); - System.out.printf("Updated indexer name: %s, description: %s%n", updatedIndexer.getName(), - updatedIndexer.getDescription()); - // END: com.azure.search.documents.SearchIndexerClient-classLevelJavaDoc.updateIndexer#SearchIndexer - } - - /** - * Code snippet for deleting an indexer using {@link SearchIndexerClient} - */ - public static void deleteIndexer() { - searchIndexerClient = createSearchIndexerClient(); - // BEGIN: com.azure.search.documents.SearchIndexerClient-classLevelJavaDoc.deleteIndexer#String - searchIndexerClient.deleteIndexer("example-indexer"); - // END: com.azure.search.documents.SearchIndexerClient-classLevelJavaDoc.deleteIndexer#String - } - - /** - * Code snippet for running an indexer using {@link SearchIndexerClient} - */ - public static void runIndexer() { - searchIndexerClient = createSearchIndexerClient(); - // BEGIN: com.azure.search.documents.SearchIndexerClient-classLevelJavaDoc.runIndexer#String - searchIndexerClient.runIndexer("example-indexer"); - // END: com.azure.search.documents.SearchIndexerClient-classLevelJavaDoc.runIndexer#String - } - - /** - * Code snippet for resetting an indexer using {@link SearchIndexerClient} - */ - public static void resetIndexer() { - searchIndexerClient = createSearchIndexerClient(); - // BEGIN: com.azure.search.documents.SearchIndexerClient-classLevelJavaDoc.resetIndexer#String - searchIndexerClient.resetIndexer("example-indexer"); - // END: com.azure.search.documents.SearchIndexerClient-classLevelJavaDoc.resetIndexer#String - } - - /** - * Code snippet for creating a skillset using {@link SearchIndexerClient} - */ - public static void createSkillset() { - searchIndexerClient = createSearchIndexerClient(); - // BEGIN: com.azure.search.documents.SearchIndexerClient-classLevelJavaDoc.createSkillset#SearchIndexerSkillset - - List inputs = Collections.singletonList( - new InputFieldMappingEntry("image") - .setSource("/document/normalized_images/*") - ); - - List outputs = Arrays.asList( - new OutputFieldMappingEntry("text") - .setTargetName("mytext"), - new OutputFieldMappingEntry("layoutText") - .setTargetName("myLayoutText") - ); - - List skills = Collections.singletonList( - new OcrSkill(inputs, outputs) - .setShouldDetectOrientation(true) - .setDefaultLanguageCode(null) - .setName("myocr") - .setDescription("Extracts text (plain and structured) from image.") - .setContext("/document/normalized_images/*") - ); - - SearchIndexerSkillset skillset = new SearchIndexerSkillset("skillsetName", skills) - .setDescription("Extracts text (plain and structured) from image."); - - System.out.println(String.format("Creating OCR skillset '%s'", skillset.getName())); - - SearchIndexerSkillset createdSkillset = searchIndexerClient.createSkillset(skillset); - - System.out.println("Created OCR skillset"); - System.out.println(String.format("Name: %s", createdSkillset.getName())); - System.out.println(String.format("ETag: %s", createdSkillset.getETag())); - - // END: com.azure.search.documents.SearchIndexerClient-classLevelJavaDoc.createSkillset#SearchIndexerSkillset - } - - /** - * Code snippet for listing all skillsets using {@link SearchIndexerClient} - */ - public static void listSkillsets() { - searchIndexerClient = createSearchIndexerClient(); - // BEGIN: com.azure.search.documents.SearchIndexerClient-classLevelJavaDoc.listSkillsets - searchIndexerClient.listSkillsets().forEach(skillset -> - System.out.printf("Retrieved skillset name: %s%n", skillset.getName()) - ); - // END: com.azure.search.documents.SearchIndexerClient-classLevelJavaDoc.listSkillsets - } - - /** - * Code snippet for getting a skillset using {@link SearchIndexerClient} - */ - public static void getSkillset() { - searchIndexerClient = createSearchIndexerClient(); - // BEGIN: com.azure.search.documents.SearchIndexerClient-classLevelJavaDoc.getSkillset#String - SearchIndexerSkillset skillset = searchIndexerClient.getSkillset("example-skillset"); - System.out.printf("Retrieved skillset name: %s%n", skillset.getName()); - // END: com.azure.search.documents.SearchIndexerClient-classLevelJavaDoc.getSkillset#String - } - - /** - * Code snippet for updating a skillset using {@link SearchIndexerClient} - */ - public static void updateSkillset() { - searchIndexerClient = createSearchIndexerClient(); - // BEGIN: com.azure.search.documents.SearchIndexerClient-classLevelJavaDoc.updateSkillset#SearchIndexerSkillset - SearchIndexerSkillset skillset = searchIndexerClient.getSkillset("example-skillset"); - skillset.setDescription("This is a new description for this skillset"); - SearchIndexerSkillset updatedSkillset = searchIndexerClient.createOrUpdateSkillset(skillset); - System.out.printf("Updated skillset name: %s, description: %s%n", updatedSkillset.getName(), - updatedSkillset.getDescription()); - // END: com.azure.search.documents.SearchIndexerClient-classLevelJavaDoc.updateSkillset#SearchIndexerSkillset - } - - /** - * Code snippet for deleting a skillset using {@link SearchIndexerClient} - */ - public static void deleteSkillset() { - searchIndexerClient = createSearchIndexerClient(); - // BEGIN: com.azure.search.documents.SearchIndexerClient-classLevelJavaDoc.deleteSkillset#String - searchIndexerClient.deleteSkillset("example-skillset"); - // END: com.azure.search.documents.SearchIndexerClient-classLevelJavaDoc.deleteSkillset#String - } - - -} diff --git a/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/codesnippets/SearchPackageInfoJavaDocSnippets.java b/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/codesnippets/SearchPackageInfoJavaDocSnippets.java deleted file mode 100644 index 59f4ceefd235..000000000000 --- a/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/codesnippets/SearchPackageInfoJavaDocSnippets.java +++ /dev/null @@ -1,290 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -package com.azure.search.documents.codesnippets; - -import com.azure.core.credential.AzureKeyCredential; -import com.azure.core.exception.HttpResponseException; -import com.azure.core.http.HttpResponse; -import com.azure.core.util.Context; -import com.azure.identity.DefaultAzureCredentialBuilder; -import com.azure.search.documents.SearchClient; -import com.azure.search.documents.SearchClientBuilder; -import com.azure.search.documents.SearchDocument; -import com.azure.search.documents.indexes.SearchIndexClient; -import com.azure.search.documents.indexes.SearchIndexClientBuilder; -import com.azure.search.documents.indexes.SearchIndexerClient; -import com.azure.search.documents.indexes.SearchIndexerClientBuilder; -import com.azure.search.documents.indexes.SimpleField; -import com.azure.search.documents.indexes.models.IndexDocumentsBatch; -import com.azure.search.documents.indexes.models.LexicalAnalyzerName; -import com.azure.search.documents.indexes.models.SearchField; -import com.azure.search.documents.indexes.models.SearchFieldDataType; -import com.azure.search.documents.indexes.models.SearchIndex; -import com.azure.search.documents.indexes.models.SearchSuggester; -import com.azure.search.documents.models.SearchAudience; -import com.azure.search.documents.models.SearchOptions; -import com.azure.search.documents.models.SearchResult; -import com.azure.search.documents.util.SearchPagedIterable; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -@SuppressWarnings("unused") -public class SearchPackageInfoJavaDocSnippets { - - /** - * Code snippet for creating a {@link SearchIndexClient} - * - * @return the created SearchIndexClient - */ - public SearchIndexClient createSearchIndexClient() { - // BEGIN: com.azure.search.documents.packageInfo-SearchIndexClient.instantiation - SearchIndexClient searchIndexClient = new SearchIndexClientBuilder() - .endpoint("{endpoint}") - .credential(new AzureKeyCredential("{key}")) - .buildClient(); - // END: com.azure.search.documents.packageInfo-SearchIndexClient.instantiation - return searchIndexClient; - } - - /** - * Code snippet for creating a {@link SearchIndexerClient} - * - * @return the created SearchIndexerClient - */ - public SearchIndexerClient createSearchIndexerClient() { - // BEGIN: com.azure.search.documents.packageInfo-SearchIndexerClient.instantiation - SearchIndexerClient searchIndexerClient = new SearchIndexerClientBuilder() - .endpoint("{endpoint}") - .credential(new AzureKeyCredential("{key}")) - .buildClient(); - // END: com.azure.search.documents.packageInfo-SearchIndexerClient.instantiation - return searchIndexerClient; - } - - /** - * Code snippet for creating a {@link SearchClient} - * - * @return the created SearchClient - */ - public SearchClient createSearchClient() { - // BEGIN: com.azure.search.documents.packageInfo-SearchClient.instantiation - SearchClient searchClient = new SearchClientBuilder() - .endpoint("{endpoint}") - .credential(new AzureKeyCredential("{key}")) - .indexName("{indexName}") - .buildClient(); - // END: com.azure.search.documents.packageInfo-SearchClient.instantiation - return searchClient; - } - - /** - * Query using SearchDocument as a dictionary for search results - */ - public void searchDocumentDictionary() { - SearchClient searchClient = createSearchClient(); - // BEGIN: com.azure.search.documents.packageInfo-SearchClient.search#String - for (SearchResult result : searchClient.search("luxury")) { - SearchDocument document = result.getDocument(SearchDocument.class); - System.out.printf("Hotel ID: %s%n", document.get("hotelId")); - System.out.printf("Hotel Name: %s%n", document.get("hotelName")); - } - // END: com.azure.search.documents.packageInfo-SearchClient.search#String - } - - - //BEGIN: hotelExampleClass - public static class Hotel { - private String hotelId; - private String hotelName; - - @SimpleField(isKey = true) - public String getHotelId() { - return this.hotelId; - } - - public String getHotelName() { - return this.hotelName; - } - - public Hotel setHotelId(String number) { - this.hotelId = number; - return this; - } - - public Hotel setHotelName(String secretPointMotel) { - this.hotelName = secretPointMotel; - return this; - } - } - //END: hotelExampleClass - - /** - * Query using Java model class for search results - */ - public void searchModelClass() { - SearchClient searchClient = createSearchClient(); - - - // BEGIN: com.azure.search.documents.packageInfo-SearchClient.search#String-Object-Class-Method - for (SearchResult result : searchClient.search("luxury")) { - Hotel hotel = result.getDocument(Hotel.class); - System.out.printf("Hotel ID: %s%n", hotel.getHotelId()); - System.out.printf("Hotel Name: %s%n", hotel.getHotelName()); - } - // END: com.azure.search.documents.packageInfo-SearchClient.search#String-Object-Class-Method - - } - - /** - * Query using SearchOptions - */ - public void searchWithOptions() { - SearchClient searchClient = createSearchClient(); - // BEGIN: com.azure.search.documents.packageInfo-SearchClient.search#SearchOptions - SearchOptions options = new SearchOptions() - .setFilter("rating gt 4") - .setOrderBy("rating desc") - .setTop(5); - SearchPagedIterable searchResultsIterable = searchClient.search("luxury", options, Context.NONE); - searchResultsIterable.forEach(result -> { - System.out.printf("Hotel ID: %s%n", result.getDocument(Hotel.class).getHotelId()); - System.out.printf("Hotel Name: %s%n", result.getDocument(Hotel.class).getHotelName()); - }); - // END: com.azure.search.documents.packageInfo-SearchClient.search#SearchOptions - } - - /** - * Create an index using SearchIndexClient - */ - public void createSearchIndex() { - SearchIndexClient searchIndexClient = createSearchIndexClient(); - // BEGIN: com.azure.search.documents.packageInfo-SearchIndexClient.createIndex#SearchIndex - // Create a new search index structure that matches the properties of the Hotel class. - List searchFields = SearchIndexClient.buildSearchFields(Hotel.class, null); - searchIndexClient.createIndex(new SearchIndex("hotels", searchFields)); - // END: com.azure.search.documents.packageInfo-SearchIndexClient.createIndex#SearchIndex - } - - /** - * Build search fields using SearchField directly and create an index using SearchIndexClient - */ - public void createSearchIndexWithSearchField() { - SearchIndexClient searchIndexClient = createSearchIndexClient(); - // BEGIN: com.azure.search.documents.packageInfo-SearchIndexClient.createIndex#String-List-boolean - // Create a new search index structure that matches the properties of the Hotel class. - List searchFieldList = new ArrayList<>(); - searchFieldList.add(new SearchField("hotelId", SearchFieldDataType.STRING) - .setKey(true) - .setFilterable(true) - .setSortable(true)); - - searchFieldList.add(new SearchField("hotelName", SearchFieldDataType.STRING) - .setSearchable(true) - .setFilterable(true) - .setSortable(true)); - searchFieldList.add(new SearchField("description", SearchFieldDataType.STRING) - .setSearchable(true) - .setAnalyzerName(LexicalAnalyzerName.EU_LUCENE)); - searchFieldList.add(new SearchField("tags", SearchFieldDataType.collection(SearchFieldDataType.STRING)) - .setSearchable(true) - .setFilterable(true) - .setFacetable(true)); - searchFieldList.add(new SearchField("address", SearchFieldDataType.COMPLEX) - .setFields(new SearchField("streetAddress", SearchFieldDataType.STRING).setSearchable(true), - new SearchField("city", SearchFieldDataType.STRING) - .setSearchable(true) - .setFilterable(true) - .setFacetable(true) - .setSortable(true), - new SearchField("stateProvince", SearchFieldDataType.STRING) - .setSearchable(true) - .setFilterable(true) - .setFacetable(true) - .setSortable(true), - new SearchField("country", SearchFieldDataType.STRING) - .setSearchable(true) - .setFilterable(true) - .setFacetable(true) - .setSortable(true), - new SearchField("postalCode", SearchFieldDataType.STRING) - .setSearchable(true) - .setFilterable(true) - .setFacetable(true) - .setSortable(true) - )); - - // Prepare suggester. - SearchSuggester suggester = new SearchSuggester("sg", Collections.singletonList("hotelName")); - // Prepare SearchIndex with index name and search fields. - SearchIndex index = new SearchIndex("hotels").setFields(searchFieldList).setSuggesters(suggester); - // Create an index - searchIndexClient.createIndex(index); - // END: com.azure.search.documents.packageInfo-SearchIndexClient.createIndex#String-List-boolean - } - - /** - * Retrieve a specific document using key. - */ - public void getDocument() { - SearchClient searchClient = createSearchClient(); - // BEGIN: com.azure.search.documents.packageInfo-SearchClient.getDocument#String-String - Hotel hotel = searchClient.getDocument("1", Hotel.class); - System.out.printf("Hotel ID: %s%n", hotel.getHotelId()); - System.out.printf("Hotel Name: %s%n", hotel.getHotelName()); - // END: com.azure.search.documents.packageInfo-SearchClient.getDocument#String-String - } - - /** - * Adding documents to your index. - */ - public void uploadDocuments() { - SearchClient searchClient = createSearchClient(); - // BEGIN: com.azure.search.documents.packageInfo-SearchClient.uploadDocuments#Iterable-boolean-boolean - IndexDocumentsBatch batch = new IndexDocumentsBatch(); - batch.addUploadActions(Collections.singletonList( - new Hotel().setHotelId("783").setHotelName("Upload Inn"))); - batch.addMergeActions(Collections.singletonList( - new Hotel().setHotelId("12").setHotelName("Renovated Ranch"))); - searchClient.indexDocuments(batch); - // END: com.azure.search.documents.packageInfo-SearchClient.uploadDocuments#Iterable-boolean-boolean - } - - /** - * Authenticate SearchClient in a national cloud. - */ - public SearchClient createSearchClientInNationalCloud() { - // BEGIN: com.azure.search.documents.packageInfo-SearchClient.instantiation.nationalCloud - SearchClient searchClient = new SearchClientBuilder() - .endpoint("{endpoint}") - .credential(new DefaultAzureCredentialBuilder() - .authorityHost("{national cloud endpoint}") - .build()) - .audience(SearchAudience.AZURE_PUBLIC_CLOUD) //set the audience of your cloud - .buildClient(); - // END: com.azure.search.documents.packageInfo-SearchClient.instantiation.nationalCloud - return searchClient; - } - - /** - * Handle Search Error Response - */ - public void handleSearchError() { - SearchClient searchClient = createSearchClient(); - // BEGIN: com.azure.search.documents.packageInfo-SearchClient.search#String-Object-Class-Error - try { - Iterable results = searchClient.search("hotel"); - results.forEach(result -> { - System.out.println(result.getDocument(Hotel.class).getHotelName()); - }); - } catch (HttpResponseException ex) { - // The exception contains the HTTP status code and the detailed message - // returned from the search service - HttpResponse response = ex.getResponse(); - System.out.println("Status Code: " + response.getStatusCode()); - System.out.println("Message: " + ex.getMessage()); - } - // END: com.azure.search.documents.packageInfo-SearchClient.search#String-Object-Class-Error - } - -} diff --git a/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/generated/SearchIndexAutocompleteDocumentsGet.java b/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/generated/SearchIndexAutocompleteDocumentsGet.java new file mode 100644 index 000000000000..93f7d3cc83e2 --- /dev/null +++ b/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/generated/SearchIndexAutocompleteDocumentsGet.java @@ -0,0 +1,26 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.search.documents.generated; + +import com.azure.identity.DefaultAzureCredentialBuilder; +import com.azure.search.documents.DocumentsClient; +import com.azure.search.documents.SearchClientBuilder; +import com.azure.search.documents.models.AutocompleteMode; +import com.azure.search.documents.models.AutocompleteResult; +import java.util.Arrays; + +public class SearchIndexAutocompleteDocumentsGet { + public static void main(String[] args) { + DocumentsClient documentsClient + = new SearchClientBuilder().credential(new DefaultAzureCredentialBuilder().build()) + .endpoint("https://myservice.search.windows.net") + .buildDocumentsClient(); + // BEGIN:com.azure.search.documents.generated.documentsautocompleteget.searchindexautocompletedocumentsget + AutocompleteResult response + = documentsClient.autocompleteGet("washington medic", "sg", "myindex", AutocompleteMode.ONE_TERM, null, + false, "", "", 80.0D, Arrays.asList("title", "description"), null); + // END:com.azure.search.documents.generated.documentsautocompleteget.searchindexautocompletedocumentsget + } +} diff --git a/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/generated/SearchIndexAutocompleteDocumentsPost.java b/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/generated/SearchIndexAutocompleteDocumentsPost.java new file mode 100644 index 000000000000..951c1fb08c93 --- /dev/null +++ b/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/generated/SearchIndexAutocompleteDocumentsPost.java @@ -0,0 +1,32 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.search.documents.generated; + +import com.azure.identity.DefaultAzureCredentialBuilder; +import com.azure.search.documents.DocumentsClient; +import com.azure.search.documents.SearchClientBuilder; +import com.azure.search.documents.models.AutocompleteMode; +import com.azure.search.documents.models.AutocompleteRequest; +import com.azure.search.documents.models.AutocompleteResult; + +public class SearchIndexAutocompleteDocumentsPost { + public static void main(String[] args) { + DocumentsClient documentsClient + = new SearchClientBuilder().credential(new DefaultAzureCredentialBuilder().build()) + .endpoint("https://previewexampleservice.search.windows.net") + .buildDocumentsClient(); + // BEGIN:com.azure.search.documents.generated.documentsautocompletepost.searchindexautocompletedocumentspost + AutocompleteResult response = documentsClient.autocompletePost("preview-test", + new AutocompleteRequest("p", "sg").setAutocompleteMode(AutocompleteMode.ONE_TERM) + .setFilter("ownerId ne '1'") + .setUseFuzzyMatching(true) + .setHighlightPostTag("") + .setHighlightPreTag("") + .setMinimumCoverage(80.0D) + .setSearchFields("category, ownerId") + .setTop(10)); + // END:com.azure.search.documents.generated.documentsautocompletepost.searchindexautocompletedocumentspost + } +} diff --git a/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/generated/SearchIndexCountDocuments.java b/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/generated/SearchIndexCountDocuments.java new file mode 100644 index 000000000000..6557fac60dee --- /dev/null +++ b/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/generated/SearchIndexCountDocuments.java @@ -0,0 +1,21 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.search.documents.generated; + +import com.azure.identity.DefaultAzureCredentialBuilder; +import com.azure.search.documents.DocumentsClient; +import com.azure.search.documents.SearchClientBuilder; + +public class SearchIndexCountDocuments { + public static void main(String[] args) { + DocumentsClient documentsClient + = new SearchClientBuilder().credential(new DefaultAzureCredentialBuilder().build()) + .endpoint("https://previewexampleservice.search.windows.net") + .buildDocumentsClient(); + // BEGIN:com.azure.search.documents.generated.documentscount.searchindexcountdocuments + int response = documentsClient.count("preview-test"); + // END:com.azure.search.documents.generated.documentscount.searchindexcountdocuments + } +} diff --git a/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/generated/SearchIndexGetDocument.java b/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/generated/SearchIndexGetDocument.java new file mode 100644 index 000000000000..18b46a920f38 --- /dev/null +++ b/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/generated/SearchIndexGetDocument.java @@ -0,0 +1,24 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.search.documents.generated; + +import com.azure.identity.DefaultAzureCredentialBuilder; +import com.azure.search.documents.DocumentsClient; +import com.azure.search.documents.SearchClientBuilder; +import com.azure.search.documents.models.LookupDocument; +import java.util.Arrays; + +public class SearchIndexGetDocument { + public static void main(String[] args) { + DocumentsClient documentsClient + = new SearchClientBuilder().credential(new DefaultAzureCredentialBuilder().build()) + .endpoint("https://previewexampleservice.search.windows.net") + .buildDocumentsClient(); + // BEGIN:com.azure.search.documents.generated.documentsget.searchindexgetdocument + LookupDocument response = documentsClient.get("1", "preview-test", + Arrays.asList("id", "description", "name", "category", "ownerId")); + // END:com.azure.search.documents.generated.documentsget.searchindexgetdocument + } +} diff --git a/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/generated/SearchIndexIndexDocuments.java b/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/generated/SearchIndexIndexDocuments.java new file mode 100644 index 000000000000..7e003862ad2e --- /dev/null +++ b/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/generated/SearchIndexIndexDocuments.java @@ -0,0 +1,727 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.search.documents.generated; + +import com.azure.core.util.BinaryData; +import com.azure.identity.DefaultAzureCredentialBuilder; +import com.azure.search.documents.DocumentsClient; +import com.azure.search.documents.SearchClientBuilder; +import com.azure.search.documents.models.IndexAction; +import com.azure.search.documents.models.IndexBatch; +import com.azure.search.documents.models.IndexDocumentsResult; +import java.nio.charset.StandardCharsets; +import java.util.Arrays; +import java.util.HashMap; +import java.util.Map; + +public class SearchIndexIndexDocuments { + public static void main(String[] args) { + DocumentsClient documentsClient + = new SearchClientBuilder().credential(new DefaultAzureCredentialBuilder().build()) + .endpoint("https://previewexampleservice.search.windows.net") + .buildDocumentsClient(); + // BEGIN:com.azure.search.documents.generated.documentsindex.searchindexindexdocuments + IndexDocumentsResult response = documentsClient.index("preview-test", new IndexBatch(Arrays.asList( + new IndexAction().setAdditionalProperties(mapOf("vector1b", + BinaryData.fromBytes("[10, 11, 12, 13, 14, 15, 16, 17, 18, 19]".getBytes(StandardCharsets.UTF_8)), + "vector3", BinaryData.fromBytes("[0, 1, 2, 3, 4]".getBytes(StandardCharsets.UTF_8)), "@search.action", + BinaryData.fromBytes("mergeOrUpload".getBytes(StandardCharsets.UTF_8)), "vector22", + BinaryData.fromBytes("[20, 21, 22, 23, 24, 25, 26, 27, 28, 29]".getBytes(StandardCharsets.UTF_8)), + "price", BinaryData.fromBytes("0".getBytes(StandardCharsets.UTF_8)), "name", + BinaryData.fromBytes("test".getBytes(StandardCharsets.UTF_8)), "description", + BinaryData.fromBytes("test0 hello".getBytes(StandardCharsets.UTF_8)), "id", + BinaryData.fromBytes("0".getBytes(StandardCharsets.UTF_8)), "vector1", + BinaryData.fromBytes("[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]" + .getBytes(StandardCharsets.UTF_8)), + "ownerId", BinaryData.fromBytes("benny".getBytes(StandardCharsets.UTF_8)), "category", + BinaryData.fromBytes("purple".getBytes(StandardCharsets.UTF_8)), "vector2", + BinaryData.fromBytes("[0, 1, 2, 3, 4]".getBytes(StandardCharsets.UTF_8)))), + new IndexAction().setAdditionalProperties(mapOf("vector1b", + BinaryData.fromBytes("[11, 12, 13, 14, 15, 16, 17, 18, 19, 20]".getBytes(StandardCharsets.UTF_8)), + "vector3", BinaryData.fromBytes("[1, 2, 3, 4, 5]".getBytes(StandardCharsets.UTF_8)), "@search.action", + BinaryData.fromBytes("mergeOrUpload".getBytes(StandardCharsets.UTF_8)), "vector22", + BinaryData.fromBytes("[21, 22, 23, 24, 25, 26, 27, 28, 29, 30]".getBytes(StandardCharsets.UTF_8)), + "price", BinaryData.fromBytes("1".getBytes(StandardCharsets.UTF_8)), "name", + BinaryData.fromBytes("test".getBytes(StandardCharsets.UTF_8)), "description", + BinaryData.fromBytes("test1 hello".getBytes(StandardCharsets.UTF_8)), "id", + BinaryData.fromBytes("1".getBytes(StandardCharsets.UTF_8)), "vector1", + BinaryData.fromBytes("[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]" + .getBytes(StandardCharsets.UTF_8)), + "ownerId", BinaryData.fromBytes("sam".getBytes(StandardCharsets.UTF_8)), "category", + BinaryData.fromBytes("purple".getBytes(StandardCharsets.UTF_8)), "vector2", + BinaryData.fromBytes("[1, 2, 3, 4, 5]".getBytes(StandardCharsets.UTF_8)))), + new IndexAction().setAdditionalProperties(mapOf("vector1b", + BinaryData.fromBytes("[12, 13, 14, 15, 16, 17, 18, 19, 20, 21]".getBytes(StandardCharsets.UTF_8)), + "vector3", BinaryData.fromBytes("[2, 3, 4, 5, 6]".getBytes(StandardCharsets.UTF_8)), "@search.action", + BinaryData.fromBytes("mergeOrUpload".getBytes(StandardCharsets.UTF_8)), "vector22", + BinaryData.fromBytes("[22, 23, 24, 25, 26, 27, 28, 29, 30, 31]".getBytes(StandardCharsets.UTF_8)), + "price", BinaryData.fromBytes("2".getBytes(StandardCharsets.UTF_8)), "name", + BinaryData.fromBytes("test".getBytes(StandardCharsets.UTF_8)), "description", + BinaryData.fromBytes("test2 hello".getBytes(StandardCharsets.UTF_8)), "id", + BinaryData.fromBytes("2".getBytes(StandardCharsets.UTF_8)), "vector1", + BinaryData.fromBytes("[2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21]" + .getBytes(StandardCharsets.UTF_8)), + "ownerId", BinaryData.fromBytes("sam".getBytes(StandardCharsets.UTF_8)), "category", + BinaryData.fromBytes("purple".getBytes(StandardCharsets.UTF_8)), "vector2", + BinaryData.fromBytes("[2, 3, 4, 5, 6]".getBytes(StandardCharsets.UTF_8)))), + new IndexAction().setAdditionalProperties(mapOf("vector1b", + BinaryData.fromBytes("[13, 14, 15, 16, 17, 18, 19, 20, 21, 22]".getBytes(StandardCharsets.UTF_8)), + "vector3", BinaryData.fromBytes("[3, 4, 5, 6, 7]".getBytes(StandardCharsets.UTF_8)), "@search.action", + BinaryData.fromBytes("mergeOrUpload".getBytes(StandardCharsets.UTF_8)), "vector22", + BinaryData.fromBytes("[23, 24, 25, 26, 27, 28, 29, 30, 31, 32]".getBytes(StandardCharsets.UTF_8)), + "price", BinaryData.fromBytes("3".getBytes(StandardCharsets.UTF_8)), "name", + BinaryData.fromBytes("test".getBytes(StandardCharsets.UTF_8)), "description", + BinaryData.fromBytes("test3 hello".getBytes(StandardCharsets.UTF_8)), "id", + BinaryData.fromBytes("3".getBytes(StandardCharsets.UTF_8)), "vector1", + BinaryData.fromBytes("[3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22]" + .getBytes(StandardCharsets.UTF_8)), + "ownerId", BinaryData.fromBytes("ryan".getBytes(StandardCharsets.UTF_8)), "category", + BinaryData.fromBytes("purple".getBytes(StandardCharsets.UTF_8)), "vector2", + BinaryData.fromBytes("[3, 4, 5, 6, 7]".getBytes(StandardCharsets.UTF_8)))), + new IndexAction().setAdditionalProperties(mapOf("vector1b", + BinaryData.fromBytes("[14, 15, 16, 17, 18, 19, 20, 21, 22, 23]".getBytes(StandardCharsets.UTF_8)), + "vector3", BinaryData.fromBytes("[4, 5, 6, 7, 8]".getBytes(StandardCharsets.UTF_8)), "@search.action", + BinaryData.fromBytes("mergeOrUpload".getBytes(StandardCharsets.UTF_8)), "vector22", + BinaryData.fromBytes("[24, 25, 26, 27, 28, 29, 30, 31, 32, 33]".getBytes(StandardCharsets.UTF_8)), + "price", BinaryData.fromBytes("4".getBytes(StandardCharsets.UTF_8)), "name", + BinaryData.fromBytes("test".getBytes(StandardCharsets.UTF_8)), "description", + BinaryData.fromBytes("test4 hello".getBytes(StandardCharsets.UTF_8)), "id", + BinaryData.fromBytes("4".getBytes(StandardCharsets.UTF_8)), "vector1", + BinaryData.fromBytes("[4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23]" + .getBytes(StandardCharsets.UTF_8)), + "ownerId", BinaryData.fromBytes("sam".getBytes(StandardCharsets.UTF_8)), "category", + BinaryData.fromBytes("purple".getBytes(StandardCharsets.UTF_8)), "vector2", + BinaryData.fromBytes("[4, 5, 6, 7, 8]".getBytes(StandardCharsets.UTF_8)))), + new IndexAction().setAdditionalProperties(mapOf("vector1b", + BinaryData.fromBytes("[15, 16, 17, 18, 19, 20, 21, 22, 23, 24]".getBytes(StandardCharsets.UTF_8)), + "vector3", BinaryData.fromBytes("[5, 6, 7, 8, 9]".getBytes(StandardCharsets.UTF_8)), "@search.action", + BinaryData.fromBytes("mergeOrUpload".getBytes(StandardCharsets.UTF_8)), "vector22", + BinaryData.fromBytes("[25, 26, 27, 28, 29, 30, 31, 32, 33, 34]".getBytes(StandardCharsets.UTF_8)), + "price", BinaryData.fromBytes("5".getBytes(StandardCharsets.UTF_8)), "name", + BinaryData.fromBytes("test".getBytes(StandardCharsets.UTF_8)), "description", + BinaryData.fromBytes("test5 hello".getBytes(StandardCharsets.UTF_8)), "id", + BinaryData.fromBytes("5".getBytes(StandardCharsets.UTF_8)), "vector1", + BinaryData.fromBytes("[5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24]" + .getBytes(StandardCharsets.UTF_8)), + "ownerId", BinaryData.fromBytes("sam".getBytes(StandardCharsets.UTF_8)), "category", + BinaryData.fromBytes("purple".getBytes(StandardCharsets.UTF_8)), "vector2", + BinaryData.fromBytes("[5, 6, 7, 8, 9]".getBytes(StandardCharsets.UTF_8)))), + new IndexAction().setAdditionalProperties(mapOf("vector1b", + BinaryData.fromBytes("[16, 17, 18, 19, 20, 21, 22, 23, 24, 25]".getBytes(StandardCharsets.UTF_8)), + "vector3", BinaryData.fromBytes("[6, 7, 8, 9, 10]".getBytes(StandardCharsets.UTF_8)), "@search.action", + BinaryData.fromBytes("mergeOrUpload".getBytes(StandardCharsets.UTF_8)), "vector22", + BinaryData.fromBytes("[26, 27, 28, 29, 30, 31, 32, 33, 34, 35]".getBytes(StandardCharsets.UTF_8)), + "price", BinaryData.fromBytes("6".getBytes(StandardCharsets.UTF_8)), "name", + BinaryData.fromBytes("test".getBytes(StandardCharsets.UTF_8)), "description", + BinaryData.fromBytes("test6 hello".getBytes(StandardCharsets.UTF_8)), "id", + BinaryData.fromBytes("6".getBytes(StandardCharsets.UTF_8)), "vector1", + BinaryData.fromBytes("[6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25]" + .getBytes(StandardCharsets.UTF_8)), + "ownerId", BinaryData.fromBytes("ryan".getBytes(StandardCharsets.UTF_8)), "category", + BinaryData.fromBytes("purple".getBytes(StandardCharsets.UTF_8)), "vector2", + BinaryData.fromBytes("[6, 7, 8, 9, 10]".getBytes(StandardCharsets.UTF_8)))), + new IndexAction().setAdditionalProperties(mapOf("vector1b", + BinaryData.fromBytes("[17, 18, 19, 20, 21, 22, 23, 24, 25, 26]".getBytes(StandardCharsets.UTF_8)), + "vector3", BinaryData.fromBytes("[7, 8, 9, 10, 11]".getBytes(StandardCharsets.UTF_8)), "@search.action", + BinaryData.fromBytes("mergeOrUpload".getBytes(StandardCharsets.UTF_8)), "vector22", + BinaryData.fromBytes("[27, 28, 29, 30, 31, 32, 33, 34, 35, 36]".getBytes(StandardCharsets.UTF_8)), + "price", BinaryData.fromBytes("7".getBytes(StandardCharsets.UTF_8)), "name", + BinaryData.fromBytes("test".getBytes(StandardCharsets.UTF_8)), "description", + BinaryData.fromBytes("test7 hello".getBytes(StandardCharsets.UTF_8)), "id", + BinaryData.fromBytes("7".getBytes(StandardCharsets.UTF_8)), "vector1", + BinaryData.fromBytes("[7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26]" + .getBytes(StandardCharsets.UTF_8)), + "ownerId", BinaryData.fromBytes("sam".getBytes(StandardCharsets.UTF_8)), "category", + BinaryData.fromBytes("purple".getBytes(StandardCharsets.UTF_8)), "vector2", + BinaryData.fromBytes("[7, 8, 9, 10, 11]".getBytes(StandardCharsets.UTF_8)))), + new IndexAction().setAdditionalProperties(mapOf("vector1b", + BinaryData.fromBytes("[18, 19, 20, 21, 22, 23, 24, 25, 26, 27]".getBytes(StandardCharsets.UTF_8)), + "vector3", BinaryData.fromBytes("[8, 9, 10, 11, 12]".getBytes(StandardCharsets.UTF_8)), + "@search.action", BinaryData.fromBytes("mergeOrUpload".getBytes(StandardCharsets.UTF_8)), "vector22", + BinaryData.fromBytes("[28, 29, 30, 31, 32, 33, 34, 35, 36, 37]".getBytes(StandardCharsets.UTF_8)), + "price", BinaryData.fromBytes("8".getBytes(StandardCharsets.UTF_8)), "name", + BinaryData.fromBytes("test".getBytes(StandardCharsets.UTF_8)), "description", + BinaryData.fromBytes("test8 hello".getBytes(StandardCharsets.UTF_8)), "id", + BinaryData.fromBytes("8".getBytes(StandardCharsets.UTF_8)), "vector1", + BinaryData.fromBytes("[8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27]" + .getBytes(StandardCharsets.UTF_8)), + "ownerId", BinaryData.fromBytes("sam".getBytes(StandardCharsets.UTF_8)), "category", + BinaryData.fromBytes("purple".getBytes(StandardCharsets.UTF_8)), "vector2", + BinaryData.fromBytes("[8, 9, 10, 11, 12]".getBytes(StandardCharsets.UTF_8)))), + new IndexAction().setAdditionalProperties(mapOf("vector1b", + BinaryData.fromBytes("[19, 20, 21, 22, 23, 24, 25, 26, 27, 28]".getBytes(StandardCharsets.UTF_8)), + "vector3", BinaryData.fromBytes("[9, 10, 11, 12, 13]".getBytes(StandardCharsets.UTF_8)), + "@search.action", BinaryData.fromBytes("mergeOrUpload".getBytes(StandardCharsets.UTF_8)), "vector22", + BinaryData.fromBytes("[29, 30, 31, 32, 33, 34, 35, 36, 37, 38]".getBytes(StandardCharsets.UTF_8)), + "price", BinaryData.fromBytes("9".getBytes(StandardCharsets.UTF_8)), "name", + BinaryData.fromBytes("test".getBytes(StandardCharsets.UTF_8)), "description", + BinaryData.fromBytes("test9 hello".getBytes(StandardCharsets.UTF_8)), "id", + BinaryData.fromBytes("9".getBytes(StandardCharsets.UTF_8)), "vector1", + BinaryData.fromBytes("[9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28]" + .getBytes(StandardCharsets.UTF_8)), + "ownerId", BinaryData.fromBytes("ryan".getBytes(StandardCharsets.UTF_8)), "category", + BinaryData.fromBytes("purple".getBytes(StandardCharsets.UTF_8)), "vector2", + BinaryData.fromBytes("[9, 10, 11, 12, 13]".getBytes(StandardCharsets.UTF_8)))), + new IndexAction().setAdditionalProperties(mapOf("vector1b", + BinaryData.fromBytes("[20, 21, 22, 23, 24, 25, 26, 27, 28, 29]".getBytes(StandardCharsets.UTF_8)), + "vector3", BinaryData.fromBytes("[10, 11, 12, 13, 14]".getBytes(StandardCharsets.UTF_8)), + "@search.action", BinaryData.fromBytes("mergeOrUpload".getBytes(StandardCharsets.UTF_8)), "vector22", + BinaryData.fromBytes("[30, 31, 32, 33, 34, 35, 36, 37, 38, 39]".getBytes(StandardCharsets.UTF_8)), + "price", BinaryData.fromBytes("10".getBytes(StandardCharsets.UTF_8)), "name", + BinaryData.fromBytes("test".getBytes(StandardCharsets.UTF_8)), "description", + BinaryData.fromBytes("test10 hello".getBytes(StandardCharsets.UTF_8)), "id", + BinaryData.fromBytes("10".getBytes(StandardCharsets.UTF_8)), "vector1", + BinaryData.fromBytes("[10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29]" + .getBytes(StandardCharsets.UTF_8)), + "ownerId", BinaryData.fromBytes("benny".getBytes(StandardCharsets.UTF_8)), "category", + BinaryData.fromBytes("purple".getBytes(StandardCharsets.UTF_8)), "vector2", + BinaryData.fromBytes("[10, 11, 12, 13, 14]".getBytes(StandardCharsets.UTF_8)))), + new IndexAction().setAdditionalProperties(mapOf("vector1b", + BinaryData.fromBytes("[21, 22, 23, 24, 25, 26, 27, 28, 29, 30]".getBytes(StandardCharsets.UTF_8)), + "vector3", BinaryData.fromBytes("[11, 12, 13, 14, 15]".getBytes(StandardCharsets.UTF_8)), + "@search.action", BinaryData.fromBytes("mergeOrUpload".getBytes(StandardCharsets.UTF_8)), "vector22", + BinaryData.fromBytes("[31, 32, 33, 34, 35, 36, 37, 38, 39, 40]".getBytes(StandardCharsets.UTF_8)), + "price", BinaryData.fromBytes("11".getBytes(StandardCharsets.UTF_8)), "name", + BinaryData.fromBytes("test".getBytes(StandardCharsets.UTF_8)), "description", + BinaryData.fromBytes("test11 hello".getBytes(StandardCharsets.UTF_8)), "id", + BinaryData.fromBytes("11".getBytes(StandardCharsets.UTF_8)), "vector1", + BinaryData.fromBytes("[11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30]" + .getBytes(StandardCharsets.UTF_8)), + "ownerId", BinaryData.fromBytes("sam".getBytes(StandardCharsets.UTF_8)), "category", + BinaryData.fromBytes("purple".getBytes(StandardCharsets.UTF_8)), "vector2", + BinaryData.fromBytes("[11, 12, 13, 14, 15]".getBytes(StandardCharsets.UTF_8)))), + new IndexAction().setAdditionalProperties(mapOf("vector1b", + BinaryData.fromBytes("[22, 23, 24, 25, 26, 27, 28, 29, 30, 31]".getBytes(StandardCharsets.UTF_8)), + "vector3", BinaryData.fromBytes("[12, 13, 14, 15, 16]".getBytes(StandardCharsets.UTF_8)), + "@search.action", BinaryData.fromBytes("mergeOrUpload".getBytes(StandardCharsets.UTF_8)), "vector22", + BinaryData.fromBytes("[32, 33, 34, 35, 36, 37, 38, 39, 40, 41]".getBytes(StandardCharsets.UTF_8)), + "price", BinaryData.fromBytes("12".getBytes(StandardCharsets.UTF_8)), "name", + BinaryData.fromBytes("test".getBytes(StandardCharsets.UTF_8)), "description", + BinaryData.fromBytes("test12 hello".getBytes(StandardCharsets.UTF_8)), "id", + BinaryData.fromBytes("12".getBytes(StandardCharsets.UTF_8)), "vector1", + BinaryData.fromBytes("[12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31]" + .getBytes(StandardCharsets.UTF_8)), + "ownerId", BinaryData.fromBytes("ryan".getBytes(StandardCharsets.UTF_8)), "category", + BinaryData.fromBytes("purple".getBytes(StandardCharsets.UTF_8)), "vector2", + BinaryData.fromBytes("[12, 13, 14, 15, 16]".getBytes(StandardCharsets.UTF_8)))), + new IndexAction().setAdditionalProperties(mapOf("vector1b", + BinaryData.fromBytes("[23, 24, 25, 26, 27, 28, 29, 30, 31, 32]".getBytes(StandardCharsets.UTF_8)), + "vector3", BinaryData.fromBytes("[13, 14, 15, 16, 17]".getBytes(StandardCharsets.UTF_8)), + "@search.action", BinaryData.fromBytes("mergeOrUpload".getBytes(StandardCharsets.UTF_8)), "vector22", + BinaryData.fromBytes("[33, 34, 35, 36, 37, 38, 39, 40, 41, 42]".getBytes(StandardCharsets.UTF_8)), + "price", BinaryData.fromBytes("13".getBytes(StandardCharsets.UTF_8)), "name", + BinaryData.fromBytes("test".getBytes(StandardCharsets.UTF_8)), "description", + BinaryData.fromBytes("test13 hello".getBytes(StandardCharsets.UTF_8)), "id", + BinaryData.fromBytes("13".getBytes(StandardCharsets.UTF_8)), "vector1", + BinaryData.fromBytes("[13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32]" + .getBytes(StandardCharsets.UTF_8)), + "ownerId", BinaryData.fromBytes("sam".getBytes(StandardCharsets.UTF_8)), "category", + BinaryData.fromBytes("purple".getBytes(StandardCharsets.UTF_8)), "vector2", + BinaryData.fromBytes("[13, 14, 15, 16, 17]".getBytes(StandardCharsets.UTF_8)))), + new IndexAction().setAdditionalProperties(mapOf("vector1b", + BinaryData.fromBytes("[24, 25, 26, 27, 28, 29, 30, 31, 32, 33]".getBytes(StandardCharsets.UTF_8)), + "vector3", BinaryData.fromBytes("[14, 15, 16, 17, 18]".getBytes(StandardCharsets.UTF_8)), + "@search.action", BinaryData.fromBytes("mergeOrUpload".getBytes(StandardCharsets.UTF_8)), "vector22", + BinaryData.fromBytes("[34, 35, 36, 37, 38, 39, 40, 41, 42, 43]".getBytes(StandardCharsets.UTF_8)), + "price", BinaryData.fromBytes("14".getBytes(StandardCharsets.UTF_8)), "name", + BinaryData.fromBytes("test".getBytes(StandardCharsets.UTF_8)), "description", + BinaryData.fromBytes("test14 hello".getBytes(StandardCharsets.UTF_8)), "id", + BinaryData.fromBytes("14".getBytes(StandardCharsets.UTF_8)), "vector1", + BinaryData.fromBytes("[14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33]" + .getBytes(StandardCharsets.UTF_8)), + "ownerId", BinaryData.fromBytes("sam".getBytes(StandardCharsets.UTF_8)), "category", + BinaryData.fromBytes("purple".getBytes(StandardCharsets.UTF_8)), "vector2", + BinaryData.fromBytes("[14, 15, 16, 17, 18]".getBytes(StandardCharsets.UTF_8)))), + new IndexAction().setAdditionalProperties(mapOf("vector1b", + BinaryData.fromBytes("[25, 26, 27, 28, 29, 30, 31, 32, 33, 34]".getBytes(StandardCharsets.UTF_8)), + "vector3", BinaryData.fromBytes("[15, 16, 17, 18, 19]".getBytes(StandardCharsets.UTF_8)), + "@search.action", BinaryData.fromBytes("mergeOrUpload".getBytes(StandardCharsets.UTF_8)), "vector22", + BinaryData.fromBytes("[35, 36, 37, 38, 39, 40, 41, 42, 43, 44]".getBytes(StandardCharsets.UTF_8)), + "price", BinaryData.fromBytes("15".getBytes(StandardCharsets.UTF_8)), "name", + BinaryData.fromBytes("test".getBytes(StandardCharsets.UTF_8)), "description", + BinaryData.fromBytes("test15 hello".getBytes(StandardCharsets.UTF_8)), "id", + BinaryData.fromBytes("15".getBytes(StandardCharsets.UTF_8)), "vector1", + BinaryData.fromBytes("[15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34]" + .getBytes(StandardCharsets.UTF_8)), + "ownerId", BinaryData.fromBytes("ryan".getBytes(StandardCharsets.UTF_8)), "category", + BinaryData.fromBytes("purple".getBytes(StandardCharsets.UTF_8)), "vector2", + BinaryData.fromBytes("[15, 16, 17, 18, 19]".getBytes(StandardCharsets.UTF_8)))), + new IndexAction().setAdditionalProperties(mapOf("vector1b", + BinaryData.fromBytes("[26, 27, 28, 29, 30, 31, 32, 33, 34, 35]".getBytes(StandardCharsets.UTF_8)), + "vector3", BinaryData.fromBytes("[16, 17, 18, 19, 20]".getBytes(StandardCharsets.UTF_8)), + "@search.action", BinaryData.fromBytes("mergeOrUpload".getBytes(StandardCharsets.UTF_8)), "vector22", + BinaryData.fromBytes("[36, 37, 38, 39, 40, 41, 42, 43, 44, 45]".getBytes(StandardCharsets.UTF_8)), + "price", BinaryData.fromBytes("16".getBytes(StandardCharsets.UTF_8)), "name", + BinaryData.fromBytes("test".getBytes(StandardCharsets.UTF_8)), "description", + BinaryData.fromBytes("test16 hello".getBytes(StandardCharsets.UTF_8)), "id", + BinaryData.fromBytes("16".getBytes(StandardCharsets.UTF_8)), "vector1", + BinaryData.fromBytes("[16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35]" + .getBytes(StandardCharsets.UTF_8)), + "ownerId", BinaryData.fromBytes("sam".getBytes(StandardCharsets.UTF_8)), "category", + BinaryData.fromBytes("purple".getBytes(StandardCharsets.UTF_8)), "vector2", + BinaryData.fromBytes("[16, 17, 18, 19, 20]".getBytes(StandardCharsets.UTF_8)))), + new IndexAction().setAdditionalProperties(mapOf("vector1b", + BinaryData.fromBytes("[27, 28, 29, 30, 31, 32, 33, 34, 35, 36]".getBytes(StandardCharsets.UTF_8)), + "vector3", BinaryData.fromBytes("[17, 18, 19, 20, 21]".getBytes(StandardCharsets.UTF_8)), + "@search.action", BinaryData.fromBytes("mergeOrUpload".getBytes(StandardCharsets.UTF_8)), "vector22", + BinaryData.fromBytes("[37, 38, 39, 40, 41, 42, 43, 44, 45, 46]".getBytes(StandardCharsets.UTF_8)), + "price", BinaryData.fromBytes("17".getBytes(StandardCharsets.UTF_8)), "name", + BinaryData.fromBytes("test".getBytes(StandardCharsets.UTF_8)), "description", + BinaryData.fromBytes("test17 hello".getBytes(StandardCharsets.UTF_8)), "id", + BinaryData.fromBytes("17".getBytes(StandardCharsets.UTF_8)), "vector1", + BinaryData.fromBytes("[17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36]" + .getBytes(StandardCharsets.UTF_8)), + "ownerId", BinaryData.fromBytes("sam".getBytes(StandardCharsets.UTF_8)), "category", + BinaryData.fromBytes("purple".getBytes(StandardCharsets.UTF_8)), "vector2", + BinaryData.fromBytes("[17, 18, 19, 20, 21]".getBytes(StandardCharsets.UTF_8)))), + new IndexAction().setAdditionalProperties(mapOf("vector1b", + BinaryData.fromBytes("[28, 29, 30, 31, 32, 33, 34, 35, 36, 37]".getBytes(StandardCharsets.UTF_8)), + "vector3", BinaryData.fromBytes("[18, 19, 20, 21, 22]".getBytes(StandardCharsets.UTF_8)), + "@search.action", BinaryData.fromBytes("mergeOrUpload".getBytes(StandardCharsets.UTF_8)), "vector22", + BinaryData.fromBytes("[38, 39, 40, 41, 42, 43, 44, 45, 46, 47]".getBytes(StandardCharsets.UTF_8)), + "price", BinaryData.fromBytes("18".getBytes(StandardCharsets.UTF_8)), "name", + BinaryData.fromBytes("test".getBytes(StandardCharsets.UTF_8)), "description", + BinaryData.fromBytes("test18 hello".getBytes(StandardCharsets.UTF_8)), "id", + BinaryData.fromBytes("18".getBytes(StandardCharsets.UTF_8)), "vector1", + BinaryData.fromBytes("[18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37]" + .getBytes(StandardCharsets.UTF_8)), + "ownerId", BinaryData.fromBytes("ryan".getBytes(StandardCharsets.UTF_8)), "category", + BinaryData.fromBytes("purple".getBytes(StandardCharsets.UTF_8)), "vector2", + BinaryData.fromBytes("[18, 19, 20, 21, 22]".getBytes(StandardCharsets.UTF_8)))), + new IndexAction().setAdditionalProperties(mapOf("vector1b", + BinaryData.fromBytes("[29, 30, 31, 32, 33, 34, 35, 36, 37, 38]".getBytes(StandardCharsets.UTF_8)), + "vector3", BinaryData.fromBytes("[19, 20, 21, 22, 23]".getBytes(StandardCharsets.UTF_8)), + "@search.action", BinaryData.fromBytes("mergeOrUpload".getBytes(StandardCharsets.UTF_8)), "vector22", + BinaryData.fromBytes("[39, 40, 41, 42, 43, 44, 45, 46, 47, 48]".getBytes(StandardCharsets.UTF_8)), + "price", BinaryData.fromBytes("19".getBytes(StandardCharsets.UTF_8)), "name", + BinaryData.fromBytes("test".getBytes(StandardCharsets.UTF_8)), "description", + BinaryData.fromBytes("test19 hello".getBytes(StandardCharsets.UTF_8)), "id", + BinaryData.fromBytes("19".getBytes(StandardCharsets.UTF_8)), "vector1", + BinaryData.fromBytes("[19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38]" + .getBytes(StandardCharsets.UTF_8)), + "ownerId", BinaryData.fromBytes("sam".getBytes(StandardCharsets.UTF_8)), "category", + BinaryData.fromBytes("purple".getBytes(StandardCharsets.UTF_8)), "vector2", + BinaryData.fromBytes("[19, 20, 21, 22, 23]".getBytes(StandardCharsets.UTF_8)))), + new IndexAction().setAdditionalProperties(mapOf("vector1b", + BinaryData.fromBytes("[30, 31, 32, 33, 34, 35, 36, 37, 38, 39]".getBytes(StandardCharsets.UTF_8)), + "vector3", BinaryData.fromBytes("[20, 21, 22, 23, 24]".getBytes(StandardCharsets.UTF_8)), + "@search.action", BinaryData.fromBytes("mergeOrUpload".getBytes(StandardCharsets.UTF_8)), "vector22", + BinaryData.fromBytes("[40, 41, 42, 43, 44, 45, 46, 47, 48, 49]".getBytes(StandardCharsets.UTF_8)), + "price", BinaryData.fromBytes("20".getBytes(StandardCharsets.UTF_8)), "name", + BinaryData.fromBytes("test".getBytes(StandardCharsets.UTF_8)), "description", + BinaryData.fromBytes("test20 hello".getBytes(StandardCharsets.UTF_8)), "id", + BinaryData.fromBytes("20".getBytes(StandardCharsets.UTF_8)), "vector1", + BinaryData.fromBytes("[20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39]" + .getBytes(StandardCharsets.UTF_8)), + "ownerId", BinaryData.fromBytes("benny".getBytes(StandardCharsets.UTF_8)), "category", + BinaryData.fromBytes("purple".getBytes(StandardCharsets.UTF_8)), "vector2", + BinaryData.fromBytes("[20, 21, 22, 23, 24]".getBytes(StandardCharsets.UTF_8)))), + new IndexAction().setAdditionalProperties(mapOf("vector1b", + BinaryData.fromBytes("[31, 32, 33, 34, 35, 36, 37, 38, 39, 40]".getBytes(StandardCharsets.UTF_8)), + "vector3", BinaryData.fromBytes("[21, 22, 23, 24, 25]".getBytes(StandardCharsets.UTF_8)), + "@search.action", BinaryData.fromBytes("mergeOrUpload".getBytes(StandardCharsets.UTF_8)), "vector22", + BinaryData.fromBytes("[41, 42, 43, 44, 45, 46, 47, 48, 49, 50]".getBytes(StandardCharsets.UTF_8)), + "price", BinaryData.fromBytes("21".getBytes(StandardCharsets.UTF_8)), "name", + BinaryData.fromBytes("test".getBytes(StandardCharsets.UTF_8)), "description", + BinaryData.fromBytes("test21 hello".getBytes(StandardCharsets.UTF_8)), "id", + BinaryData.fromBytes("21".getBytes(StandardCharsets.UTF_8)), "vector1", + BinaryData.fromBytes("[21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40]" + .getBytes(StandardCharsets.UTF_8)), + "ownerId", BinaryData.fromBytes("ryan".getBytes(StandardCharsets.UTF_8)), "category", + BinaryData.fromBytes("purple".getBytes(StandardCharsets.UTF_8)), "vector2", + BinaryData.fromBytes("[21, 22, 23, 24, 25]".getBytes(StandardCharsets.UTF_8)))), + new IndexAction().setAdditionalProperties(mapOf("vector1b", + BinaryData.fromBytes("[32, 33, 34, 35, 36, 37, 38, 39, 40, 41]".getBytes(StandardCharsets.UTF_8)), + "vector3", BinaryData.fromBytes("[22, 23, 24, 25, 26]".getBytes(StandardCharsets.UTF_8)), + "@search.action", BinaryData.fromBytes("mergeOrUpload".getBytes(StandardCharsets.UTF_8)), "vector22", + BinaryData.fromBytes("[42, 43, 44, 45, 46, 47, 48, 49, 50, 51]".getBytes(StandardCharsets.UTF_8)), + "price", BinaryData.fromBytes("22".getBytes(StandardCharsets.UTF_8)), "name", + BinaryData.fromBytes("test".getBytes(StandardCharsets.UTF_8)), "description", + BinaryData.fromBytes("test22 hello".getBytes(StandardCharsets.UTF_8)), "id", + BinaryData.fromBytes("22".getBytes(StandardCharsets.UTF_8)), "vector1", + BinaryData.fromBytes("[22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41]" + .getBytes(StandardCharsets.UTF_8)), + "ownerId", BinaryData.fromBytes("sam".getBytes(StandardCharsets.UTF_8)), "category", + BinaryData.fromBytes("purple".getBytes(StandardCharsets.UTF_8)), "vector2", + BinaryData.fromBytes("[22, 23, 24, 25, 26]".getBytes(StandardCharsets.UTF_8)))), + new IndexAction().setAdditionalProperties(mapOf("vector1b", + BinaryData.fromBytes("[33, 34, 35, 36, 37, 38, 39, 40, 41, 42]".getBytes(StandardCharsets.UTF_8)), + "vector3", BinaryData.fromBytes("[23, 24, 25, 26, 27]".getBytes(StandardCharsets.UTF_8)), + "@search.action", BinaryData.fromBytes("mergeOrUpload".getBytes(StandardCharsets.UTF_8)), "vector22", + BinaryData.fromBytes("[43, 44, 45, 46, 47, 48, 49, 50, 51, 52]".getBytes(StandardCharsets.UTF_8)), + "price", BinaryData.fromBytes("23".getBytes(StandardCharsets.UTF_8)), "name", + BinaryData.fromBytes("test".getBytes(StandardCharsets.UTF_8)), "description", + BinaryData.fromBytes("test23 hello".getBytes(StandardCharsets.UTF_8)), "id", + BinaryData.fromBytes("23".getBytes(StandardCharsets.UTF_8)), "vector1", + BinaryData.fromBytes("[23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42]" + .getBytes(StandardCharsets.UTF_8)), + "ownerId", BinaryData.fromBytes("sam".getBytes(StandardCharsets.UTF_8)), "category", + BinaryData.fromBytes("purple".getBytes(StandardCharsets.UTF_8)), "vector2", + BinaryData.fromBytes("[23, 24, 25, 26, 27]".getBytes(StandardCharsets.UTF_8)))), + new IndexAction().setAdditionalProperties(mapOf("vector1b", + BinaryData.fromBytes("[34, 35, 36, 37, 38, 39, 40, 41, 42, 43]".getBytes(StandardCharsets.UTF_8)), + "vector3", BinaryData.fromBytes("[24, 25, 26, 27, 28]".getBytes(StandardCharsets.UTF_8)), + "@search.action", BinaryData.fromBytes("mergeOrUpload".getBytes(StandardCharsets.UTF_8)), "vector22", + BinaryData.fromBytes("[44, 45, 46, 47, 48, 49, 50, 51, 52, 53]".getBytes(StandardCharsets.UTF_8)), + "price", BinaryData.fromBytes("24".getBytes(StandardCharsets.UTF_8)), "name", + BinaryData.fromBytes("test".getBytes(StandardCharsets.UTF_8)), "description", + BinaryData.fromBytes("test24 hello".getBytes(StandardCharsets.UTF_8)), "id", + BinaryData.fromBytes("24".getBytes(StandardCharsets.UTF_8)), "vector1", + BinaryData.fromBytes("[24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43]" + .getBytes(StandardCharsets.UTF_8)), + "ownerId", BinaryData.fromBytes("ryan".getBytes(StandardCharsets.UTF_8)), "category", + BinaryData.fromBytes("purple".getBytes(StandardCharsets.UTF_8)), "vector2", + BinaryData.fromBytes("[24, 25, 26, 27, 28]".getBytes(StandardCharsets.UTF_8)))), + new IndexAction().setAdditionalProperties(mapOf("vector1b", + BinaryData.fromBytes("[35, 36, 37, 38, 39, 40, 41, 42, 43, 44]".getBytes(StandardCharsets.UTF_8)), + "vector3", BinaryData.fromBytes("[25, 26, 27, 28, 29]".getBytes(StandardCharsets.UTF_8)), + "@search.action", BinaryData.fromBytes("mergeOrUpload".getBytes(StandardCharsets.UTF_8)), "vector22", + BinaryData.fromBytes("[45, 46, 47, 48, 49, 50, 51, 52, 53, 54]".getBytes(StandardCharsets.UTF_8)), + "price", BinaryData.fromBytes("25".getBytes(StandardCharsets.UTF_8)), "name", + BinaryData.fromBytes("test".getBytes(StandardCharsets.UTF_8)), "description", + BinaryData.fromBytes("test25 hello".getBytes(StandardCharsets.UTF_8)), "id", + BinaryData.fromBytes("25".getBytes(StandardCharsets.UTF_8)), "vector1", + BinaryData.fromBytes("[25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44]" + .getBytes(StandardCharsets.UTF_8)), + "ownerId", BinaryData.fromBytes("sam".getBytes(StandardCharsets.UTF_8)), "category", + BinaryData.fromBytes("pink".getBytes(StandardCharsets.UTF_8)), "vector2", + BinaryData.fromBytes("[25, 26, 27, 28, 29]".getBytes(StandardCharsets.UTF_8)))), + new IndexAction().setAdditionalProperties(mapOf("vector1b", + BinaryData.fromBytes("[36, 37, 38, 39, 40, 41, 42, 43, 44, 45]".getBytes(StandardCharsets.UTF_8)), + "vector3", BinaryData.fromBytes("[26, 27, 28, 29, 30]".getBytes(StandardCharsets.UTF_8)), + "@search.action", BinaryData.fromBytes("mergeOrUpload".getBytes(StandardCharsets.UTF_8)), "vector22", + BinaryData.fromBytes("[46, 47, 48, 49, 50, 51, 52, 53, 54, 55]".getBytes(StandardCharsets.UTF_8)), + "price", BinaryData.fromBytes("26".getBytes(StandardCharsets.UTF_8)), "name", + BinaryData.fromBytes("test".getBytes(StandardCharsets.UTF_8)), "description", + BinaryData.fromBytes("test26 hello".getBytes(StandardCharsets.UTF_8)), "id", + BinaryData.fromBytes("26".getBytes(StandardCharsets.UTF_8)), "vector1", + BinaryData.fromBytes("[26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45]" + .getBytes(StandardCharsets.UTF_8)), + "ownerId", BinaryData.fromBytes("sam".getBytes(StandardCharsets.UTF_8)), "category", + BinaryData.fromBytes("pink".getBytes(StandardCharsets.UTF_8)), "vector2", + BinaryData.fromBytes("[26, 27, 28, 29, 30]".getBytes(StandardCharsets.UTF_8)))), + new IndexAction().setAdditionalProperties(mapOf("vector1b", + BinaryData.fromBytes("[37, 38, 39, 40, 41, 42, 43, 44, 45, 46]".getBytes(StandardCharsets.UTF_8)), + "vector3", BinaryData.fromBytes("[27, 28, 29, 30, 31]".getBytes(StandardCharsets.UTF_8)), + "@search.action", BinaryData.fromBytes("mergeOrUpload".getBytes(StandardCharsets.UTF_8)), "vector22", + BinaryData.fromBytes("[47, 48, 49, 50, 51, 52, 53, 54, 55, 56]".getBytes(StandardCharsets.UTF_8)), + "price", BinaryData.fromBytes("27".getBytes(StandardCharsets.UTF_8)), "name", + BinaryData.fromBytes("test".getBytes(StandardCharsets.UTF_8)), "description", + BinaryData.fromBytes("test27 hello".getBytes(StandardCharsets.UTF_8)), "id", + BinaryData.fromBytes("27".getBytes(StandardCharsets.UTF_8)), "vector1", + BinaryData.fromBytes("[27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46]" + .getBytes(StandardCharsets.UTF_8)), + "ownerId", BinaryData.fromBytes("ryan".getBytes(StandardCharsets.UTF_8)), "category", + BinaryData.fromBytes("pink".getBytes(StandardCharsets.UTF_8)), "vector2", + BinaryData.fromBytes("[27, 28, 29, 30, 31]".getBytes(StandardCharsets.UTF_8)))), + new IndexAction().setAdditionalProperties(mapOf("vector1b", + BinaryData.fromBytes("[38, 39, 40, 41, 42, 43, 44, 45, 46, 47]".getBytes(StandardCharsets.UTF_8)), + "vector3", BinaryData.fromBytes("[28, 29, 30, 31, 32]".getBytes(StandardCharsets.UTF_8)), + "@search.action", BinaryData.fromBytes("mergeOrUpload".getBytes(StandardCharsets.UTF_8)), "vector22", + BinaryData.fromBytes("[48, 49, 50, 51, 52, 53, 54, 55, 56, 57]".getBytes(StandardCharsets.UTF_8)), + "price", BinaryData.fromBytes("28".getBytes(StandardCharsets.UTF_8)), "name", + BinaryData.fromBytes("test".getBytes(StandardCharsets.UTF_8)), "description", + BinaryData.fromBytes("test28 hello".getBytes(StandardCharsets.UTF_8)), "id", + BinaryData.fromBytes("28".getBytes(StandardCharsets.UTF_8)), "vector1", + BinaryData.fromBytes("[28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47]" + .getBytes(StandardCharsets.UTF_8)), + "ownerId", BinaryData.fromBytes("sam".getBytes(StandardCharsets.UTF_8)), "category", + BinaryData.fromBytes("pink".getBytes(StandardCharsets.UTF_8)), "vector2", + BinaryData.fromBytes("[28, 29, 30, 31, 32]".getBytes(StandardCharsets.UTF_8)))), + new IndexAction().setAdditionalProperties(mapOf("vector1b", + BinaryData.fromBytes("[39, 40, 41, 42, 43, 44, 45, 46, 47, 48]".getBytes(StandardCharsets.UTF_8)), + "vector3", BinaryData.fromBytes("[29, 30, 31, 32, 33]".getBytes(StandardCharsets.UTF_8)), + "@search.action", BinaryData.fromBytes("mergeOrUpload".getBytes(StandardCharsets.UTF_8)), "vector22", + BinaryData.fromBytes("[49, 50, 51, 52, 53, 54, 55, 56, 57, 58]".getBytes(StandardCharsets.UTF_8)), + "price", BinaryData.fromBytes("29".getBytes(StandardCharsets.UTF_8)), "name", + BinaryData.fromBytes("test".getBytes(StandardCharsets.UTF_8)), "description", + BinaryData.fromBytes("test29 hello".getBytes(StandardCharsets.UTF_8)), "id", + BinaryData.fromBytes("29".getBytes(StandardCharsets.UTF_8)), "vector1", + BinaryData.fromBytes("[29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48]" + .getBytes(StandardCharsets.UTF_8)), + "ownerId", BinaryData.fromBytes("sam".getBytes(StandardCharsets.UTF_8)), "category", + BinaryData.fromBytes("pink".getBytes(StandardCharsets.UTF_8)), "vector2", + BinaryData.fromBytes("[29, 30, 31, 32, 33]".getBytes(StandardCharsets.UTF_8)))), + new IndexAction().setAdditionalProperties(mapOf("vector1b", + BinaryData.fromBytes("[40, 41, 42, 43, 44, 45, 46, 47, 48, 49]".getBytes(StandardCharsets.UTF_8)), + "vector3", BinaryData.fromBytes("[30, 31, 32, 33, 34]".getBytes(StandardCharsets.UTF_8)), + "@search.action", BinaryData.fromBytes("mergeOrUpload".getBytes(StandardCharsets.UTF_8)), "vector22", + BinaryData.fromBytes("[50, 51, 52, 53, 54, 55, 56, 57, 58, 59]".getBytes(StandardCharsets.UTF_8)), + "price", BinaryData.fromBytes("30".getBytes(StandardCharsets.UTF_8)), "name", + BinaryData.fromBytes("test".getBytes(StandardCharsets.UTF_8)), "description", + BinaryData.fromBytes("test30 hello".getBytes(StandardCharsets.UTF_8)), "id", + BinaryData.fromBytes("30".getBytes(StandardCharsets.UTF_8)), "vector1", + BinaryData.fromBytes("[30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49]" + .getBytes(StandardCharsets.UTF_8)), + "ownerId", BinaryData.fromBytes("benny".getBytes(StandardCharsets.UTF_8)), "category", + BinaryData.fromBytes("pink".getBytes(StandardCharsets.UTF_8)), "vector2", + BinaryData.fromBytes("[30, 31, 32, 33, 34]".getBytes(StandardCharsets.UTF_8)))), + new IndexAction().setAdditionalProperties(mapOf("vector1b", + BinaryData.fromBytes("[41, 42, 43, 44, 45, 46, 47, 48, 49, 50]".getBytes(StandardCharsets.UTF_8)), + "vector3", BinaryData.fromBytes("[31, 32, 33, 34, 35]".getBytes(StandardCharsets.UTF_8)), + "@search.action", BinaryData.fromBytes("mergeOrUpload".getBytes(StandardCharsets.UTF_8)), "vector22", + BinaryData.fromBytes("[51, 52, 53, 54, 55, 56, 57, 58, 59, 60]".getBytes(StandardCharsets.UTF_8)), + "price", BinaryData.fromBytes("31".getBytes(StandardCharsets.UTF_8)), "name", + BinaryData.fromBytes("test".getBytes(StandardCharsets.UTF_8)), "description", + BinaryData.fromBytes("test31 hello".getBytes(StandardCharsets.UTF_8)), "id", + BinaryData.fromBytes("31".getBytes(StandardCharsets.UTF_8)), "vector1", + BinaryData.fromBytes("[31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50]" + .getBytes(StandardCharsets.UTF_8)), + "ownerId", BinaryData.fromBytes("sam".getBytes(StandardCharsets.UTF_8)), "category", + BinaryData.fromBytes("pink".getBytes(StandardCharsets.UTF_8)), "vector2", + BinaryData.fromBytes("[31, 32, 33, 34, 35]".getBytes(StandardCharsets.UTF_8)))), + new IndexAction().setAdditionalProperties(mapOf("vector1b", + BinaryData.fromBytes("[42, 43, 44, 45, 46, 47, 48, 49, 50, 51]".getBytes(StandardCharsets.UTF_8)), + "vector3", BinaryData.fromBytes("[32, 33, 34, 35, 36]".getBytes(StandardCharsets.UTF_8)), + "@search.action", BinaryData.fromBytes("mergeOrUpload".getBytes(StandardCharsets.UTF_8)), "vector22", + BinaryData.fromBytes("[52, 53, 54, 55, 56, 57, 58, 59, 60, 61]".getBytes(StandardCharsets.UTF_8)), + "price", BinaryData.fromBytes("32".getBytes(StandardCharsets.UTF_8)), "name", + BinaryData.fromBytes("test".getBytes(StandardCharsets.UTF_8)), "description", + BinaryData.fromBytes("test32 hello".getBytes(StandardCharsets.UTF_8)), "id", + BinaryData.fromBytes("32".getBytes(StandardCharsets.UTF_8)), "vector1", + BinaryData.fromBytes("[32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51]" + .getBytes(StandardCharsets.UTF_8)), + "ownerId", BinaryData.fromBytes("sam".getBytes(StandardCharsets.UTF_8)), "category", + BinaryData.fromBytes("pink".getBytes(StandardCharsets.UTF_8)), "vector2", + BinaryData.fromBytes("[32, 33, 34, 35, 36]".getBytes(StandardCharsets.UTF_8)))), + new IndexAction().setAdditionalProperties(mapOf("vector1b", + BinaryData.fromBytes("[43, 44, 45, 46, 47, 48, 49, 50, 51, 52]".getBytes(StandardCharsets.UTF_8)), + "vector3", BinaryData.fromBytes("[33, 34, 35, 36, 37]".getBytes(StandardCharsets.UTF_8)), + "@search.action", BinaryData.fromBytes("mergeOrUpload".getBytes(StandardCharsets.UTF_8)), "vector22", + BinaryData.fromBytes("[53, 54, 55, 56, 57, 58, 59, 60, 61, 62]".getBytes(StandardCharsets.UTF_8)), + "price", BinaryData.fromBytes("33".getBytes(StandardCharsets.UTF_8)), "name", + BinaryData.fromBytes("test".getBytes(StandardCharsets.UTF_8)), "description", + BinaryData.fromBytes("test33 hello".getBytes(StandardCharsets.UTF_8)), "id", + BinaryData.fromBytes("33".getBytes(StandardCharsets.UTF_8)), "vector1", + BinaryData.fromBytes("[33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52]" + .getBytes(StandardCharsets.UTF_8)), + "ownerId", BinaryData.fromBytes("ryan".getBytes(StandardCharsets.UTF_8)), "category", + BinaryData.fromBytes("pink".getBytes(StandardCharsets.UTF_8)), "vector2", + BinaryData.fromBytes("[33, 34, 35, 36, 37]".getBytes(StandardCharsets.UTF_8)))), + new IndexAction().setAdditionalProperties(mapOf("vector1b", + BinaryData.fromBytes("[44, 45, 46, 47, 48, 49, 50, 51, 52, 53]".getBytes(StandardCharsets.UTF_8)), + "vector3", BinaryData.fromBytes("[34, 35, 36, 37, 38]".getBytes(StandardCharsets.UTF_8)), + "@search.action", BinaryData.fromBytes("mergeOrUpload".getBytes(StandardCharsets.UTF_8)), "vector22", + BinaryData.fromBytes("[54, 55, 56, 57, 58, 59, 60, 61, 62, 63]".getBytes(StandardCharsets.UTF_8)), + "price", BinaryData.fromBytes("34".getBytes(StandardCharsets.UTF_8)), "name", + BinaryData.fromBytes("test".getBytes(StandardCharsets.UTF_8)), "description", + BinaryData.fromBytes("test34 hello".getBytes(StandardCharsets.UTF_8)), "id", + BinaryData.fromBytes("34".getBytes(StandardCharsets.UTF_8)), "vector1", + BinaryData.fromBytes("[34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53]" + .getBytes(StandardCharsets.UTF_8)), + "ownerId", BinaryData.fromBytes("sam".getBytes(StandardCharsets.UTF_8)), "category", + BinaryData.fromBytes("pink".getBytes(StandardCharsets.UTF_8)), "vector2", + BinaryData.fromBytes("[34, 35, 36, 37, 38]".getBytes(StandardCharsets.UTF_8)))), + new IndexAction().setAdditionalProperties(mapOf("vector1b", + BinaryData.fromBytes("[45, 46, 47, 48, 49, 50, 51, 52, 53, 54]".getBytes(StandardCharsets.UTF_8)), + "vector3", BinaryData.fromBytes("[35, 36, 37, 38, 39]".getBytes(StandardCharsets.UTF_8)), + "@search.action", BinaryData.fromBytes("mergeOrUpload".getBytes(StandardCharsets.UTF_8)), "vector22", + BinaryData.fromBytes("[55, 56, 57, 58, 59, 60, 61, 62, 63, 64]".getBytes(StandardCharsets.UTF_8)), + "price", BinaryData.fromBytes("35".getBytes(StandardCharsets.UTF_8)), "name", + BinaryData.fromBytes("test".getBytes(StandardCharsets.UTF_8)), "description", + BinaryData.fromBytes("test35 hello".getBytes(StandardCharsets.UTF_8)), "id", + BinaryData.fromBytes("35".getBytes(StandardCharsets.UTF_8)), "vector1", + BinaryData.fromBytes("[35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54]" + .getBytes(StandardCharsets.UTF_8)), + "ownerId", BinaryData.fromBytes("sam".getBytes(StandardCharsets.UTF_8)), "category", + BinaryData.fromBytes("pink".getBytes(StandardCharsets.UTF_8)), "vector2", + BinaryData.fromBytes("[35, 36, 37, 38, 39]".getBytes(StandardCharsets.UTF_8)))), + new IndexAction().setAdditionalProperties(mapOf("vector1b", + BinaryData.fromBytes("[46, 47, 48, 49, 50, 51, 52, 53, 54, 55]".getBytes(StandardCharsets.UTF_8)), + "vector3", BinaryData.fromBytes("[36, 37, 38, 39, 40]".getBytes(StandardCharsets.UTF_8)), + "@search.action", BinaryData.fromBytes("mergeOrUpload".getBytes(StandardCharsets.UTF_8)), "vector22", + BinaryData.fromBytes("[56, 57, 58, 59, 60, 61, 62, 63, 64, 65]".getBytes(StandardCharsets.UTF_8)), + "price", BinaryData.fromBytes("36".getBytes(StandardCharsets.UTF_8)), "name", + BinaryData.fromBytes("test".getBytes(StandardCharsets.UTF_8)), "description", + BinaryData.fromBytes("test36 hello".getBytes(StandardCharsets.UTF_8)), "id", + BinaryData.fromBytes("36".getBytes(StandardCharsets.UTF_8)), "vector1", + BinaryData.fromBytes("[36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55]" + .getBytes(StandardCharsets.UTF_8)), + "ownerId", BinaryData.fromBytes("ryan".getBytes(StandardCharsets.UTF_8)), "category", + BinaryData.fromBytes("pink".getBytes(StandardCharsets.UTF_8)), "vector2", + BinaryData.fromBytes("[36, 37, 38, 39, 40]".getBytes(StandardCharsets.UTF_8)))), + new IndexAction().setAdditionalProperties(mapOf("vector1b", + BinaryData.fromBytes("[47, 48, 49, 50, 51, 52, 53, 54, 55, 56]".getBytes(StandardCharsets.UTF_8)), + "vector3", BinaryData.fromBytes("[37, 38, 39, 40, 41]".getBytes(StandardCharsets.UTF_8)), + "@search.action", BinaryData.fromBytes("mergeOrUpload".getBytes(StandardCharsets.UTF_8)), "vector22", + BinaryData.fromBytes("[57, 58, 59, 60, 61, 62, 63, 64, 65, 66]".getBytes(StandardCharsets.UTF_8)), + "price", BinaryData.fromBytes("37".getBytes(StandardCharsets.UTF_8)), "name", + BinaryData.fromBytes("test".getBytes(StandardCharsets.UTF_8)), "description", + BinaryData.fromBytes("test37 hello".getBytes(StandardCharsets.UTF_8)), "id", + BinaryData.fromBytes("37".getBytes(StandardCharsets.UTF_8)), "vector1", + BinaryData.fromBytes("[37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56]" + .getBytes(StandardCharsets.UTF_8)), + "ownerId", BinaryData.fromBytes("sam".getBytes(StandardCharsets.UTF_8)), "category", + BinaryData.fromBytes("pink".getBytes(StandardCharsets.UTF_8)), "vector2", + BinaryData.fromBytes("[37, 38, 39, 40, 41]".getBytes(StandardCharsets.UTF_8)))), + new IndexAction().setAdditionalProperties(mapOf("vector1b", + BinaryData.fromBytes("[48, 49, 50, 51, 52, 53, 54, 55, 56, 57]".getBytes(StandardCharsets.UTF_8)), + "vector3", BinaryData.fromBytes("[38, 39, 40, 41, 42]".getBytes(StandardCharsets.UTF_8)), + "@search.action", BinaryData.fromBytes("mergeOrUpload".getBytes(StandardCharsets.UTF_8)), "vector22", + BinaryData.fromBytes("[58, 59, 60, 61, 62, 63, 64, 65, 66, 67]".getBytes(StandardCharsets.UTF_8)), + "price", BinaryData.fromBytes("38".getBytes(StandardCharsets.UTF_8)), "name", + BinaryData.fromBytes("test".getBytes(StandardCharsets.UTF_8)), "description", + BinaryData.fromBytes("test38 hello".getBytes(StandardCharsets.UTF_8)), "id", + BinaryData.fromBytes("38".getBytes(StandardCharsets.UTF_8)), "vector1", + BinaryData.fromBytes("[38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57]" + .getBytes(StandardCharsets.UTF_8)), + "ownerId", BinaryData.fromBytes("sam".getBytes(StandardCharsets.UTF_8)), "category", + BinaryData.fromBytes("pink".getBytes(StandardCharsets.UTF_8)), "vector2", + BinaryData.fromBytes("[38, 39, 40, 41, 42]".getBytes(StandardCharsets.UTF_8)))), + new IndexAction().setAdditionalProperties(mapOf("vector1b", + BinaryData.fromBytes("[49, 50, 51, 52, 53, 54, 55, 56, 57, 58]".getBytes(StandardCharsets.UTF_8)), + "vector3", BinaryData.fromBytes("[39, 40, 41, 42, 43]".getBytes(StandardCharsets.UTF_8)), + "@search.action", BinaryData.fromBytes("mergeOrUpload".getBytes(StandardCharsets.UTF_8)), "vector22", + BinaryData.fromBytes("[59, 60, 61, 62, 63, 64, 65, 66, 67, 68]".getBytes(StandardCharsets.UTF_8)), + "price", BinaryData.fromBytes("39".getBytes(StandardCharsets.UTF_8)), "name", + BinaryData.fromBytes("test".getBytes(StandardCharsets.UTF_8)), "description", + BinaryData.fromBytes("test39 hello".getBytes(StandardCharsets.UTF_8)), "id", + BinaryData.fromBytes("39".getBytes(StandardCharsets.UTF_8)), "vector1", + BinaryData.fromBytes("[39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58]" + .getBytes(StandardCharsets.UTF_8)), + "ownerId", BinaryData.fromBytes("ryan".getBytes(StandardCharsets.UTF_8)), "category", + BinaryData.fromBytes("pink".getBytes(StandardCharsets.UTF_8)), "vector2", + BinaryData.fromBytes("[39, 40, 41, 42, 43]".getBytes(StandardCharsets.UTF_8)))), + new IndexAction().setAdditionalProperties(mapOf("vector1b", + BinaryData.fromBytes("[50, 51, 52, 53, 54, 55, 56, 57, 58, 59]".getBytes(StandardCharsets.UTF_8)), + "vector3", BinaryData.fromBytes("[40, 41, 42, 43, 44]".getBytes(StandardCharsets.UTF_8)), + "@search.action", BinaryData.fromBytes("mergeOrUpload".getBytes(StandardCharsets.UTF_8)), "vector22", + BinaryData.fromBytes("[60, 61, 62, 63, 64, 65, 66, 67, 68, 69]".getBytes(StandardCharsets.UTF_8)), + "price", BinaryData.fromBytes("40".getBytes(StandardCharsets.UTF_8)), "name", + BinaryData.fromBytes("test".getBytes(StandardCharsets.UTF_8)), "description", + BinaryData.fromBytes("test40 hello".getBytes(StandardCharsets.UTF_8)), "id", + BinaryData.fromBytes("40".getBytes(StandardCharsets.UTF_8)), "vector1", + BinaryData.fromBytes("[40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59]" + .getBytes(StandardCharsets.UTF_8)), + "ownerId", BinaryData.fromBytes("benny".getBytes(StandardCharsets.UTF_8)), "category", + BinaryData.fromBytes("green".getBytes(StandardCharsets.UTF_8)), "vector2", + BinaryData.fromBytes("[40, 41, 42, 43, 44]".getBytes(StandardCharsets.UTF_8)))), + new IndexAction().setAdditionalProperties(mapOf("vector1b", + BinaryData.fromBytes("[51, 52, 53, 54, 55, 56, 57, 58, 59, 60]".getBytes(StandardCharsets.UTF_8)), + "vector3", BinaryData.fromBytes("[41, 42, 43, 44, 45]".getBytes(StandardCharsets.UTF_8)), + "@search.action", BinaryData.fromBytes("mergeOrUpload".getBytes(StandardCharsets.UTF_8)), "vector22", + BinaryData.fromBytes("[61, 62, 63, 64, 65, 66, 67, 68, 69, 70]".getBytes(StandardCharsets.UTF_8)), + "price", BinaryData.fromBytes("41".getBytes(StandardCharsets.UTF_8)), "name", + BinaryData.fromBytes("test".getBytes(StandardCharsets.UTF_8)), "description", + BinaryData.fromBytes("test41 hello".getBytes(StandardCharsets.UTF_8)), "id", + BinaryData.fromBytes("41".getBytes(StandardCharsets.UTF_8)), "vector1", + BinaryData.fromBytes("[41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60]" + .getBytes(StandardCharsets.UTF_8)), + "ownerId", BinaryData.fromBytes("sam".getBytes(StandardCharsets.UTF_8)), "category", + BinaryData.fromBytes("green".getBytes(StandardCharsets.UTF_8)), "vector2", + BinaryData.fromBytes("[41, 42, 43, 44, 45]".getBytes(StandardCharsets.UTF_8)))), + new IndexAction().setAdditionalProperties(mapOf("vector1b", + BinaryData.fromBytes("[52, 53, 54, 55, 56, 57, 58, 59, 60, 61]".getBytes(StandardCharsets.UTF_8)), + "vector3", BinaryData.fromBytes("[42, 43, 44, 45, 46]".getBytes(StandardCharsets.UTF_8)), + "@search.action", BinaryData.fromBytes("mergeOrUpload".getBytes(StandardCharsets.UTF_8)), "vector22", + BinaryData.fromBytes("[62, 63, 64, 65, 66, 67, 68, 69, 70, 71]".getBytes(StandardCharsets.UTF_8)), + "price", BinaryData.fromBytes("42".getBytes(StandardCharsets.UTF_8)), "name", + BinaryData.fromBytes("test".getBytes(StandardCharsets.UTF_8)), "description", + BinaryData.fromBytes("test42 hello".getBytes(StandardCharsets.UTF_8)), "id", + BinaryData.fromBytes("42".getBytes(StandardCharsets.UTF_8)), "vector1", + BinaryData.fromBytes("[42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61]" + .getBytes(StandardCharsets.UTF_8)), + "ownerId", BinaryData.fromBytes("ryan".getBytes(StandardCharsets.UTF_8)), "category", + BinaryData.fromBytes("green".getBytes(StandardCharsets.UTF_8)), "vector2", + BinaryData.fromBytes("[42, 43, 44, 45, 46]".getBytes(StandardCharsets.UTF_8)))), + new IndexAction().setAdditionalProperties(mapOf("vector1b", + BinaryData.fromBytes("[53, 54, 55, 56, 57, 58, 59, 60, 61, 62]".getBytes(StandardCharsets.UTF_8)), + "vector3", BinaryData.fromBytes("[43, 44, 45, 46, 47]".getBytes(StandardCharsets.UTF_8)), + "@search.action", BinaryData.fromBytes("mergeOrUpload".getBytes(StandardCharsets.UTF_8)), "vector22", + BinaryData.fromBytes("[63, 64, 65, 66, 67, 68, 69, 70, 71, 72]".getBytes(StandardCharsets.UTF_8)), + "price", BinaryData.fromBytes("43".getBytes(StandardCharsets.UTF_8)), "name", + BinaryData.fromBytes("test".getBytes(StandardCharsets.UTF_8)), "description", + BinaryData.fromBytes("test43 hello".getBytes(StandardCharsets.UTF_8)), "id", + BinaryData.fromBytes("43".getBytes(StandardCharsets.UTF_8)), "vector1", + BinaryData.fromBytes("[43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62]" + .getBytes(StandardCharsets.UTF_8)), + "ownerId", BinaryData.fromBytes("sam".getBytes(StandardCharsets.UTF_8)), "category", + BinaryData.fromBytes("green".getBytes(StandardCharsets.UTF_8)), "vector2", + BinaryData.fromBytes("[43, 44, 45, 46, 47]".getBytes(StandardCharsets.UTF_8)))), + new IndexAction().setAdditionalProperties(mapOf("vector1b", + BinaryData.fromBytes("[54, 55, 56, 57, 58, 59, 60, 61, 62, 63]".getBytes(StandardCharsets.UTF_8)), + "vector3", BinaryData.fromBytes("[44, 45, 46, 47, 48]".getBytes(StandardCharsets.UTF_8)), + "@search.action", BinaryData.fromBytes("mergeOrUpload".getBytes(StandardCharsets.UTF_8)), "vector22", + BinaryData.fromBytes("[64, 65, 66, 67, 68, 69, 70, 71, 72, 73]".getBytes(StandardCharsets.UTF_8)), + "price", BinaryData.fromBytes("44".getBytes(StandardCharsets.UTF_8)), "name", + BinaryData.fromBytes("test".getBytes(StandardCharsets.UTF_8)), "description", + BinaryData.fromBytes("test44 hello".getBytes(StandardCharsets.UTF_8)), "id", + BinaryData.fromBytes("44".getBytes(StandardCharsets.UTF_8)), "vector1", + BinaryData.fromBytes("[44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63]" + .getBytes(StandardCharsets.UTF_8)), + "ownerId", BinaryData.fromBytes("sam".getBytes(StandardCharsets.UTF_8)), "category", + BinaryData.fromBytes("green".getBytes(StandardCharsets.UTF_8)), "vector2", + BinaryData.fromBytes("[44, 45, 46, 47, 48]".getBytes(StandardCharsets.UTF_8)))), + new IndexAction().setAdditionalProperties(mapOf("vector1b", + BinaryData.fromBytes("[55, 56, 57, 58, 59, 60, 61, 62, 63, 64]".getBytes(StandardCharsets.UTF_8)), + "vector3", BinaryData.fromBytes("[45, 46, 47, 48, 49]".getBytes(StandardCharsets.UTF_8)), + "@search.action", BinaryData.fromBytes("mergeOrUpload".getBytes(StandardCharsets.UTF_8)), "vector22", + BinaryData.fromBytes("[65, 66, 67, 68, 69, 70, 71, 72, 73, 74]".getBytes(StandardCharsets.UTF_8)), + "price", BinaryData.fromBytes("45".getBytes(StandardCharsets.UTF_8)), "name", + BinaryData.fromBytes("test".getBytes(StandardCharsets.UTF_8)), "description", + BinaryData.fromBytes("test45 hello".getBytes(StandardCharsets.UTF_8)), "id", + BinaryData.fromBytes("45".getBytes(StandardCharsets.UTF_8)), "vector1", + BinaryData.fromBytes("[45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64]" + .getBytes(StandardCharsets.UTF_8)), + "ownerId", BinaryData.fromBytes("ryan".getBytes(StandardCharsets.UTF_8)), "category", + BinaryData.fromBytes("orange".getBytes(StandardCharsets.UTF_8)), "vector2", + BinaryData.fromBytes("[45, 46, 47, 48, 49]".getBytes(StandardCharsets.UTF_8)))), + new IndexAction().setAdditionalProperties(mapOf("vector1b", + BinaryData.fromBytes("[56, 57, 58, 59, 60, 61, 62, 63, 64, 65]".getBytes(StandardCharsets.UTF_8)), + "vector3", BinaryData.fromBytes("[46, 47, 48, 49, 50]".getBytes(StandardCharsets.UTF_8)), + "@search.action", BinaryData.fromBytes("mergeOrUpload".getBytes(StandardCharsets.UTF_8)), "vector22", + BinaryData.fromBytes("[66, 67, 68, 69, 70, 71, 72, 73, 74, 75]".getBytes(StandardCharsets.UTF_8)), + "price", BinaryData.fromBytes("46".getBytes(StandardCharsets.UTF_8)), "name", + BinaryData.fromBytes("test".getBytes(StandardCharsets.UTF_8)), "description", + BinaryData.fromBytes("test46 hello".getBytes(StandardCharsets.UTF_8)), "id", + BinaryData.fromBytes("46".getBytes(StandardCharsets.UTF_8)), "vector1", + BinaryData.fromBytes("[46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65]" + .getBytes(StandardCharsets.UTF_8)), + "ownerId", BinaryData.fromBytes("sam".getBytes(StandardCharsets.UTF_8)), "category", + BinaryData.fromBytes("orange".getBytes(StandardCharsets.UTF_8)), "vector2", + BinaryData.fromBytes("[46, 47, 48, 49, 50]".getBytes(StandardCharsets.UTF_8)))), + new IndexAction().setAdditionalProperties(mapOf("vector1b", + BinaryData.fromBytes("[57, 58, 59, 60, 61, 62, 63, 64, 65, 66]".getBytes(StandardCharsets.UTF_8)), + "vector3", BinaryData.fromBytes("[47, 48, 49, 50, 51]".getBytes(StandardCharsets.UTF_8)), + "@search.action", BinaryData.fromBytes("mergeOrUpload".getBytes(StandardCharsets.UTF_8)), "vector22", + BinaryData.fromBytes("[67, 68, 69, 70, 71, 72, 73, 74, 75, 76]".getBytes(StandardCharsets.UTF_8)), + "price", BinaryData.fromBytes("47".getBytes(StandardCharsets.UTF_8)), "name", + BinaryData.fromBytes("test".getBytes(StandardCharsets.UTF_8)), "description", + BinaryData.fromBytes("test47 hello".getBytes(StandardCharsets.UTF_8)), "id", + BinaryData.fromBytes("47".getBytes(StandardCharsets.UTF_8)), "vector1", + BinaryData.fromBytes("[47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66]" + .getBytes(StandardCharsets.UTF_8)), + "ownerId", BinaryData.fromBytes("sam".getBytes(StandardCharsets.UTF_8)), "category", + BinaryData.fromBytes("orange".getBytes(StandardCharsets.UTF_8)), "vector2", + BinaryData.fromBytes("[47, 48, 49, 50, 51]".getBytes(StandardCharsets.UTF_8)))), + new IndexAction().setAdditionalProperties( + mapOf("@search.action", BinaryData.fromBytes("mergeOrUpload".getBytes(StandardCharsets.UTF_8)), "name", + BinaryData.fromBytes("test".getBytes(StandardCharsets.UTF_8)), "description", + BinaryData.fromBytes("no vector".getBytes(StandardCharsets.UTF_8)), "id", + BinaryData.fromBytes("no-vectors".getBytes(StandardCharsets.UTF_8)), "ownerId", + BinaryData.fromBytes("sam".getBytes(StandardCharsets.UTF_8)), "category", + BinaryData.fromBytes("purple".getBytes(StandardCharsets.UTF_8)))), + new IndexAction().setAdditionalProperties( + mapOf("@search.action", BinaryData.fromBytes("mergeOrUpload".getBytes(StandardCharsets.UTF_8)), "name", + BinaryData.fromBytes("test".getBytes(StandardCharsets.UTF_8)), "description", + BinaryData.fromBytes("no vector".getBytes(StandardCharsets.UTF_8)), "id", + BinaryData.fromBytes("empty-vectors".getBytes(StandardCharsets.UTF_8)), "ownerId", + BinaryData.fromBytes("sam".getBytes(StandardCharsets.UTF_8)), "category", + BinaryData.fromBytes("purple".getBytes(StandardCharsets.UTF_8))))))); + // END:com.azure.search.documents.generated.documentsindex.searchindexindexdocuments + } + + // Use "Map.of" if available + @SuppressWarnings("unchecked") + private static Map mapOf(Object... inputs) { + Map map = new HashMap<>(); + for (int i = 0; i < inputs.length; i += 2) { + String key = (String) inputs[i]; + T value = (T) inputs[i + 1]; + map.put(key, value); + } + return map; + } +} diff --git a/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/generated/SearchIndexSearchDocumentsGet.java b/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/generated/SearchIndexSearchDocumentsGet.java new file mode 100644 index 000000000000..065754ebcdf4 --- /dev/null +++ b/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/generated/SearchIndexSearchDocumentsGet.java @@ -0,0 +1,31 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.search.documents.generated; + +import com.azure.identity.DefaultAzureCredentialBuilder; +import com.azure.search.documents.DocumentsClient; +import com.azure.search.documents.SearchClientBuilder; +import com.azure.search.documents.models.QueryType; +import com.azure.search.documents.models.ScoringStatistics; +import com.azure.search.documents.models.SearchDocumentsResult; +import com.azure.search.documents.models.SearchMode; +import java.util.Arrays; + +public class SearchIndexSearchDocumentsGet { + public static void main(String[] args) { + DocumentsClient documentsClient + = new SearchClientBuilder().credential(new DefaultAzureCredentialBuilder().build()) + .endpoint("https://myservice.search.windows.net") + .buildDocumentsClient(); + // BEGIN:com.azure.search.documents.generated.documentssearchget.searchindexsearchdocumentsget + SearchDocumentsResult response = documentsClient.searchGet("myindex", "nice hotels", true, + Arrays.asList("category,count:10,sort:count"), "rating gt 10", Arrays.asList("title"), "", "", + 80.0D, Arrays.asList("search.score() desc", "rating desc"), QueryType.SIMPLE, null, "sp", + Arrays.asList("title", "description"), SearchMode.ANY, ScoringStatistics.GLOBAL, "mysessionid", + Arrays.asList("docId", "title", "description"), 100, 10, null, null, null, null, null, null, null, null, + null, null, null); + // END:com.azure.search.documents.generated.documentssearchget.searchindexsearchdocumentsget + } +} diff --git a/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/generated/SearchIndexSearchDocumentsPost.java b/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/generated/SearchIndexSearchDocumentsPost.java new file mode 100644 index 000000000000..409adb876cbf --- /dev/null +++ b/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/generated/SearchIndexSearchDocumentsPost.java @@ -0,0 +1,76 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.search.documents.generated; + +import com.azure.identity.DefaultAzureCredentialBuilder; +import com.azure.search.documents.DocumentsClient; +import com.azure.search.documents.SearchClientBuilder; +import com.azure.search.documents.models.HybridCountAndFacetMode; +import com.azure.search.documents.models.HybridSearch; +import com.azure.search.documents.models.QueryAnswerType; +import com.azure.search.documents.models.QueryCaptionType; +import com.azure.search.documents.models.QueryLanguage; +import com.azure.search.documents.models.QueryRewritesType; +import com.azure.search.documents.models.QuerySpellerType; +import com.azure.search.documents.models.QueryType; +import com.azure.search.documents.models.ScoringStatistics; +import com.azure.search.documents.models.SearchDocumentsResult; +import com.azure.search.documents.models.SearchMode; +import com.azure.search.documents.models.SearchRequest; +import com.azure.search.documents.models.SemanticErrorMode; +import com.azure.search.documents.models.VectorFilterMode; +import com.azure.search.documents.models.VectorSimilarityThreshold; +import com.azure.search.documents.models.VectorizedQuery; +import java.util.Arrays; + +public class SearchIndexSearchDocumentsPost { + public static void main(String[] args) { + DocumentsClient documentsClient + = new SearchClientBuilder().credential(new DefaultAzureCredentialBuilder().build()) + .endpoint("https://previewexampleservice.search.windows.net") + .buildDocumentsClient(); + // BEGIN:com.azure.search.documents.generated.documentssearchpost.searchindexsearchdocumentspost + SearchDocumentsResult response = documentsClient.searchPost("preview-test", + new SearchRequest().setIncludeTotalResultCount(true) + .setFacets(Arrays.asList("ownerId", "price,metric:sum,default:10")) + .setFilter("category eq 'purple' or category eq 'pink'") + .setHighlightFields("category") + .setHighlightPostTag("") + .setHighlightPreTag("") + .setMinimumCoverage(100.0D) + .setQueryType(QueryType.SEMANTIC) + .setScoringStatistics(ScoringStatistics.GLOBAL) + .setSessionId("mysessionid") + .setScoringParameters(Arrays.asList("categoryTag:desiredCategoryValue")) + .setScoringProfile("stringFieldBoost") + .setSearchText("purple") + .setSearchFields("id,name,description,category,ownerId") + .setSearchMode(SearchMode.ANY) + .setQueryLanguage(QueryLanguage.EN_US) + .setSpeller(QuerySpellerType.LEXICON) + .setSelect("id,name,description,category,ownerId") + .setSkip(0) + .setTop(10) + .setSemanticConfiguration("testconfig") + .setSemanticErrorHandling(SemanticErrorMode.PARTIAL) + .setSemanticMaxWaitInMilliseconds(5000) + .setSemanticQuery("find all purple") + .setAnswers(QueryAnswerType.EXTRACTIVE) + .setCaptions(QueryCaptionType.EXTRACTIVE) + .setQueryRewrites(QueryRewritesType.GENERATIVE) + .setVectorQueries( + Arrays.asList(new VectorizedQuery(Arrays.asList(0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0)) + .setKNearestNeighbors(50) + .setFields("vector22, vector1b") + .setOversampling(20.0D) + .setWeight(1.0D) + .setThreshold(new VectorSimilarityThreshold(0.984)) + .setFilterOverride("ownerId eq 'sam'"))) + .setVectorFilterMode(VectorFilterMode.PRE_FILTER) + .setHybridSearch(new HybridSearch().setMaxTextRecallSize(100) + .setCountAndFacetMode(HybridCountAndFacetMode.COUNT_ALL_RESULTS))); + // END:com.azure.search.documents.generated.documentssearchpost.searchindexsearchdocumentspost + } +} diff --git a/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/generated/SearchIndexSearchDocumentsSemanticGet.java b/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/generated/SearchIndexSearchDocumentsSemanticGet.java new file mode 100644 index 000000000000..120d56cfdb76 --- /dev/null +++ b/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/generated/SearchIndexSearchDocumentsSemanticGet.java @@ -0,0 +1,29 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.search.documents.generated; + +import com.azure.identity.DefaultAzureCredentialBuilder; +import com.azure.search.documents.DocumentsClient; +import com.azure.search.documents.SearchClientBuilder; +import com.azure.search.documents.models.QueryAnswerType; +import com.azure.search.documents.models.QueryCaptionType; +import com.azure.search.documents.models.QueryType; +import com.azure.search.documents.models.SearchDocumentsResult; +import com.azure.search.documents.models.SemanticErrorMode; + +public class SearchIndexSearchDocumentsSemanticGet { + public static void main(String[] args) { + DocumentsClient documentsClient + = new SearchClientBuilder().credential(new DefaultAzureCredentialBuilder().build()) + .endpoint("https://myservice.search.windows.net") + .buildDocumentsClient(); + // BEGIN:com.azure.search.documents.generated.documentssearchget.searchindexsearchdocumentssemanticget + SearchDocumentsResult response = documentsClient.searchGet("myindex", "how do clouds form", true, null, null, + null, "", "", null, null, QueryType.SEMANTIC, null, null, null, null, null, null, null, null, null, + "my-semantic-config", SemanticErrorMode.PARTIAL, 780, QueryAnswerType.fromString("extractive|count-3"), + QueryCaptionType.fromString("extractive|highlight-true"), null, null, null, null, null, null); + // END:com.azure.search.documents.generated.documentssearchget.searchindexsearchdocumentssemanticget + } +} diff --git a/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/generated/SearchIndexSearchDocumentsSemanticPost.java b/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/generated/SearchIndexSearchDocumentsSemanticPost.java new file mode 100644 index 000000000000..daf2a76b9946 --- /dev/null +++ b/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/generated/SearchIndexSearchDocumentsSemanticPost.java @@ -0,0 +1,37 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.search.documents.generated; + +import com.azure.identity.DefaultAzureCredentialBuilder; +import com.azure.search.documents.DocumentsClient; +import com.azure.search.documents.SearchClientBuilder; +import com.azure.search.documents.models.QueryAnswerType; +import com.azure.search.documents.models.QueryCaptionType; +import com.azure.search.documents.models.QueryType; +import com.azure.search.documents.models.SearchDocumentsResult; +import com.azure.search.documents.models.SearchRequest; +import com.azure.search.documents.models.SemanticErrorMode; + +public class SearchIndexSearchDocumentsSemanticPost { + public static void main(String[] args) { + DocumentsClient documentsClient + = new SearchClientBuilder().credential(new DefaultAzureCredentialBuilder().build()) + .endpoint("https://myservice.search.windows.net") + .buildDocumentsClient(); + // BEGIN:com.azure.search.documents.generated.documentssearchpost.searchindexsearchdocumentssemanticpost + SearchDocumentsResult response = documentsClient.searchPost("myindex", + new SearchRequest().setIncludeTotalResultCount(true) + .setHighlightPostTag("") + .setHighlightPreTag("") + .setQueryType(QueryType.SEMANTIC) + .setSearchText("how do clouds form") + .setSemanticConfiguration("my-semantic-config") + .setSemanticErrorHandling(SemanticErrorMode.PARTIAL) + .setSemanticMaxWaitInMilliseconds(780) + .setAnswers(QueryAnswerType.fromString("extractive|count-3")) + .setCaptions(QueryCaptionType.fromString("extractive|highlight-true"))); + // END:com.azure.search.documents.generated.documentssearchpost.searchindexsearchdocumentssemanticpost + } +} diff --git a/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/generated/SearchIndexSuggestDocumentsGet.java b/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/generated/SearchIndexSuggestDocumentsGet.java new file mode 100644 index 000000000000..f15f46ddcf6e --- /dev/null +++ b/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/generated/SearchIndexSuggestDocumentsGet.java @@ -0,0 +1,25 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.search.documents.generated; + +import com.azure.identity.DefaultAzureCredentialBuilder; +import com.azure.search.documents.DocumentsClient; +import com.azure.search.documents.SearchClientBuilder; +import com.azure.search.documents.models.SuggestDocumentsResult; +import java.util.Arrays; + +public class SearchIndexSuggestDocumentsGet { + public static void main(String[] args) { + DocumentsClient documentsClient + = new SearchClientBuilder().credential(new DefaultAzureCredentialBuilder().build()) + .endpoint("https://myservice.search.windows.net") + .buildDocumentsClient(); + // BEGIN:com.azure.search.documents.generated.documentssuggestget.searchindexsuggestdocumentsget + SuggestDocumentsResult response = documentsClient.suggestGet("hote", "sg", "myindex", "rating gt 10", false, + "", "", 80.0D, Arrays.asList("search.score() desc", "rating desc"), Arrays.asList("title"), + Arrays.asList("docId", "title", "description"), 10); + // END:com.azure.search.documents.generated.documentssuggestget.searchindexsuggestdocumentsget + } +} diff --git a/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/generated/SearchIndexSuggestDocumentsPost.java b/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/generated/SearchIndexSuggestDocumentsPost.java new file mode 100644 index 000000000000..fdb1aa96f8df --- /dev/null +++ b/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/generated/SearchIndexSuggestDocumentsPost.java @@ -0,0 +1,32 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.search.documents.generated; + +import com.azure.identity.DefaultAzureCredentialBuilder; +import com.azure.search.documents.DocumentsClient; +import com.azure.search.documents.SearchClientBuilder; +import com.azure.search.documents.models.SuggestDocumentsResult; +import com.azure.search.documents.models.SuggestRequest; + +public class SearchIndexSuggestDocumentsPost { + public static void main(String[] args) { + DocumentsClient documentsClient + = new SearchClientBuilder().credential(new DefaultAzureCredentialBuilder().build()) + .endpoint("https://previewexampleservice.search.windows.net") + .buildDocumentsClient(); + // BEGIN:com.azure.search.documents.generated.documentssuggestpost.searchindexsuggestdocumentspost + SuggestDocumentsResult response = documentsClient.suggestPost("preview-test", + new SuggestRequest("p", "sg").setFilter("ownerId eq 'sam' and id lt '15'") + .setUseFuzzyMatching(true) + .setHighlightPostTag("") + .setHighlightPreTag("") + .setMinimumCoverage(80.0D) + .setOrderBy("id desc") + .setSearchFields("category") + .setSelect("id,name,category,ownerId") + .setTop(10)); + // END:com.azure.search.documents.generated.documentssuggestpost.searchindexsuggestdocumentspost + } +} diff --git a/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/generated/SearchServiceCreateAlias.java b/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/generated/SearchServiceCreateAlias.java new file mode 100644 index 000000000000..94fb1d22e6a8 --- /dev/null +++ b/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/generated/SearchServiceCreateAlias.java @@ -0,0 +1,22 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.search.documents.generated; + +import com.azure.identity.DefaultAzureCredentialBuilder; +import com.azure.search.documents.AliasesClient; +import com.azure.search.documents.SearchClientBuilder; +import com.azure.search.documents.models.SearchAlias; +import java.util.Arrays; + +public class SearchServiceCreateAlias { + public static void main(String[] args) { + AliasesClient aliasesClient = new SearchClientBuilder().credential(new DefaultAzureCredentialBuilder().build()) + .endpoint("https://previewexampleservice.search.windows.net") + .buildAliasesClient(); + // BEGIN:com.azure.search.documents.generated.aliasescreate.searchservicecreatealias + SearchAlias response = aliasesClient.create(new SearchAlias("tempalias", Arrays.asList("preview-test"))); + // END:com.azure.search.documents.generated.aliasescreate.searchservicecreatealias + } +} diff --git a/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/generated/SearchServiceCreateDataSource.java b/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/generated/SearchServiceCreateDataSource.java new file mode 100644 index 000000000000..86db2986d7a6 --- /dev/null +++ b/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/generated/SearchServiceCreateDataSource.java @@ -0,0 +1,45 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.search.documents.generated; + +import com.azure.identity.DefaultAzureCredentialBuilder; +import com.azure.search.documents.DataSourcesClient; +import com.azure.search.documents.SearchClientBuilder; +import com.azure.search.documents.models.AzureActiveDirectoryApplicationCredentials; +import com.azure.search.documents.models.DataSourceCredentials; +import com.azure.search.documents.models.HighWaterMarkChangeDetectionPolicy; +import com.azure.search.documents.models.SearchIndexerDataContainer; +import com.azure.search.documents.models.SearchIndexerDataNoneIdentity; +import com.azure.search.documents.models.SearchIndexerDataSource; +import com.azure.search.documents.models.SearchIndexerDataSourceType; +import com.azure.search.documents.models.SearchResourceEncryptionKey; +import com.azure.search.documents.models.SoftDeleteColumnDeletionDetectionPolicy; + +public class SearchServiceCreateDataSource { + public static void main(String[] args) { + DataSourcesClient dataSourcesClient + = new SearchClientBuilder().credential(new DefaultAzureCredentialBuilder().build()) + .endpoint("https://previewexampleservice.search.windows.net") + .buildDataSourcesClient(); + // BEGIN:com.azure.search.documents.generated.datasourcescreate.searchservicecreatedatasource + SearchIndexerDataSource response = dataSourcesClient.create(new SearchIndexerDataSource("tempdatasource", + SearchIndexerDataSourceType.AZURE_BLOB, + new DataSourceCredentials().setConnectionString( + "DefaultEndpointsProtocol=https;AccountName=myAccountName;AccountKey=myAccountKey;EndpointSuffix=core.windows.net "), + new SearchIndexerDataContainer("doc-extraction-skillset").setQuery("E2E_Dsat")) + .setDescription("My Azure Blob data source.") + .setIdentity(new SearchIndexerDataNoneIdentity()) + .setDataChangeDetectionPolicy(new HighWaterMarkChangeDetectionPolicy("metadata_storage_last_modified")) + .setDataDeletionDetectionPolicy( + new SoftDeleteColumnDeletionDetectionPolicy().setSoftDeleteColumnName("isDeleted") + .setSoftDeleteMarkerValue("true")) + .setEncryptionKey(new SearchResourceEncryptionKey("fakeTokenPlaceholder", "fakeTokenPlaceholder") + .setKeyVersion("fakeTokenPlaceholder") + .setAccessCredentials( + new AzureActiveDirectoryApplicationCredentials("00000000-0000-0000-0000-000000000000") + .setApplicationSecret("fakeTokenPlaceholder")))); + // END:com.azure.search.documents.generated.datasourcescreate.searchservicecreatedatasource + } +} diff --git a/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/generated/SearchServiceCreateIndex.java b/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/generated/SearchServiceCreateIndex.java new file mode 100644 index 000000000000..88d39a82e718 --- /dev/null +++ b/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/generated/SearchServiceCreateIndex.java @@ -0,0 +1,216 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.search.documents.generated; + +import com.azure.identity.DefaultAzureCredentialBuilder; +import com.azure.search.documents.IndexesClient; +import com.azure.search.documents.SearchClientBuilder; +import com.azure.search.documents.models.AIFoundryModelCatalogName; +import com.azure.search.documents.models.AsciiFoldingTokenFilter; +import com.azure.search.documents.models.AzureMachineLearningParameters; +import com.azure.search.documents.models.AzureMachineLearningVectorizer; +import com.azure.search.documents.models.AzureOpenAIModelName; +import com.azure.search.documents.models.AzureOpenAIVectorizer; +import com.azure.search.documents.models.AzureOpenAIVectorizerParameters; +import com.azure.search.documents.models.BM25SimilarityAlgorithm; +import com.azure.search.documents.models.BinaryQuantizationCompression; +import com.azure.search.documents.models.CharFilterName; +import com.azure.search.documents.models.CorsOptions; +import com.azure.search.documents.models.CustomAnalyzer; +import com.azure.search.documents.models.CustomNormalizer; +import com.azure.search.documents.models.HnswAlgorithmConfiguration; +import com.azure.search.documents.models.HnswParameters; +import com.azure.search.documents.models.LexicalAnalyzerName; +import com.azure.search.documents.models.LexicalTokenizerName; +import com.azure.search.documents.models.LuceneStandardTokenizerV2; +import com.azure.search.documents.models.MappingCharFilter; +import com.azure.search.documents.models.RescoringOptions; +import com.azure.search.documents.models.ScalarQuantizationCompression; +import com.azure.search.documents.models.ScalarQuantizationParameters; +import com.azure.search.documents.models.ScoringProfile; +import com.azure.search.documents.models.SearchField; +import com.azure.search.documents.models.SearchFieldDataType; +import com.azure.search.documents.models.SearchIndex; +import com.azure.search.documents.models.SearchIndexerDataNoneIdentity; +import com.azure.search.documents.models.SearchSuggester; +import com.azure.search.documents.models.SemanticConfiguration; +import com.azure.search.documents.models.SemanticField; +import com.azure.search.documents.models.SemanticPrioritizedFields; +import com.azure.search.documents.models.SemanticSearch; +import com.azure.search.documents.models.TagScoringFunction; +import com.azure.search.documents.models.TagScoringParameters; +import com.azure.search.documents.models.TextWeights; +import com.azure.search.documents.models.TokenFilterName; +import com.azure.search.documents.models.VectorSearch; +import com.azure.search.documents.models.VectorSearchAlgorithmMetric; +import com.azure.search.documents.models.VectorSearchCompressionRescoreStorageMethod; +import com.azure.search.documents.models.VectorSearchCompressionTarget; +import com.azure.search.documents.models.VectorSearchProfile; +import com.azure.search.documents.models.WebApiVectorizer; +import com.azure.search.documents.models.WebApiVectorizerParameters; +import java.time.Duration; +import java.util.Arrays; +import java.util.HashMap; +import java.util.Map; + +public class SearchServiceCreateIndex { + public static void main(String[] args) { + IndexesClient indexesClient = new SearchClientBuilder().credential(new DefaultAzureCredentialBuilder().build()) + .endpoint("https://previewexampleservice.search.windows.net") + .buildIndexesClient(); + // BEGIN:com.azure.search.documents.generated.indexescreate.searchservicecreateindex + SearchIndex response = indexesClient.create(new SearchIndex("temp-preview-test", Arrays.asList( + new SearchField("id", SearchFieldDataType.STRING).setKey(true).setSortable(true), + new SearchField("vector1", SearchFieldDataType.fromString("Collection(Edm.Single)")).setRetrievable(true) + .setSearchable(true) + .setVectorSearchDimensions(20) + .setVectorSearchProfileName("config1"), + new SearchField("vector1b", SearchFieldDataType.fromString("Collection(Edm.Single)")).setRetrievable(true) + .setSearchable(true) + .setVectorSearchDimensions(10) + .setVectorSearchProfileName("config2"), + new SearchField("vector2", SearchFieldDataType.fromString("Collection(Edm.Single)")).setRetrievable(true) + .setSearchable(true) + .setVectorSearchDimensions(5) + .setVectorSearchProfileName("config3"), + new SearchField("vector3", SearchFieldDataType.fromString("Collection(Edm.Single)")).setRetrievable(true) + .setSearchable(true) + .setVectorSearchDimensions(5) + .setVectorSearchProfileName("config3"), + new SearchField("vector22", SearchFieldDataType.fromString("Collection(Edm.Single)")).setRetrievable(true) + .setSearchable(true) + .setVectorSearchDimensions(10) + .setVectorSearchProfileName("config2"), + new SearchField("vector4", SearchFieldDataType.fromString("Collection(Edm.Single)")).setRetrievable(true) + .setSearchable(true) + .setVectorSearchDimensions(32) + .setVectorSearchProfileName("config4"), + new SearchField("name", SearchFieldDataType.STRING).setRetrievable(true) + .setSearchable(true) + .setFilterable(true) + .setSortable(true) + .setFacetable(true) + .setAnalyzer(LexicalAnalyzerName.EN_LUCENE), + new SearchField("description", SearchFieldDataType.STRING).setRetrievable(true) + .setSearchable(true) + .setFilterable(true) + .setSortable(true) + .setFacetable(true) + .setAnalyzer(LexicalAnalyzerName.STANDARD_LUCENE), + new SearchField("category", SearchFieldDataType.STRING).setRetrievable(true) + .setSearchable(true) + .setFilterable(true) + .setSortable(true) + .setFacetable(true) + .setAnalyzer(LexicalAnalyzerName.EN_LUCENE), + new SearchField("ownerId", SearchFieldDataType.STRING).setRetrievable(true) + .setSearchable(true) + .setFilterable(true) + .setSortable(true) + .setFacetable(true) + .setAnalyzer(LexicalAnalyzerName.EN_LUCENE), + new SearchField("price", SearchFieldDataType.DOUBLE).setRetrievable(true) + .setFilterable(true) + .setSortable(true) + .setFacetable(true))) + .setScoringProfiles(Arrays.asList(new ScoringProfile("stringFieldBoost") + .setTextWeights( + new TextWeights(mapOf("name", 3.0, "description", 1.0, "category", 2.0, "ownerId", 1.0))) + .setFunctions(Arrays + .asList(new TagScoringFunction("category", 2.0, new TagScoringParameters("categoryTag")))))) + .setDefaultScoringProfile("stringFieldBoost") + .setCorsOptions( + new CorsOptions(Arrays.asList("https://www.example.com/foo")).setMaxAgeInSeconds(10L)) + .setSuggesters(Arrays.asList(new SearchSuggester("sg", Arrays.asList("category", "ownerId")))) + .setAnalyzers(Arrays.asList(new CustomAnalyzer("tagsAnalyzer", LexicalTokenizerName.STANDARD) + .setTokenFilters(Arrays.asList(TokenFilterName.COMMON_GRAM)) + .setCharFilters(Arrays.asList(CharFilterName.HTML_STRIP)))) + .setTokenizers(Arrays.asList(new LuceneStandardTokenizerV2("my_tokenizer").setMaxTokenLength(100))) + .setTokenFilters( + Arrays.asList(new AsciiFoldingTokenFilter("my_tokenFilter").setPreserveOriginal(false))) + .setCharFilters(Arrays.asList(new MappingCharFilter("my_mapping", Arrays.asList(".=>,", "_=>-")))) + .setNormalizers(Arrays.asList(new CustomNormalizer("my_normalizer") + .setTokenFilters(Arrays.asList(TokenFilterName.fromString("my_tokenFilter"))) + .setCharFilters(Arrays.asList(CharFilterName.fromString("my_mapping"))))) + .setSimilarity(new BM25SimilarityAlgorithm().setK1(10.0D).setB(0.1D)) + .setSemanticSearch(new SemanticSearch().setDefaultConfigurationName("testconfig") + .setConfigurations(Arrays.asList(new SemanticConfiguration("testconfig", + new SemanticPrioritizedFields().setTitleField(new SemanticField("category")) + .setContentFields(Arrays.asList(new SemanticField("description"))) + .setKeywordsFields(Arrays.asList(new SemanticField("ownerId")))) + .setFlightingOptIn(true)))) + .setVectorSearch(new VectorSearch() + .setProfiles(Arrays.asList( + new VectorSearchProfile("config1", "cosine").setVectorizerName("openai") + .setCompressionName("mySQ8"), + new VectorSearchProfile("config2", "euclidean").setVectorizerName("custom-web-api") + .setCompressionName("mySQ8"), + new VectorSearchProfile("config3", "dotProduct").setVectorizerName("custom-web-api") + .setCompressionName("myBQC"), + new VectorSearchProfile("config4", "dotProduct").setVectorizerName("custom-web-api") + .setCompressionName("myBQWithoutOriginals"))) + .setAlgorithms(Arrays.asList( + new HnswAlgorithmConfiguration("cosine") + .setParameters(new HnswParameters().setMetric(VectorSearchAlgorithmMetric.COSINE)), + new HnswAlgorithmConfiguration("euclidean") + .setParameters(new HnswParameters().setMetric(VectorSearchAlgorithmMetric.EUCLIDEAN)), + new HnswAlgorithmConfiguration("dotProduct").setParameters( + new HnswParameters().setMetric(VectorSearchAlgorithmMetric.DOT_PRODUCT)))) + .setVectorizers(Arrays.asList( + new AzureOpenAIVectorizer("openai").setParameters(new AzureOpenAIVectorizerParameters() + .setResourceUrl("https://test-sample.openai.azure.com/") + .setDeploymentName("model") + .setApiKey("fakeTokenPlaceholder") + .setModelName(AzureOpenAIModelName.TEXT_EMBEDDING3LARGE)), + new WebApiVectorizer("custom-web-api").setWebApiParameters( + new WebApiVectorizerParameters().setUrl("https://my-custom-endpoint.org/") + .setHttpHeaders(mapOf("header1", "value1", "header2", "value2")) + .setHttpMethod("POST") + .setTimeout(Duration.parse("PT1M")) + .setAuthResourceId("api://f89d1c93-58a7-4b07-9a5b-5f89048b927b") + .setAuthIdentity(new SearchIndexerDataNoneIdentity())), + new AzureMachineLearningVectorizer("aml") + .setAMLParameters(new AzureMachineLearningParameters("https://my-custom-endpoint.org/") + .setResourceId("aml resource id") + .setTimeout(Duration.parse("PT1M")) + .setRegion("aml region") + .setModelName( + AIFoundryModelCatalogName.OPEN_AICLIPIMAGE_TEXT_EMBEDDINGS_VIT_BASE_PATCH32)))) + .setCompressions(Arrays.asList( + new ScalarQuantizationCompression("mySQ8") + .setRescoringOptions(new RescoringOptions().setEnableRescoring(true) + .setDefaultOversampling(10.0D) + .setRescoreStorageMethod( + VectorSearchCompressionRescoreStorageMethod.PRESERVE_ORIGINALS)) + .setTruncationDimension(2) + .setParameters(new ScalarQuantizationParameters() + .setQuantizedDataType(VectorSearchCompressionTarget.INT8)), + new BinaryQuantizationCompression("myBQC") + .setRescoringOptions(new RescoringOptions().setEnableRescoring(true) + .setDefaultOversampling(10.0D) + .setRescoreStorageMethod( + VectorSearchCompressionRescoreStorageMethod.PRESERVE_ORIGINALS)) + .setTruncationDimension(2), + new BinaryQuantizationCompression("myBQWithoutOriginals") + .setRescoringOptions(new RescoringOptions().setEnableRescoring(true) + .setDefaultOversampling(10.0D) + .setRescoreStorageMethod( + VectorSearchCompressionRescoreStorageMethod.DISCARD_ORIGINALS)) + .setTruncationDimension(2))))); + // END:com.azure.search.documents.generated.indexescreate.searchservicecreateindex + } + + // Use "Map.of" if available + @SuppressWarnings("unchecked") + private static Map mapOf(Object... inputs) { + Map map = new HashMap<>(); + for (int i = 0; i < inputs.length; i += 2) { + String key = (String) inputs[i]; + T value = (T) inputs[i + 1]; + map.put(key, value); + } + return map; + } +} diff --git a/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/generated/SearchServiceCreateIndexer.java b/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/generated/SearchServiceCreateIndexer.java new file mode 100644 index 000000000000..090dac0507a9 --- /dev/null +++ b/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/generated/SearchServiceCreateIndexer.java @@ -0,0 +1,101 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.search.documents.generated; + +import com.azure.identity.DefaultAzureCredentialBuilder; +import com.azure.search.documents.IndexersClient; +import com.azure.search.documents.SearchClientBuilder; +import com.azure.search.documents.models.AzureActiveDirectoryApplicationCredentials; +import com.azure.search.documents.models.BlobIndexerDataToExtract; +import com.azure.search.documents.models.BlobIndexerImageAction; +import com.azure.search.documents.models.BlobIndexerPDFTextRotationAlgorithm; +import com.azure.search.documents.models.BlobIndexerParsingMode; +import com.azure.search.documents.models.FieldMapping; +import com.azure.search.documents.models.FieldMappingFunction; +import com.azure.search.documents.models.IndexerExecutionEnvironment; +import com.azure.search.documents.models.IndexingParameters; +import com.azure.search.documents.models.IndexingParametersConfiguration; +import com.azure.search.documents.models.IndexingSchedule; +import com.azure.search.documents.models.MarkdownHeaderDepth; +import com.azure.search.documents.models.MarkdownParsingSubmode; +import com.azure.search.documents.models.SearchIndexer; +import com.azure.search.documents.models.SearchIndexerCache; +import com.azure.search.documents.models.SearchIndexerDataNoneIdentity; +import com.azure.search.documents.models.SearchResourceEncryptionKey; +import java.time.Duration; +import java.time.OffsetDateTime; +import java.util.Arrays; +import java.util.HashMap; +import java.util.Map; + +public class SearchServiceCreateIndexer { + public static void main(String[] args) { + IndexersClient indexersClient + = new SearchClientBuilder().credential(new DefaultAzureCredentialBuilder().build()) + .endpoint("https://previewexampleservice.search.windows.net") + .buildIndexersClient(); + // BEGIN:com.azure.search.documents.generated.indexerscreate.searchservicecreateindexer + SearchIndexer response + = indexersClient + .create( + new SearchIndexer("myindexer", "mydocdbdatasource", "preview-test") + .setDescription("Description of the indexer") + .setSkillsetName("myskillset") + .setSchedule(new IndexingSchedule(Duration.parse("P1D")) + .setStartTime(OffsetDateTime.parse("2025-01-07T19:30:00Z"))) + .setParameters( + new IndexingParameters().setBatchSize(10) + .setMaxFailedItems(10) + .setMaxFailedItemsPerBatch(5) + .setConfiguration(new IndexingParametersConfiguration() + .setParsingMode(BlobIndexerParsingMode.MARKDOWN) + .setExcludedFileNameExtensions(".png,.mp4") + .setIndexedFileNameExtensions(".docx,.pptx") + .setFailOnUnsupportedContentType(true) + .setFailOnUnprocessableDocument(false) + .setIndexStorageMetadataOnlyForOversizedDocuments(true) + .setDelimitedTextHeaders("Header1,Header2") + .setDelimitedTextDelimiter("|") + .setFirstLineContainsHeaders(true) + .setMarkdownParsingSubmode(MarkdownParsingSubmode.ONE_TO_MANY) + .setMarkdownHeaderDepth(MarkdownHeaderDepth.H6) + .setDocumentRoot("/root") + .setDataToExtract(BlobIndexerDataToExtract.STORAGE_METADATA) + .setImageAction(BlobIndexerImageAction.NONE) + .setAllowSkillsetToReadFileData(false) + .setPdfTextRotationAlgorithm(BlobIndexerPDFTextRotationAlgorithm.NONE) + .setExecutionEnvironment(IndexerExecutionEnvironment.STANDARD) + .setAdditionalProperties(mapOf()))) + .setFieldMappings(Arrays.asList(new FieldMapping("/document").setTargetFieldName("name") + .setMappingFunction(new FieldMappingFunction("base64Encode")))) + .setOutputFieldMappings(Arrays + .asList(new FieldMapping("/document").setTargetFieldName("name") + .setMappingFunction(new FieldMappingFunction("base64Encode")))) + .setIsDisabled(false) + .setEncryptionKey( + new SearchResourceEncryptionKey("fakeTokenPlaceholder", "fakeTokenPlaceholder") + .setKeyVersion("fakeTokenPlaceholder") + .setAccessCredentials(new AzureActiveDirectoryApplicationCredentials( + "00000000-0000-0000-0000-000000000000") + .setApplicationSecret("fakeTokenPlaceholder"))) + .setCache(new SearchIndexerCache().setStorageConnectionString( + "DefaultEndpointsProtocol=https;AccountName=myAccountName;AccountKey=myAccountKey;EndpointSuffix=core.windows.net ") + .setEnableReprocessing(true) + .setIdentity(new SearchIndexerDataNoneIdentity()))); + // END:com.azure.search.documents.generated.indexerscreate.searchservicecreateindexer + } + + // Use "Map.of" if available + @SuppressWarnings("unchecked") + private static Map mapOf(Object... inputs) { + Map map = new HashMap<>(); + for (int i = 0; i < inputs.length; i += 2) { + String key = (String) inputs[i]; + T value = (T) inputs[i + 1]; + map.put(key, value); + } + return map; + } +} diff --git a/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/generated/SearchServiceCreateOrUpdateAlias.java b/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/generated/SearchServiceCreateOrUpdateAlias.java new file mode 100644 index 000000000000..92a676731ef3 --- /dev/null +++ b/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/generated/SearchServiceCreateOrUpdateAlias.java @@ -0,0 +1,24 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.search.documents.generated; + +import com.azure.core.http.MatchConditions; +import com.azure.identity.DefaultAzureCredentialBuilder; +import com.azure.search.documents.AliasesClient; +import com.azure.search.documents.SearchClientBuilder; +import com.azure.search.documents.models.SearchAlias; +import java.util.Arrays; + +public class SearchServiceCreateOrUpdateAlias { + public static void main(String[] args) { + AliasesClient aliasesClient = new SearchClientBuilder().credential(new DefaultAzureCredentialBuilder().build()) + .endpoint("https://previewexampleservice.search.windows.net") + .buildAliasesClient(); + // BEGIN:com.azure.search.documents.generated.aliasescreateorupdate.searchservicecreateorupdatealias + SearchAlias response = aliasesClient.createOrUpdate("myalias", + new SearchAlias("myalias", Arrays.asList("preview-test")), new MatchConditions()); + // END:com.azure.search.documents.generated.aliasescreateorupdate.searchservicecreateorupdatealias + } +} diff --git a/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/generated/SearchServiceCreateOrUpdateDataSource.java b/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/generated/SearchServiceCreateOrUpdateDataSource.java new file mode 100644 index 000000000000..83569fccdb9e --- /dev/null +++ b/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/generated/SearchServiceCreateOrUpdateDataSource.java @@ -0,0 +1,48 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.search.documents.generated; + +import com.azure.core.http.MatchConditions; +import com.azure.identity.DefaultAzureCredentialBuilder; +import com.azure.search.documents.DataSourcesClient; +import com.azure.search.documents.SearchClientBuilder; +import com.azure.search.documents.models.AzureActiveDirectoryApplicationCredentials; +import com.azure.search.documents.models.DataSourceCredentials; +import com.azure.search.documents.models.HighWaterMarkChangeDetectionPolicy; +import com.azure.search.documents.models.SearchIndexerDataContainer; +import com.azure.search.documents.models.SearchIndexerDataNoneIdentity; +import com.azure.search.documents.models.SearchIndexerDataSource; +import com.azure.search.documents.models.SearchIndexerDataSourceType; +import com.azure.search.documents.models.SearchResourceEncryptionKey; +import com.azure.search.documents.models.SoftDeleteColumnDeletionDetectionPolicy; + +public class SearchServiceCreateOrUpdateDataSource { + public static void main(String[] args) { + DataSourcesClient dataSourcesClient + = new SearchClientBuilder().credential(new DefaultAzureCredentialBuilder().build()) + .endpoint("https://previewexampleservice.search.windows.net") + .buildDataSourcesClient(); + // BEGIN:com.azure.search.documents.generated.datasourcescreateorupdate.searchservicecreateorupdatedatasource + SearchIndexerDataSource response = dataSourcesClient.createOrUpdate("tempdatasource", + new SearchIndexerDataSource("tempdatasource", SearchIndexerDataSourceType.AZURE_BLOB, + new DataSourceCredentials().setConnectionString( + "DefaultEndpointsProtocol=https;AccountName=myAccountName;AccountKey=myAccountKey;EndpointSuffix=core.windows.net "), + new SearchIndexerDataContainer("doc-extraction-skillset").setQuery("E2E_Dsat")) + .setDescription("My Azure Blob data source.") + .setIdentity(new SearchIndexerDataNoneIdentity()) + .setDataChangeDetectionPolicy( + new HighWaterMarkChangeDetectionPolicy("metadata_storage_last_modified")) + .setDataDeletionDetectionPolicy( + new SoftDeleteColumnDeletionDetectionPolicy().setSoftDeleteColumnName("isDeleted") + .setSoftDeleteMarkerValue("true")) + .setEncryptionKey(new SearchResourceEncryptionKey("fakeTokenPlaceholder", "fakeTokenPlaceholder") + .setKeyVersion("fakeTokenPlaceholder") + .setAccessCredentials( + new AzureActiveDirectoryApplicationCredentials("00000000-0000-0000-0000-000000000000") + .setApplicationSecret("fakeTokenPlaceholder"))), + null, new MatchConditions()); + // END:com.azure.search.documents.generated.datasourcescreateorupdate.searchservicecreateorupdatedatasource + } +} diff --git a/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/generated/SearchServiceCreateOrUpdateIndex.java b/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/generated/SearchServiceCreateOrUpdateIndex.java new file mode 100644 index 000000000000..5d72cc29daf4 --- /dev/null +++ b/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/generated/SearchServiceCreateOrUpdateIndex.java @@ -0,0 +1,231 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.search.documents.generated; + +import com.azure.core.http.MatchConditions; +import com.azure.identity.DefaultAzureCredentialBuilder; +import com.azure.search.documents.IndexesClient; +import com.azure.search.documents.SearchClientBuilder; +import com.azure.search.documents.models.AIFoundryModelCatalogName; +import com.azure.search.documents.models.AsciiFoldingTokenFilter; +import com.azure.search.documents.models.AzureMachineLearningParameters; +import com.azure.search.documents.models.AzureMachineLearningVectorizer; +import com.azure.search.documents.models.AzureOpenAIModelName; +import com.azure.search.documents.models.AzureOpenAIVectorizer; +import com.azure.search.documents.models.AzureOpenAIVectorizerParameters; +import com.azure.search.documents.models.BM25SimilarityAlgorithm; +import com.azure.search.documents.models.BinaryQuantizationCompression; +import com.azure.search.documents.models.CharFilterName; +import com.azure.search.documents.models.CorsOptions; +import com.azure.search.documents.models.CustomAnalyzer; +import com.azure.search.documents.models.CustomNormalizer; +import com.azure.search.documents.models.HnswAlgorithmConfiguration; +import com.azure.search.documents.models.HnswParameters; +import com.azure.search.documents.models.LexicalAnalyzerName; +import com.azure.search.documents.models.LexicalTokenizerName; +import com.azure.search.documents.models.LuceneStandardTokenizerV2; +import com.azure.search.documents.models.MappingCharFilter; +import com.azure.search.documents.models.RescoringOptions; +import com.azure.search.documents.models.ScalarQuantizationCompression; +import com.azure.search.documents.models.ScalarQuantizationParameters; +import com.azure.search.documents.models.ScoringProfile; +import com.azure.search.documents.models.SearchField; +import com.azure.search.documents.models.SearchFieldDataType; +import com.azure.search.documents.models.SearchIndex; +import com.azure.search.documents.models.SearchIndexerDataNoneIdentity; +import com.azure.search.documents.models.SearchSuggester; +import com.azure.search.documents.models.SemanticConfiguration; +import com.azure.search.documents.models.SemanticField; +import com.azure.search.documents.models.SemanticPrioritizedFields; +import com.azure.search.documents.models.SemanticSearch; +import com.azure.search.documents.models.TagScoringFunction; +import com.azure.search.documents.models.TagScoringParameters; +import com.azure.search.documents.models.TextWeights; +import com.azure.search.documents.models.TokenFilterName; +import com.azure.search.documents.models.VectorSearch; +import com.azure.search.documents.models.VectorSearchAlgorithmMetric; +import com.azure.search.documents.models.VectorSearchCompressionRescoreStorageMethod; +import com.azure.search.documents.models.VectorSearchCompressionTarget; +import com.azure.search.documents.models.VectorSearchProfile; +import com.azure.search.documents.models.WebApiVectorizer; +import com.azure.search.documents.models.WebApiVectorizerParameters; +import java.time.Duration; +import java.util.Arrays; +import java.util.HashMap; +import java.util.Map; + +public class SearchServiceCreateOrUpdateIndex { + public static void main(String[] args) { + IndexesClient indexesClient = new SearchClientBuilder().credential(new DefaultAzureCredentialBuilder().build()) + .endpoint("https://previewexampleservice.search.windows.net") + .buildIndexesClient(); + // BEGIN:com.azure.search.documents.generated.indexescreateorupdate.searchservicecreateorupdateindex + SearchIndex response = indexesClient.createOrUpdate("temp-preview-test", + new SearchIndex("temp-preview-test", + Arrays.asList(new SearchField("id", SearchFieldDataType.STRING).setKey(true).setSortable(true), + new SearchField("vector1", SearchFieldDataType.fromString("Collection(Edm.Single)")) + .setRetrievable(true) + .setSearchable(true) + .setVectorSearchDimensions(20) + .setVectorSearchProfileName("config1"), + new SearchField("vector1b", SearchFieldDataType.fromString("Collection(Edm.Single)")) + .setRetrievable(true) + .setSearchable(true) + .setVectorSearchDimensions(10) + .setVectorSearchProfileName("config2"), + new SearchField("vector2", SearchFieldDataType.fromString("Collection(Edm.Single)")) + .setRetrievable(true) + .setSearchable(true) + .setVectorSearchDimensions(5) + .setVectorSearchProfileName("config3"), + new SearchField("vector3", SearchFieldDataType.fromString("Collection(Edm.Single)")) + .setRetrievable(true) + .setSearchable(true) + .setVectorSearchDimensions(5) + .setVectorSearchProfileName("config3"), + new SearchField("vector22", SearchFieldDataType.fromString("Collection(Edm.Single)")) + .setRetrievable(true) + .setSearchable(true) + .setVectorSearchDimensions(10) + .setVectorSearchProfileName("config2"), + new SearchField("vector4", SearchFieldDataType.fromString("Collection(Edm.Single)")) + .setRetrievable(true) + .setSearchable(true) + .setVectorSearchDimensions(32) + .setVectorSearchProfileName("config4"), + new SearchField("name", SearchFieldDataType.STRING).setRetrievable(true) + .setSearchable(true) + .setFilterable(true) + .setSortable(true) + .setFacetable(true) + .setAnalyzer(LexicalAnalyzerName.EN_LUCENE), + new SearchField("description", SearchFieldDataType.STRING).setRetrievable(true) + .setSearchable(true) + .setFilterable(true) + .setSortable(true) + .setFacetable(true) + .setAnalyzer(LexicalAnalyzerName.STANDARD_LUCENE), + new SearchField("category", SearchFieldDataType.STRING).setRetrievable(true) + .setSearchable(true) + .setFilterable(true) + .setSortable(true) + .setFacetable(true) + .setAnalyzer(LexicalAnalyzerName.EN_LUCENE), + new SearchField("ownerId", SearchFieldDataType.STRING).setRetrievable(true) + .setSearchable(true) + .setFilterable(true) + .setSortable(true) + .setFacetable(true) + .setAnalyzer(LexicalAnalyzerName.EN_LUCENE), + new SearchField("price", SearchFieldDataType.DOUBLE).setRetrievable(true) + .setFilterable(true) + .setSortable(true) + .setFacetable(true))) + .setScoringProfiles(Arrays.asList(new ScoringProfile("stringFieldBoost") + .setTextWeights(new TextWeights( + mapOf("name", 3.0, "description", 1.0, "category", 2.0, "ownerId", 1.0))) + .setFunctions(Arrays.asList( + new TagScoringFunction("category", 2.0, new TagScoringParameters("categoryTag")))))) + .setDefaultScoringProfile("stringFieldBoost") + .setCorsOptions( + new CorsOptions(Arrays.asList("https://www.example.com/foo")).setMaxAgeInSeconds(10L)) + .setSuggesters( + Arrays.asList(new SearchSuggester("sg", Arrays.asList("category", "ownerId")))) + .setAnalyzers( + Arrays.asList(new CustomAnalyzer("tagsAnalyzer", LexicalTokenizerName.STANDARD) + .setTokenFilters(Arrays.asList(TokenFilterName.COMMON_GRAM)) + .setCharFilters(Arrays.asList(CharFilterName.HTML_STRIP)))) + .setTokenizers( + Arrays.asList(new LuceneStandardTokenizerV2("my_tokenizer").setMaxTokenLength(100))) + .setTokenFilters( + Arrays.asList(new AsciiFoldingTokenFilter("my_tokenFilter").setPreserveOriginal(false))) + .setCharFilters( + Arrays.asList(new MappingCharFilter("my_mapping", Arrays.asList(".=>,", "_=>-")))) + .setNormalizers(Arrays.asList(new CustomNormalizer("my_normalizer") + .setTokenFilters(Arrays.asList(TokenFilterName.fromString("my_tokenFilter"))) + .setCharFilters(Arrays.asList(CharFilterName.fromString("my_mapping"))))) + .setSimilarity(new BM25SimilarityAlgorithm().setK1(10.0D).setB(0.1D)) + .setSemanticSearch(new SemanticSearch().setDefaultConfigurationName("testconfig") + .setConfigurations(Arrays.asList(new SemanticConfiguration("testconfig", + new SemanticPrioritizedFields().setTitleField(new SemanticField("category")) + .setContentFields(Arrays.asList(new SemanticField("description"))) + .setKeywordsFields(Arrays.asList(new SemanticField("ownerId")))) + .setFlightingOptIn(true)))) + .setVectorSearch(new VectorSearch() + .setProfiles(Arrays.asList( + new VectorSearchProfile("config1", "cosine").setVectorizerName("openai") + .setCompressionName("mySQ8"), + new VectorSearchProfile("config2", "euclidean").setVectorizerName("custom-web-api") + .setCompressionName("mySQ8"), + new VectorSearchProfile("config3", "dotProduct").setVectorizerName("custom-web-api") + .setCompressionName("myBQC"), + new VectorSearchProfile("config4", "dotProduct").setVectorizerName("custom-web-api") + .setCompressionName("myBQWithoutOriginals"))) + .setAlgorithms(Arrays.asList( + new HnswAlgorithmConfiguration("cosine").setParameters( + new HnswParameters().setMetric(VectorSearchAlgorithmMetric.COSINE)), + new HnswAlgorithmConfiguration("euclidean").setParameters( + new HnswParameters().setMetric(VectorSearchAlgorithmMetric.EUCLIDEAN)), + new HnswAlgorithmConfiguration("dotProduct").setParameters( + new HnswParameters().setMetric(VectorSearchAlgorithmMetric.DOT_PRODUCT)))) + .setVectorizers(Arrays.asList( + new AzureOpenAIVectorizer("openai") + .setParameters(new AzureOpenAIVectorizerParameters() + .setResourceUrl("https://test-sample.openai.azure.com/") + .setDeploymentName("model") + .setApiKey("fakeTokenPlaceholder") + .setModelName(AzureOpenAIModelName.TEXT_EMBEDDING3LARGE)), + new WebApiVectorizer("custom-web-api") + .setWebApiParameters(new WebApiVectorizerParameters() + .setUrl("https://my-custom-endpoint.org/") + .setHttpHeaders(mapOf("header1", "value1", "header2", "value2")) + .setHttpMethod("POST") + .setTimeout(Duration.parse("PT1M")) + .setAuthResourceId("api://f89d1c93-58a7-4b07-9a5b-5f89048b927b") + .setAuthIdentity(new SearchIndexerDataNoneIdentity())), + new AzureMachineLearningVectorizer("aml").setAMLParameters( + new AzureMachineLearningParameters("https://my-custom-endpoint.org/") + .setResourceId("aml resource id") + .setTimeout(Duration.parse("PT1M")) + .setRegion("aml region") + .setModelName( + AIFoundryModelCatalogName.OPEN_AICLIPIMAGE_TEXT_EMBEDDINGS_VIT_BASE_PATCH32)))) + .setCompressions(Arrays.asList( + new ScalarQuantizationCompression("mySQ8") + .setRescoringOptions(new RescoringOptions().setEnableRescoring(true) + .setDefaultOversampling(10.0D) + .setRescoreStorageMethod( + VectorSearchCompressionRescoreStorageMethod.PRESERVE_ORIGINALS)) + .setTruncationDimension(2) + .setParameters(new ScalarQuantizationParameters() + .setQuantizedDataType(VectorSearchCompressionTarget.INT8)), + new BinaryQuantizationCompression("myBQC") + .setRescoringOptions(new RescoringOptions().setEnableRescoring(true) + .setDefaultOversampling(10.0D) + .setRescoreStorageMethod( + VectorSearchCompressionRescoreStorageMethod.PRESERVE_ORIGINALS)) + .setTruncationDimension(2), + new BinaryQuantizationCompression("myBQWithoutOriginals") + .setRescoringOptions(new RescoringOptions().setEnableRescoring(true) + .setDefaultOversampling(10.0D) + .setRescoreStorageMethod( + VectorSearchCompressionRescoreStorageMethod.DISCARD_ORIGINALS)) + .setTruncationDimension(2)))), + null, new MatchConditions()); + // END:com.azure.search.documents.generated.indexescreateorupdate.searchservicecreateorupdateindex + } + + // Use "Map.of" if available + @SuppressWarnings("unchecked") + private static Map mapOf(Object... inputs) { + Map map = new HashMap<>(); + for (int i = 0; i < inputs.length; i += 2) { + String key = (String) inputs[i]; + T value = (T) inputs[i + 1]; + map.put(key, value); + } + return map; + } +} diff --git a/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/generated/SearchServiceCreateOrUpdateIndexer.java b/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/generated/SearchServiceCreateOrUpdateIndexer.java new file mode 100644 index 000000000000..2480db61bb53 --- /dev/null +++ b/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/generated/SearchServiceCreateOrUpdateIndexer.java @@ -0,0 +1,96 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.search.documents.generated; + +import com.azure.core.http.MatchConditions; +import com.azure.identity.DefaultAzureCredentialBuilder; +import com.azure.search.documents.IndexersClient; +import com.azure.search.documents.SearchClientBuilder; +import com.azure.search.documents.models.AzureActiveDirectoryApplicationCredentials; +import com.azure.search.documents.models.BlobIndexerDataToExtract; +import com.azure.search.documents.models.BlobIndexerImageAction; +import com.azure.search.documents.models.BlobIndexerPDFTextRotationAlgorithm; +import com.azure.search.documents.models.BlobIndexerParsingMode; +import com.azure.search.documents.models.FieldMapping; +import com.azure.search.documents.models.FieldMappingFunction; +import com.azure.search.documents.models.IndexerExecutionEnvironment; +import com.azure.search.documents.models.IndexingParameters; +import com.azure.search.documents.models.IndexingParametersConfiguration; +import com.azure.search.documents.models.IndexingSchedule; +import com.azure.search.documents.models.MarkdownHeaderDepth; +import com.azure.search.documents.models.MarkdownParsingSubmode; +import com.azure.search.documents.models.SearchIndexer; +import com.azure.search.documents.models.SearchResourceEncryptionKey; +import java.time.Duration; +import java.time.OffsetDateTime; +import java.util.Arrays; +import java.util.HashMap; +import java.util.Map; + +public class SearchServiceCreateOrUpdateIndexer { + public static void main(String[] args) { + IndexersClient indexersClient + = new SearchClientBuilder().credential(new DefaultAzureCredentialBuilder().build()) + .endpoint("https://previewexampleservice.search.windows.net") + .buildIndexersClient(); + // BEGIN:com.azure.search.documents.generated.indexerscreateorupdate.searchservicecreateorupdateindexer + SearchIndexer response + = indexersClient + .createOrUpdate("myindexer", + new SearchIndexer("myindexer", "mydocdbdatasource", "preview-test") + .setDescription("Description of the indexer") + .setSkillsetName("myskillset") + .setSchedule(new IndexingSchedule(Duration.parse("P1D")) + .setStartTime(OffsetDateTime.parse("2025-01-07T19:30:00Z"))) + .setParameters( + new IndexingParameters().setBatchSize(10) + .setMaxFailedItems(10) + .setMaxFailedItemsPerBatch(5) + .setConfiguration(new IndexingParametersConfiguration() + .setParsingMode(BlobIndexerParsingMode.MARKDOWN) + .setExcludedFileNameExtensions(".png,.mp4") + .setIndexedFileNameExtensions(".docx,.pptx") + .setFailOnUnsupportedContentType(true) + .setFailOnUnprocessableDocument(false) + .setIndexStorageMetadataOnlyForOversizedDocuments(true) + .setDelimitedTextHeaders("Header1,Header2") + .setDelimitedTextDelimiter("|") + .setFirstLineContainsHeaders(true) + .setMarkdownParsingSubmode(MarkdownParsingSubmode.ONE_TO_ONE) + .setMarkdownHeaderDepth(MarkdownHeaderDepth.H6) + .setDocumentRoot("/root") + .setDataToExtract(BlobIndexerDataToExtract.STORAGE_METADATA) + .setImageAction(BlobIndexerImageAction.NONE) + .setAllowSkillsetToReadFileData(false) + .setPdfTextRotationAlgorithm(BlobIndexerPDFTextRotationAlgorithm.NONE) + .setExecutionEnvironment(IndexerExecutionEnvironment.STANDARD) + .setAdditionalProperties(mapOf()))) + .setFieldMappings(Arrays.asList(new FieldMapping("/document").setTargetFieldName("name") + .setMappingFunction(new FieldMappingFunction("base64Encode")))) + .setOutputFieldMappings(Arrays.asList(new FieldMapping("/document").setTargetFieldName("name") + .setMappingFunction(new FieldMappingFunction("base64Encode")))) + .setIsDisabled(false) + .setEncryptionKey( + new SearchResourceEncryptionKey("fakeTokenPlaceholder", "fakeTokenPlaceholder") + .setKeyVersion("fakeTokenPlaceholder") + .setAccessCredentials(new AzureActiveDirectoryApplicationCredentials( + "00000000-0000-0000-0000-000000000000") + .setApplicationSecret("fakeTokenPlaceholder"))), + null, null, new MatchConditions()); + // END:com.azure.search.documents.generated.indexerscreateorupdate.searchservicecreateorupdateindexer + } + + // Use "Map.of" if available + @SuppressWarnings("unchecked") + private static Map mapOf(Object... inputs) { + Map map = new HashMap<>(); + for (int i = 0; i < inputs.length; i += 2) { + String key = (String) inputs[i]; + T value = (T) inputs[i + 1]; + map.put(key, value); + } + return map; + } +} diff --git a/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/generated/SearchServiceCreateOrUpdateSkillset.java b/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/generated/SearchServiceCreateOrUpdateSkillset.java new file mode 100644 index 000000000000..f1851f0338df --- /dev/null +++ b/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/generated/SearchServiceCreateOrUpdateSkillset.java @@ -0,0 +1,88 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.search.documents.generated; + +import com.azure.core.http.MatchConditions; +import com.azure.identity.DefaultAzureCredentialBuilder; +import com.azure.search.documents.SearchClientBuilder; +import com.azure.search.documents.SkillsetsClient; +import com.azure.search.documents.models.AIServicesAccountKey; +import com.azure.search.documents.models.AzureActiveDirectoryApplicationCredentials; +import com.azure.search.documents.models.AzureOpenAITokenizerParameters; +import com.azure.search.documents.models.DocumentIntelligenceLayoutSkill; +import com.azure.search.documents.models.DocumentIntelligenceLayoutSkillMarkdownHeaderDepth; +import com.azure.search.documents.models.DocumentIntelligenceLayoutSkillOutputMode; +import com.azure.search.documents.models.InputFieldMappingEntry; +import com.azure.search.documents.models.KeyPhraseExtractionSkill; +import com.azure.search.documents.models.LanguageDetectionSkill; +import com.azure.search.documents.models.OutputFieldMappingEntry; +import com.azure.search.documents.models.SearchIndexerSkillset; +import com.azure.search.documents.models.SearchResourceEncryptionKey; +import com.azure.search.documents.models.SplitSkill; +import com.azure.search.documents.models.SplitSkillEncoderModelName; +import com.azure.search.documents.models.SplitSkillUnit; +import com.azure.search.documents.models.TextSplitMode; +import com.azure.search.documents.models.WebApiSkill; +import java.time.Duration; +import java.util.Arrays; + +public class SearchServiceCreateOrUpdateSkillset { + public static void main(String[] args) { + SkillsetsClient skillsetsClient + = new SearchClientBuilder().credential(new DefaultAzureCredentialBuilder().build()) + .endpoint("https://previewexampleservice.search.windows.net") + .buildSkillsetsClient(); + // BEGIN:com.azure.search.documents.generated.skillsetscreateorupdate.searchservicecreateorupdateskillset + SearchIndexerSkillset response = skillsetsClient.createOrUpdate("tempskillset", + new SearchIndexerSkillset("tempskillset", Arrays.asList( + new LanguageDetectionSkill( + Arrays.asList(new InputFieldMappingEntry("text").setSource("/document/content"), + new InputFieldMappingEntry("countryHint").setSource("/document/countryHint")), + Arrays.asList(new OutputFieldMappingEntry("languageCode").setTargetName("languageCode"))) + .setName("skill2"), + new SplitSkill( + Arrays.asList(new InputFieldMappingEntry("text").setSource("/document/content"), + new InputFieldMappingEntry("languageCode").setSource("/document/languageCode")), + Arrays.asList(new OutputFieldMappingEntry("textItems").setTargetName("pages"))).setName("skill3") + .setTextSplitMode(TextSplitMode.PAGES) + .setMaximumPageLength(4000) + .setUnit(SplitSkillUnit.AZURE_OPEN_AITOKENS) + .setAzureOpenAITokenizerParameters(new AzureOpenAITokenizerParameters() + .setEncoderModelName(SplitSkillEncoderModelName.CL100K_BASE) + .setAllowedSpecialTokens(Arrays.asList("[START]", "[END]"))), + new KeyPhraseExtractionSkill( + Arrays.asList(new InputFieldMappingEntry("text").setSource("/document/content"), + new InputFieldMappingEntry("languageCode").setSource("/document/languageCode")), + Arrays.asList(new OutputFieldMappingEntry("keyPhrases").setTargetName("keyPhrases"))) + .setName("skill4") + .setContext("/document/pages/*"), + new WebApiSkill( + Arrays.asList(new InputFieldMappingEntry("text").setSource("/document/content"), + new InputFieldMappingEntry("languageCode").setSource("/document/languageCode")), + Arrays.asList(new OutputFieldMappingEntry("customresult").setTargetName("result")), + "https://contoso.example.org/").setName("skill5") + .setHttpMethod("POST") + .setTimeout(Duration.parse("PT5S")), + new DocumentIntelligenceLayoutSkill( + Arrays.asList(new InputFieldMappingEntry("file_data").setSource("/document/content")), + Arrays.asList(new OutputFieldMappingEntry("markdown_document").setTargetName("markdown_document"))) + .setName("docIntelligenceLayoutSkill") + .setContext("/document") + .setOutputMode(DocumentIntelligenceLayoutSkillOutputMode.ONE_TO_MANY) + .setMarkdownHeaderDepth(DocumentIntelligenceLayoutSkillMarkdownHeaderDepth.H3))) + .setDescription("Skillset for extracting entities and more") + .setCognitiveServicesAccount(new AIServicesAccountKey("fakeTokenPlaceholder", + "https://mySubdomainName.cognitiveservices.azure.com").setDescription( + "Description of the Azure AI service resource attached to a skillset")) + .setEncryptionKey( + new SearchResourceEncryptionKey("fakeTokenPlaceholder", "fakeTokenPlaceholder") + .setKeyVersion("fakeTokenPlaceholder") + .setAccessCredentials(new AzureActiveDirectoryApplicationCredentials( + "00000000-0000-0000-0000-000000000000") + .setApplicationSecret("fakeTokenPlaceholder"))), + null, null, new MatchConditions()); + // END:com.azure.search.documents.generated.skillsetscreateorupdate.searchservicecreateorupdateskillset + } +} diff --git a/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/generated/SearchServiceCreateOrUpdateSynonymMap.java b/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/generated/SearchServiceCreateOrUpdateSynonymMap.java new file mode 100644 index 000000000000..74af550e44e6 --- /dev/null +++ b/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/generated/SearchServiceCreateOrUpdateSynonymMap.java @@ -0,0 +1,32 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.search.documents.generated; + +import com.azure.core.http.MatchConditions; +import com.azure.identity.DefaultAzureCredentialBuilder; +import com.azure.search.documents.SearchClientBuilder; +import com.azure.search.documents.SynonymMapsClient; +import com.azure.search.documents.models.AzureActiveDirectoryApplicationCredentials; +import com.azure.search.documents.models.SearchResourceEncryptionKey; +import com.azure.search.documents.models.SynonymMap; + +public class SearchServiceCreateOrUpdateSynonymMap { + public static void main(String[] args) { + SynonymMapsClient synonymMapsClient + = new SearchClientBuilder().credential(new DefaultAzureCredentialBuilder().build()) + .endpoint("https://previewexampleservice.search.windows.net") + .buildSynonymMapsClient(); + // BEGIN:com.azure.search.documents.generated.synonymmapscreateorupdate.searchservicecreateorupdatesynonymmap + SynonymMap response = synonymMapsClient.createOrUpdate("mysynonymmap", + new SynonymMap("mysynonymmap", "United States, United States of America, USA\nWashington, Wash. => WA") + .setEncryptionKey(new SearchResourceEncryptionKey("fakeTokenPlaceholder", "fakeTokenPlaceholder") + .setKeyVersion("fakeTokenPlaceholder") + .setAccessCredentials( + new AzureActiveDirectoryApplicationCredentials("00000000-0000-0000-0000-000000000000") + .setApplicationSecret("fakeTokenPlaceholder"))), + new MatchConditions()); + // END:com.azure.search.documents.generated.synonymmapscreateorupdate.searchservicecreateorupdatesynonymmap + } +} diff --git a/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/generated/SearchServiceCreateSkillset.java b/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/generated/SearchServiceCreateSkillset.java new file mode 100644 index 000000000000..db6858c7a668 --- /dev/null +++ b/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/generated/SearchServiceCreateSkillset.java @@ -0,0 +1,86 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.search.documents.generated; + +import com.azure.identity.DefaultAzureCredentialBuilder; +import com.azure.search.documents.SearchClientBuilder; +import com.azure.search.documents.SkillsetsClient; +import com.azure.search.documents.models.AIServicesAccountKey; +import com.azure.search.documents.models.AzureActiveDirectoryApplicationCredentials; +import com.azure.search.documents.models.AzureOpenAITokenizerParameters; +import com.azure.search.documents.models.DocumentIntelligenceLayoutSkill; +import com.azure.search.documents.models.DocumentIntelligenceLayoutSkillMarkdownHeaderDepth; +import com.azure.search.documents.models.DocumentIntelligenceLayoutSkillOutputMode; +import com.azure.search.documents.models.InputFieldMappingEntry; +import com.azure.search.documents.models.KeyPhraseExtractionSkill; +import com.azure.search.documents.models.LanguageDetectionSkill; +import com.azure.search.documents.models.OutputFieldMappingEntry; +import com.azure.search.documents.models.SearchIndexerSkillset; +import com.azure.search.documents.models.SearchResourceEncryptionKey; +import com.azure.search.documents.models.SplitSkill; +import com.azure.search.documents.models.SplitSkillEncoderModelName; +import com.azure.search.documents.models.SplitSkillUnit; +import com.azure.search.documents.models.TextSplitMode; +import com.azure.search.documents.models.WebApiSkill; +import java.time.Duration; +import java.util.Arrays; + +public class SearchServiceCreateSkillset { + public static void main(String[] args) { + SkillsetsClient skillsetsClient + = new SearchClientBuilder().credential(new DefaultAzureCredentialBuilder().build()) + .endpoint("https://previewexampleservice.search.windows.net") + .buildSkillsetsClient(); + // BEGIN:com.azure.search.documents.generated.skillsetscreate.searchservicecreateskillset + SearchIndexerSkillset response = skillsetsClient.create(new SearchIndexerSkillset("tempskillset", + Arrays.asList( + new LanguageDetectionSkill( + Arrays.asList(new InputFieldMappingEntry("text").setSource("/document/content"), + new InputFieldMappingEntry("countryHint").setSource("/document/countryHint")), + Arrays.asList(new OutputFieldMappingEntry("languageCode").setTargetName("languageCode"))) + .setName("skill2"), + new SplitSkill( + Arrays.asList(new InputFieldMappingEntry("text").setSource("/document/content"), + new InputFieldMappingEntry("languageCode").setSource("/document/languageCode")), + Arrays.asList(new OutputFieldMappingEntry("textItems").setTargetName("pages"))).setName("skill3") + .setTextSplitMode(TextSplitMode.PAGES) + .setMaximumPageLength(4000) + .setUnit(SplitSkillUnit.AZURE_OPEN_AITOKENS) + .setAzureOpenAITokenizerParameters(new AzureOpenAITokenizerParameters() + .setEncoderModelName(SplitSkillEncoderModelName.CL100K_BASE) + .setAllowedSpecialTokens(Arrays.asList("[START]", "[END]"))), + new KeyPhraseExtractionSkill( + Arrays.asList(new InputFieldMappingEntry("text").setSource("/document/content"), + new InputFieldMappingEntry("languageCode").setSource("/document/languageCode")), + Arrays.asList(new OutputFieldMappingEntry("keyPhrases").setTargetName("keyPhrases"))) + .setName("skill4") + .setContext("/document/pages/*"), + new WebApiSkill( + Arrays.asList(new InputFieldMappingEntry("text").setSource("/document/content"), + new InputFieldMappingEntry("languageCode").setSource("/document/languageCode")), + Arrays.asList(new OutputFieldMappingEntry("customresult").setTargetName("result")), + "https://contoso.example.org/").setName("skill5") + .setHttpMethod("POST") + .setTimeout(Duration.parse("PT5S")), + new DocumentIntelligenceLayoutSkill( + Arrays.asList(new InputFieldMappingEntry("file_data").setSource("/document/content")), + Arrays.asList(new OutputFieldMappingEntry("markdown_document").setTargetName("markdown_document"))) + .setName("docIntelligenceLayoutSkill") + .setContext("/document") + .setOutputMode(DocumentIntelligenceLayoutSkillOutputMode.ONE_TO_MANY) + .setMarkdownHeaderDepth(DocumentIntelligenceLayoutSkillMarkdownHeaderDepth.H3))) + .setDescription("Skillset for extracting entities and more") + .setCognitiveServicesAccount(new AIServicesAccountKey("fakeTokenPlaceholder", + "https://mySubdomainName.cognitiveservices.azure.com").setDescription( + "Description of the Azure AI service resource attached to a skillset")) + .setEncryptionKey( + new SearchResourceEncryptionKey("fakeTokenPlaceholder", "fakeTokenPlaceholder") + .setKeyVersion("fakeTokenPlaceholder") + .setAccessCredentials(new AzureActiveDirectoryApplicationCredentials( + "00000000-0000-0000-0000-000000000000") + .setApplicationSecret("fakeTokenPlaceholder")))); + // END:com.azure.search.documents.generated.skillsetscreate.searchservicecreateskillset + } +} diff --git a/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/generated/SearchServiceCreateSynonymMap.java b/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/generated/SearchServiceCreateSynonymMap.java new file mode 100644 index 000000000000..36ab69632744 --- /dev/null +++ b/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/generated/SearchServiceCreateSynonymMap.java @@ -0,0 +1,30 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.search.documents.generated; + +import com.azure.identity.DefaultAzureCredentialBuilder; +import com.azure.search.documents.SearchClientBuilder; +import com.azure.search.documents.SynonymMapsClient; +import com.azure.search.documents.models.AzureActiveDirectoryApplicationCredentials; +import com.azure.search.documents.models.SearchResourceEncryptionKey; +import com.azure.search.documents.models.SynonymMap; + +public class SearchServiceCreateSynonymMap { + public static void main(String[] args) { + SynonymMapsClient synonymMapsClient + = new SearchClientBuilder().credential(new DefaultAzureCredentialBuilder().build()) + .endpoint("https://previewexampleservice.search.windows.net") + .buildSynonymMapsClient(); + // BEGIN:com.azure.search.documents.generated.synonymmapscreate.searchservicecreatesynonymmap + SynonymMap response = synonymMapsClient.create( + new SynonymMap("tempsynonymmap", "United States, United States of America, USA\nWashington, Wash. => WA") + .setEncryptionKey(new SearchResourceEncryptionKey("fakeTokenPlaceholder", "fakeTokenPlaceholder") + .setKeyVersion("fakeTokenPlaceholder") + .setAccessCredentials( + new AzureActiveDirectoryApplicationCredentials("00000000-0000-0000-0000-000000000000") + .setApplicationSecret("fakeTokenPlaceholder")))); + // END:com.azure.search.documents.generated.synonymmapscreate.searchservicecreatesynonymmap + } +} diff --git a/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/generated/SearchServiceDeleteAlias.java b/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/generated/SearchServiceDeleteAlias.java new file mode 100644 index 000000000000..bec95c29825b --- /dev/null +++ b/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/generated/SearchServiceDeleteAlias.java @@ -0,0 +1,21 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.search.documents.generated; + +import com.azure.core.http.MatchConditions; +import com.azure.identity.DefaultAzureCredentialBuilder; +import com.azure.search.documents.AliasesClient; +import com.azure.search.documents.SearchClientBuilder; + +public class SearchServiceDeleteAlias { + public static void main(String[] args) { + AliasesClient aliasesClient = new SearchClientBuilder().credential(new DefaultAzureCredentialBuilder().build()) + .endpoint("https://previewexampleservice.search.windows.net") + .buildAliasesClient(); + // BEGIN:com.azure.search.documents.generated.aliasesdelete.searchservicedeletealias + aliasesClient.delete("tempalias", new MatchConditions()); + // END:com.azure.search.documents.generated.aliasesdelete.searchservicedeletealias + } +} diff --git a/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/generated/SearchServiceDeleteDataSource.java b/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/generated/SearchServiceDeleteDataSource.java new file mode 100644 index 000000000000..2727137c1769 --- /dev/null +++ b/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/generated/SearchServiceDeleteDataSource.java @@ -0,0 +1,22 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.search.documents.generated; + +import com.azure.core.http.MatchConditions; +import com.azure.identity.DefaultAzureCredentialBuilder; +import com.azure.search.documents.DataSourcesClient; +import com.azure.search.documents.SearchClientBuilder; + +public class SearchServiceDeleteDataSource { + public static void main(String[] args) { + DataSourcesClient dataSourcesClient + = new SearchClientBuilder().credential(new DefaultAzureCredentialBuilder().build()) + .endpoint("https://previewexampleservice.search.windows.net") + .buildDataSourcesClient(); + // BEGIN:com.azure.search.documents.generated.datasourcesdelete.searchservicedeletedatasource + dataSourcesClient.delete("tempdatasource", new MatchConditions()); + // END:com.azure.search.documents.generated.datasourcesdelete.searchservicedeletedatasource + } +} diff --git a/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/generated/SearchServiceDeleteIndex.java b/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/generated/SearchServiceDeleteIndex.java new file mode 100644 index 000000000000..ffec3626d585 --- /dev/null +++ b/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/generated/SearchServiceDeleteIndex.java @@ -0,0 +1,21 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.search.documents.generated; + +import com.azure.core.http.MatchConditions; +import com.azure.identity.DefaultAzureCredentialBuilder; +import com.azure.search.documents.IndexesClient; +import com.azure.search.documents.SearchClientBuilder; + +public class SearchServiceDeleteIndex { + public static void main(String[] args) { + IndexesClient indexesClient = new SearchClientBuilder().credential(new DefaultAzureCredentialBuilder().build()) + .endpoint("https://previewexampleservice.search.windows.net") + .buildIndexesClient(); + // BEGIN:com.azure.search.documents.generated.indexesdelete.searchservicedeleteindex + indexesClient.delete("temp-preview-test", new MatchConditions()); + // END:com.azure.search.documents.generated.indexesdelete.searchservicedeleteindex + } +} diff --git a/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/generated/SearchServiceDeleteIndexer.java b/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/generated/SearchServiceDeleteIndexer.java new file mode 100644 index 000000000000..f90cc7037d8b --- /dev/null +++ b/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/generated/SearchServiceDeleteIndexer.java @@ -0,0 +1,22 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.search.documents.generated; + +import com.azure.core.http.MatchConditions; +import com.azure.identity.DefaultAzureCredentialBuilder; +import com.azure.search.documents.IndexersClient; +import com.azure.search.documents.SearchClientBuilder; + +public class SearchServiceDeleteIndexer { + public static void main(String[] args) { + IndexersClient indexersClient + = new SearchClientBuilder().credential(new DefaultAzureCredentialBuilder().build()) + .endpoint("https://previewexampleservice.search.windows.net") + .buildIndexersClient(); + // BEGIN:com.azure.search.documents.generated.indexersdelete.searchservicedeleteindexer + indexersClient.delete("tempindexer", new MatchConditions()); + // END:com.azure.search.documents.generated.indexersdelete.searchservicedeleteindexer + } +} diff --git a/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/generated/SearchServiceDeleteSkillset.java b/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/generated/SearchServiceDeleteSkillset.java new file mode 100644 index 000000000000..ac2030bd5fbb --- /dev/null +++ b/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/generated/SearchServiceDeleteSkillset.java @@ -0,0 +1,22 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.search.documents.generated; + +import com.azure.core.http.MatchConditions; +import com.azure.identity.DefaultAzureCredentialBuilder; +import com.azure.search.documents.SearchClientBuilder; +import com.azure.search.documents.SkillsetsClient; + +public class SearchServiceDeleteSkillset { + public static void main(String[] args) { + SkillsetsClient skillsetsClient + = new SearchClientBuilder().credential(new DefaultAzureCredentialBuilder().build()) + .endpoint("https://previewexampleservice.search.windows.net") + .buildSkillsetsClient(); + // BEGIN:com.azure.search.documents.generated.skillsetsdelete.searchservicedeleteskillset + skillsetsClient.delete("tempskillset", new MatchConditions()); + // END:com.azure.search.documents.generated.skillsetsdelete.searchservicedeleteskillset + } +} diff --git a/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/generated/SearchServiceDeleteSynonymMap.java b/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/generated/SearchServiceDeleteSynonymMap.java new file mode 100644 index 000000000000..2341ffdb7440 --- /dev/null +++ b/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/generated/SearchServiceDeleteSynonymMap.java @@ -0,0 +1,22 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.search.documents.generated; + +import com.azure.core.http.MatchConditions; +import com.azure.identity.DefaultAzureCredentialBuilder; +import com.azure.search.documents.SearchClientBuilder; +import com.azure.search.documents.SynonymMapsClient; + +public class SearchServiceDeleteSynonymMap { + public static void main(String[] args) { + SynonymMapsClient synonymMapsClient + = new SearchClientBuilder().credential(new DefaultAzureCredentialBuilder().build()) + .endpoint("https://previewexampleservice.search.windows.net") + .buildSynonymMapsClient(); + // BEGIN:com.azure.search.documents.generated.synonymmapsdelete.searchservicedeletesynonymmap + synonymMapsClient.delete("tempsynonymmap", new MatchConditions()); + // END:com.azure.search.documents.generated.synonymmapsdelete.searchservicedeletesynonymmap + } +} diff --git a/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/generated/SearchServiceGetAlias.java b/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/generated/SearchServiceGetAlias.java new file mode 100644 index 000000000000..361d1a6774f7 --- /dev/null +++ b/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/generated/SearchServiceGetAlias.java @@ -0,0 +1,21 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.search.documents.generated; + +import com.azure.identity.DefaultAzureCredentialBuilder; +import com.azure.search.documents.AliasesClient; +import com.azure.search.documents.SearchClientBuilder; +import com.azure.search.documents.models.SearchAlias; + +public class SearchServiceGetAlias { + public static void main(String[] args) { + AliasesClient aliasesClient = new SearchClientBuilder().credential(new DefaultAzureCredentialBuilder().build()) + .endpoint("https://previewexampleservice.search.windows.net") + .buildAliasesClient(); + // BEGIN:com.azure.search.documents.generated.aliasesget.searchservicegetalias + SearchAlias response = aliasesClient.get("myalias"); + // END:com.azure.search.documents.generated.aliasesget.searchservicegetalias + } +} diff --git a/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/generated/SearchServiceGetDataSource.java b/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/generated/SearchServiceGetDataSource.java new file mode 100644 index 000000000000..450438a3554b --- /dev/null +++ b/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/generated/SearchServiceGetDataSource.java @@ -0,0 +1,22 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.search.documents.generated; + +import com.azure.identity.DefaultAzureCredentialBuilder; +import com.azure.search.documents.DataSourcesClient; +import com.azure.search.documents.SearchClientBuilder; +import com.azure.search.documents.models.SearchIndexerDataSource; + +public class SearchServiceGetDataSource { + public static void main(String[] args) { + DataSourcesClient dataSourcesClient + = new SearchClientBuilder().credential(new DefaultAzureCredentialBuilder().build()) + .endpoint("https://previewexampleservice.search.windows.net") + .buildDataSourcesClient(); + // BEGIN:com.azure.search.documents.generated.datasourcesget.searchservicegetdatasource + SearchIndexerDataSource response = dataSourcesClient.get("mydocdbdatasource"); + // END:com.azure.search.documents.generated.datasourcesget.searchservicegetdatasource + } +} diff --git a/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/generated/SearchServiceGetIndex.java b/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/generated/SearchServiceGetIndex.java new file mode 100644 index 000000000000..09b9a9826cc7 --- /dev/null +++ b/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/generated/SearchServiceGetIndex.java @@ -0,0 +1,21 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.search.documents.generated; + +import com.azure.identity.DefaultAzureCredentialBuilder; +import com.azure.search.documents.IndexesClient; +import com.azure.search.documents.SearchClientBuilder; +import com.azure.search.documents.models.SearchIndex; + +public class SearchServiceGetIndex { + public static void main(String[] args) { + IndexesClient indexesClient = new SearchClientBuilder().credential(new DefaultAzureCredentialBuilder().build()) + .endpoint("https://previewexampleservice.search.windows.net") + .buildIndexesClient(); + // BEGIN:com.azure.search.documents.generated.indexesget.searchservicegetindex + SearchIndex response = indexesClient.get("preview-test"); + // END:com.azure.search.documents.generated.indexesget.searchservicegetindex + } +} diff --git a/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/generated/SearchServiceGetIndexStatistics.java b/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/generated/SearchServiceGetIndexStatistics.java new file mode 100644 index 000000000000..0a69ec650d41 --- /dev/null +++ b/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/generated/SearchServiceGetIndexStatistics.java @@ -0,0 +1,21 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.search.documents.generated; + +import com.azure.identity.DefaultAzureCredentialBuilder; +import com.azure.search.documents.IndexesClient; +import com.azure.search.documents.SearchClientBuilder; +import com.azure.search.documents.models.GetIndexStatisticsResult; + +public class SearchServiceGetIndexStatistics { + public static void main(String[] args) { + IndexesClient indexesClient = new SearchClientBuilder().credential(new DefaultAzureCredentialBuilder().build()) + .endpoint("https://previewexampleservice.search.windows.net") + .buildIndexesClient(); + // BEGIN:com.azure.search.documents.generated.indexesgetstatistics.searchservicegetindexstatistics + GetIndexStatisticsResult response = indexesClient.getStatistics("preview-test"); + // END:com.azure.search.documents.generated.indexesgetstatistics.searchservicegetindexstatistics + } +} diff --git a/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/generated/SearchServiceGetIndexStatsSummary.java b/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/generated/SearchServiceGetIndexStatsSummary.java new file mode 100644 index 000000000000..ca343f375f30 --- /dev/null +++ b/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/generated/SearchServiceGetIndexStatsSummary.java @@ -0,0 +1,22 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.search.documents.generated; + +import com.azure.core.http.rest.PagedIterable; +import com.azure.identity.DefaultAzureCredentialBuilder; +import com.azure.search.documents.SearchClient; +import com.azure.search.documents.SearchClientBuilder; +import com.azure.search.documents.models.IndexStatisticsSummary; + +public class SearchServiceGetIndexStatsSummary { + public static void main(String[] args) { + SearchClient searchClient = new SearchClientBuilder().credential(new DefaultAzureCredentialBuilder().build()) + .endpoint("https://previewexampleservice.search.windows.net") + .buildClient(); + // BEGIN:com.azure.search.documents.generated.getindexstatssummary.searchservicegetindexstatssummary + PagedIterable response = searchClient.getIndexStatsSummary(); + // END:com.azure.search.documents.generated.getindexstatssummary.searchservicegetindexstatssummary + } +} diff --git a/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/generated/SearchServiceGetIndexer.java b/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/generated/SearchServiceGetIndexer.java new file mode 100644 index 000000000000..54112433d2fa --- /dev/null +++ b/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/generated/SearchServiceGetIndexer.java @@ -0,0 +1,22 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.search.documents.generated; + +import com.azure.identity.DefaultAzureCredentialBuilder; +import com.azure.search.documents.IndexersClient; +import com.azure.search.documents.SearchClientBuilder; +import com.azure.search.documents.models.SearchIndexer; + +public class SearchServiceGetIndexer { + public static void main(String[] args) { + IndexersClient indexersClient + = new SearchClientBuilder().credential(new DefaultAzureCredentialBuilder().build()) + .endpoint("https://previewexampleservice.search.windows.net") + .buildIndexersClient(); + // BEGIN:com.azure.search.documents.generated.indexersget.searchservicegetindexer + SearchIndexer response = indexersClient.get("myindexer"); + // END:com.azure.search.documents.generated.indexersget.searchservicegetindexer + } +} diff --git a/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/generated/SearchServiceGetIndexerStatus.java b/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/generated/SearchServiceGetIndexerStatus.java new file mode 100644 index 000000000000..5ef8849421ef --- /dev/null +++ b/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/generated/SearchServiceGetIndexerStatus.java @@ -0,0 +1,22 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.search.documents.generated; + +import com.azure.identity.DefaultAzureCredentialBuilder; +import com.azure.search.documents.IndexersClient; +import com.azure.search.documents.SearchClientBuilder; +import com.azure.search.documents.models.SearchIndexerStatus; + +public class SearchServiceGetIndexerStatus { + public static void main(String[] args) { + IndexersClient indexersClient + = new SearchClientBuilder().credential(new DefaultAzureCredentialBuilder().build()) + .endpoint("https://myservice.search.windows.net") + .buildIndexersClient(); + // BEGIN:com.azure.search.documents.generated.indexersgetstatus.searchservicegetindexerstatus + SearchIndexerStatus response = indexersClient.getStatus("myindexer"); + // END:com.azure.search.documents.generated.indexersgetstatus.searchservicegetindexerstatus + } +} diff --git a/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/generated/SearchServiceGetServiceStatistics.java b/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/generated/SearchServiceGetServiceStatistics.java new file mode 100644 index 000000000000..1855d40fda7a --- /dev/null +++ b/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/generated/SearchServiceGetServiceStatistics.java @@ -0,0 +1,25 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.search.documents.generated; + +import com.azure.core.http.rest.RequestOptions; +import com.azure.core.http.rest.Response; +import com.azure.core.util.BinaryData; +import com.azure.identity.DefaultAzureCredentialBuilder; +import com.azure.search.documents.DataSourcesClient; +import com.azure.search.documents.SearchClientBuilder; + +public class SearchServiceGetServiceStatistics { + public static void main(String[] args) { + DataSourcesClient dataSourcesClient + = new SearchClientBuilder().credential(new DefaultAzureCredentialBuilder().build()) + .endpoint("https://previewexampleservice.search.windows.net") + .buildDataSourcesClient(); + // BEGIN:com.azure.search.documents.generated.getservicestatistics.searchservicegetservicestatistics + RequestOptions requestOptions = new RequestOptions(); + Response response = dataSourcesClient.getServiceStatisticsWithResponse(requestOptions); + // END:com.azure.search.documents.generated.getservicestatistics.searchservicegetservicestatistics + } +} diff --git a/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/generated/SearchServiceGetSkillset.java b/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/generated/SearchServiceGetSkillset.java new file mode 100644 index 000000000000..afbb9027201d --- /dev/null +++ b/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/generated/SearchServiceGetSkillset.java @@ -0,0 +1,22 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.search.documents.generated; + +import com.azure.identity.DefaultAzureCredentialBuilder; +import com.azure.search.documents.SearchClientBuilder; +import com.azure.search.documents.SkillsetsClient; +import com.azure.search.documents.models.SearchIndexerSkillset; + +public class SearchServiceGetSkillset { + public static void main(String[] args) { + SkillsetsClient skillsetsClient + = new SearchClientBuilder().credential(new DefaultAzureCredentialBuilder().build()) + .endpoint("https://previewexampleservice.search.windows.net") + .buildSkillsetsClient(); + // BEGIN:com.azure.search.documents.generated.skillsetsget.searchservicegetskillset + SearchIndexerSkillset response = skillsetsClient.get("myskillset"); + // END:com.azure.search.documents.generated.skillsetsget.searchservicegetskillset + } +} diff --git a/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/generated/SearchServiceGetSynonymMap.java b/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/generated/SearchServiceGetSynonymMap.java new file mode 100644 index 000000000000..a28398dd7dff --- /dev/null +++ b/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/generated/SearchServiceGetSynonymMap.java @@ -0,0 +1,22 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.search.documents.generated; + +import com.azure.identity.DefaultAzureCredentialBuilder; +import com.azure.search.documents.SearchClientBuilder; +import com.azure.search.documents.SynonymMapsClient; +import com.azure.search.documents.models.SynonymMap; + +public class SearchServiceGetSynonymMap { + public static void main(String[] args) { + SynonymMapsClient synonymMapsClient + = new SearchClientBuilder().credential(new DefaultAzureCredentialBuilder().build()) + .endpoint("https://previewexampleservice.search.windows.net") + .buildSynonymMapsClient(); + // BEGIN:com.azure.search.documents.generated.synonymmapsget.searchservicegetsynonymmap + SynonymMap response = synonymMapsClient.get("mysynonymmap"); + // END:com.azure.search.documents.generated.synonymmapsget.searchservicegetsynonymmap + } +} diff --git a/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/generated/SearchServiceIndexAnalyze.java b/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/generated/SearchServiceIndexAnalyze.java new file mode 100644 index 000000000000..e6b75424674c --- /dev/null +++ b/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/generated/SearchServiceIndexAnalyze.java @@ -0,0 +1,24 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.search.documents.generated; + +import com.azure.identity.DefaultAzureCredentialBuilder; +import com.azure.search.documents.IndexesClient; +import com.azure.search.documents.SearchClientBuilder; +import com.azure.search.documents.models.AnalyzeRequest; +import com.azure.search.documents.models.AnalyzeResult; +import com.azure.search.documents.models.LexicalAnalyzerName; + +public class SearchServiceIndexAnalyze { + public static void main(String[] args) { + IndexesClient indexesClient = new SearchClientBuilder().credential(new DefaultAzureCredentialBuilder().build()) + .endpoint("https://previewexampleservice.search.windows.net") + .buildIndexesClient(); + // BEGIN:com.azure.search.documents.generated.indexesanalyze.searchserviceindexanalyze + AnalyzeResult response = indexesClient.analyze("preview-test", + new AnalyzeRequest("Text to analyze").setAnalyzer(LexicalAnalyzerName.AR_LUCENE)); + // END:com.azure.search.documents.generated.indexesanalyze.searchserviceindexanalyze + } +} diff --git a/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/generated/SearchServiceListAliases.java b/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/generated/SearchServiceListAliases.java new file mode 100644 index 000000000000..f04e01e75862 --- /dev/null +++ b/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/generated/SearchServiceListAliases.java @@ -0,0 +1,22 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.search.documents.generated; + +import com.azure.core.http.rest.PagedIterable; +import com.azure.identity.DefaultAzureCredentialBuilder; +import com.azure.search.documents.AliasesClient; +import com.azure.search.documents.SearchClientBuilder; +import com.azure.search.documents.models.SearchAlias; + +public class SearchServiceListAliases { + public static void main(String[] args) { + AliasesClient aliasesClient = new SearchClientBuilder().credential(new DefaultAzureCredentialBuilder().build()) + .endpoint("https://previewexampleservice.search.windows.net") + .buildAliasesClient(); + // BEGIN:com.azure.search.documents.generated.aliaseslist.searchservicelistaliases + PagedIterable response = aliasesClient.list(); + // END:com.azure.search.documents.generated.aliaseslist.searchservicelistaliases + } +} diff --git a/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/generated/SearchServiceListDataSources.java b/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/generated/SearchServiceListDataSources.java new file mode 100644 index 000000000000..fcbef6e05769 --- /dev/null +++ b/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/generated/SearchServiceListDataSources.java @@ -0,0 +1,22 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.search.documents.generated; + +import com.azure.identity.DefaultAzureCredentialBuilder; +import com.azure.search.documents.DataSourcesClient; +import com.azure.search.documents.SearchClientBuilder; +import com.azure.search.documents.models.ListDataSourcesResult; + +public class SearchServiceListDataSources { + public static void main(String[] args) { + DataSourcesClient dataSourcesClient + = new SearchClientBuilder().credential(new DefaultAzureCredentialBuilder().build()) + .endpoint("https://previewexampleservice.search.windows.net") + .buildDataSourcesClient(); + // BEGIN:com.azure.search.documents.generated.datasourceslist.searchservicelistdatasources + ListDataSourcesResult response = dataSourcesClient.list(null); + // END:com.azure.search.documents.generated.datasourceslist.searchservicelistdatasources + } +} diff --git a/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/generated/SearchServiceListIndexers.java b/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/generated/SearchServiceListIndexers.java new file mode 100644 index 000000000000..a0a8f2b83d5f --- /dev/null +++ b/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/generated/SearchServiceListIndexers.java @@ -0,0 +1,22 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.search.documents.generated; + +import com.azure.identity.DefaultAzureCredentialBuilder; +import com.azure.search.documents.IndexersClient; +import com.azure.search.documents.SearchClientBuilder; +import com.azure.search.documents.models.ListIndexersResult; + +public class SearchServiceListIndexers { + public static void main(String[] args) { + IndexersClient indexersClient + = new SearchClientBuilder().credential(new DefaultAzureCredentialBuilder().build()) + .endpoint("https://previewexampleservice.search.windows.net") + .buildIndexersClient(); + // BEGIN:com.azure.search.documents.generated.indexerslist.searchservicelistindexers + ListIndexersResult response = indexersClient.list("*"); + // END:com.azure.search.documents.generated.indexerslist.searchservicelistindexers + } +} diff --git a/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/generated/SearchServiceListIndexes.java b/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/generated/SearchServiceListIndexes.java new file mode 100644 index 000000000000..8ab14aa2dfcb --- /dev/null +++ b/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/generated/SearchServiceListIndexes.java @@ -0,0 +1,22 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.search.documents.generated; + +import com.azure.core.http.rest.PagedIterable; +import com.azure.identity.DefaultAzureCredentialBuilder; +import com.azure.search.documents.IndexesClient; +import com.azure.search.documents.SearchClientBuilder; +import com.azure.search.documents.models.SearchIndex; + +public class SearchServiceListIndexes { + public static void main(String[] args) { + IndexesClient indexesClient = new SearchClientBuilder().credential(new DefaultAzureCredentialBuilder().build()) + .endpoint("https://previewexampleservice.search.windows.net") + .buildIndexesClient(); + // BEGIN:com.azure.search.documents.generated.indexeslist.searchservicelistindexes + PagedIterable response = indexesClient.list(null); + // END:com.azure.search.documents.generated.indexeslist.searchservicelistindexes + } +} diff --git a/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/generated/SearchServiceListSkillsets.java b/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/generated/SearchServiceListSkillsets.java new file mode 100644 index 000000000000..72778fff5061 --- /dev/null +++ b/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/generated/SearchServiceListSkillsets.java @@ -0,0 +1,22 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.search.documents.generated; + +import com.azure.identity.DefaultAzureCredentialBuilder; +import com.azure.search.documents.SearchClientBuilder; +import com.azure.search.documents.SkillsetsClient; +import com.azure.search.documents.models.ListSkillsetsResult; + +public class SearchServiceListSkillsets { + public static void main(String[] args) { + SkillsetsClient skillsetsClient + = new SearchClientBuilder().credential(new DefaultAzureCredentialBuilder().build()) + .endpoint("https://previewexampleservice.search.windows.net") + .buildSkillsetsClient(); + // BEGIN:com.azure.search.documents.generated.skillsetslist.searchservicelistskillsets + ListSkillsetsResult response = skillsetsClient.list(null); + // END:com.azure.search.documents.generated.skillsetslist.searchservicelistskillsets + } +} diff --git a/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/generated/SearchServiceListSynonymMaps.java b/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/generated/SearchServiceListSynonymMaps.java new file mode 100644 index 000000000000..73687f9ab3f5 --- /dev/null +++ b/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/generated/SearchServiceListSynonymMaps.java @@ -0,0 +1,22 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.search.documents.generated; + +import com.azure.identity.DefaultAzureCredentialBuilder; +import com.azure.search.documents.SearchClientBuilder; +import com.azure.search.documents.SynonymMapsClient; +import com.azure.search.documents.models.ListSynonymMapsResult; + +public class SearchServiceListSynonymMaps { + public static void main(String[] args) { + SynonymMapsClient synonymMapsClient + = new SearchClientBuilder().credential(new DefaultAzureCredentialBuilder().build()) + .endpoint("https://previewexampleservice.search.windows.net") + .buildSynonymMapsClient(); + // BEGIN:com.azure.search.documents.generated.synonymmapslist.searchservicelistsynonymmaps + ListSynonymMapsResult response = synonymMapsClient.list(null); + // END:com.azure.search.documents.generated.synonymmapslist.searchservicelistsynonymmaps + } +} diff --git a/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/generated/SearchServiceResetDocs.java b/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/generated/SearchServiceResetDocs.java new file mode 100644 index 000000000000..384f23f3e1d4 --- /dev/null +++ b/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/generated/SearchServiceResetDocs.java @@ -0,0 +1,24 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.search.documents.generated; + +import com.azure.identity.DefaultAzureCredentialBuilder; +import com.azure.search.documents.IndexersClient; +import com.azure.search.documents.SearchClientBuilder; +import com.azure.search.documents.models.DocumentKeysOrIds; +import java.util.Arrays; + +public class SearchServiceResetDocs { + public static void main(String[] args) { + IndexersClient indexersClient + = new SearchClientBuilder().credential(new DefaultAzureCredentialBuilder().build()) + .endpoint("https://previewexampleservice.search.windows.net") + .buildIndexersClient(); + // BEGIN:com.azure.search.documents.generated.indexersresetdocs.searchserviceresetdocs + indexersClient.resetDocs("myindexer", true, + new DocumentKeysOrIds().setDocumentKeys(Arrays.asList("1", "2", "3"))); + // END:com.azure.search.documents.generated.indexersresetdocs.searchserviceresetdocs + } +} diff --git a/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/generated/SearchServiceResetIndexer.java b/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/generated/SearchServiceResetIndexer.java new file mode 100644 index 000000000000..218111cc43ee --- /dev/null +++ b/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/generated/SearchServiceResetIndexer.java @@ -0,0 +1,21 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.search.documents.generated; + +import com.azure.identity.DefaultAzureCredentialBuilder; +import com.azure.search.documents.IndexersClient; +import com.azure.search.documents.SearchClientBuilder; + +public class SearchServiceResetIndexer { + public static void main(String[] args) { + IndexersClient indexersClient + = new SearchClientBuilder().credential(new DefaultAzureCredentialBuilder().build()) + .endpoint("https://previewexampleservice.search.windows.net") + .buildIndexersClient(); + // BEGIN:com.azure.search.documents.generated.indexersreset.searchserviceresetindexer + indexersClient.reset("myindexer"); + // END:com.azure.search.documents.generated.indexersreset.searchserviceresetindexer + } +} diff --git a/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/generated/SearchServiceResetSkills.java b/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/generated/SearchServiceResetSkills.java new file mode 100644 index 000000000000..d89b266412a5 --- /dev/null +++ b/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/generated/SearchServiceResetSkills.java @@ -0,0 +1,24 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.search.documents.generated; + +import com.azure.identity.DefaultAzureCredentialBuilder; +import com.azure.search.documents.SearchClientBuilder; +import com.azure.search.documents.SkillsetsClient; +import com.azure.search.documents.models.SkillNames; +import java.util.Arrays; + +public class SearchServiceResetSkills { + public static void main(String[] args) { + SkillsetsClient skillsetsClient + = new SearchClientBuilder().credential(new DefaultAzureCredentialBuilder().build()) + .endpoint("https://previewexampleservice.search.windows.net") + .buildSkillsetsClient(); + // BEGIN:com.azure.search.documents.generated.skillsetsresetskills.searchserviceresetskills + skillsetsClient.resetSkills("myskillset", + new SkillNames().setSkillNames(Arrays.asList("skill2", "skill3", "skill4"))); + // END:com.azure.search.documents.generated.skillsetsresetskills.searchserviceresetskills + } +} diff --git a/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/generated/SearchServiceRunIndexer.java b/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/generated/SearchServiceRunIndexer.java new file mode 100644 index 000000000000..66d42c934480 --- /dev/null +++ b/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/generated/SearchServiceRunIndexer.java @@ -0,0 +1,21 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.search.documents.generated; + +import com.azure.identity.DefaultAzureCredentialBuilder; +import com.azure.search.documents.IndexersClient; +import com.azure.search.documents.SearchClientBuilder; + +public class SearchServiceRunIndexer { + public static void main(String[] args) { + IndexersClient indexersClient + = new SearchClientBuilder().credential(new DefaultAzureCredentialBuilder().build()) + .endpoint("https://previewexampleservice.search.windows.net") + .buildIndexersClient(); + // BEGIN:com.azure.search.documents.generated.indexersrun.searchservicerunindexer + indexersClient.run("myindexer"); + // END:com.azure.search.documents.generated.indexersrun.searchservicerunindexer + } +} diff --git a/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/indexes/CreateIndexExample.java b/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/indexes/CreateIndexExample.java deleted file mode 100644 index 6de3b143f9dd..000000000000 --- a/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/indexes/CreateIndexExample.java +++ /dev/null @@ -1,83 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.search.documents.indexes; - -import com.azure.core.credential.AzureKeyCredential; -import com.azure.core.util.Configuration; -import com.azure.search.documents.indexes.models.LexicalAnalyzerName; -import com.azure.search.documents.indexes.models.SearchField; -import com.azure.search.documents.indexes.models.SearchFieldDataType; -import com.azure.search.documents.indexes.models.SearchIndex; - -import java.util.Arrays; - -public class CreateIndexExample { - /** - * From the Azure portal, get your Azure AI Search service name and API key and populate ADMIN_KEY and - * SEARCH_SERVICE_NAME. - */ - private static final String ENDPOINT = Configuration.getGlobalConfiguration().get("AZURE_COGNITIVE_SEARCH_ENDPOINT"); - private static final String ADMIN_KEY = Configuration.getGlobalConfiguration().get("AZURE_COGNITIVE_SEARCH_API_KEY"); - - public static void main(String[] args) { - // Create the SearchIndex client. - SearchIndexClient client = new SearchIndexClientBuilder() - .endpoint(ENDPOINT) - .credential(new AzureKeyCredential(ADMIN_KEY)) - .buildClient(); - - // Configure the index using SearchFields - String indexName = "hotels"; - SearchIndex newIndex = new SearchIndex(indexName, Arrays.asList( - new SearchField("hotelId", SearchFieldDataType.STRING) - .setKey(true) - .setFilterable(true) - .setSortable(true), - new SearchField("hotelName", SearchFieldDataType.STRING) - .setSearchable(true) - .setFilterable(true) - .setSortable(true), - new SearchField("description", SearchFieldDataType.STRING) - .setSearchable(true) - .setAnalyzerName(LexicalAnalyzerName.EN_LUCENE), - new SearchField("descriptionFr", SearchFieldDataType.STRING) - .setSearchable(true) - .setAnalyzerName(LexicalAnalyzerName.FR_LUCENE), - new SearchField("tags", SearchFieldDataType.collection(SearchFieldDataType.STRING)) - .setSearchable(true) - .setFilterable(true) - .setFacetable(true), - new SearchField("address", SearchFieldDataType.COMPLEX) - .setFields( - new SearchField("streetAddress", SearchFieldDataType.STRING) - .setSearchable(true), - new SearchField("city", SearchFieldDataType.STRING) - .setFilterable(true) - .setSortable(true) - .setFacetable(true), - new SearchField("stateProvince", SearchFieldDataType.STRING) - .setSearchable(true) - .setFilterable(true) - .setSortable(true) - .setFacetable(true), - new SearchField("country", SearchFieldDataType.STRING) - .setSearchable(true) - .setSynonymMapNames("synonymMapName") - .setFilterable(true) - .setSortable(true) - .setFacetable(true), - new SearchField("postalCode", SearchFieldDataType.STRING) - .setSearchable(true) - .setFilterable(true) - .setSortable(true) - .setFacetable(true)) - )); - - // Create index. - client.createIndex(newIndex); - - // Cleanup index resource. - client.deleteIndex(indexName); - } -} diff --git a/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/indexes/CreateIndexWithFieldBuilderExample.java b/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/indexes/CreateIndexWithFieldBuilderExample.java deleted file mode 100644 index e8cdf0d211a7..000000000000 --- a/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/indexes/CreateIndexWithFieldBuilderExample.java +++ /dev/null @@ -1,311 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.search.documents.indexes; - -import com.azure.core.credential.AzureKeyCredential; -import com.azure.core.util.Configuration; -import com.azure.search.documents.indexes.models.FieldBuilderOptions; -import com.azure.search.documents.indexes.models.SearchField; -import com.azure.search.documents.indexes.models.SearchFieldDataType; -import com.azure.search.documents.indexes.models.SearchIndex; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; - -public class CreateIndexWithFieldBuilderExample { - /** - * From the Azure portal, get your Azure AI Search service name and API key and populate ADMIN_KEY and - * SEARCH_SERVICE_NAME. - */ - private static final String ENDPOINT = Configuration.getGlobalConfiguration() - .get("AZURE_COGNITIVE_SEARCH_ENDPOINT"); - private static final String ADMIN_KEY = Configuration.getGlobalConfiguration() - .get("AZURE_COGNITIVE_SEARCH_API_KEY"); - - public static void main(String[] args) { - // Create the SearchIndex client. - SearchIndexClient client = new SearchIndexClientBuilder().endpoint(ENDPOINT) - .credential(new AzureKeyCredential(ADMIN_KEY)) - .buildClient(); - - // Use the SearchIndexClient to create SearchFields from your own model that has fields or methods annotated - // with @SimpleField or @SearchableField. - List indexFields = SearchIndexClient.buildSearchFields(Hotel.class, new FieldBuilderOptions()); - String indexName = "hotels"; - List searchFieldList = new ArrayList<>(); - searchFieldList.add( - new SearchField("hotelId", SearchFieldDataType.STRING).setKey(true).setFilterable(true).setSortable(true)); - SearchIndex newIndex = new SearchIndex(indexName, indexFields).setFields(searchFieldList); - // Create index. - client.createIndex(newIndex); - // Cleanup index resource. - client.deleteIndex(indexName); - } - - /** - * A hotel. - */ - public static final class Hotel { - @SimpleField(isKey = true, isFilterable = true, isSortable = true) - private final String hotelId; - - @SearchableField(isFilterable = true, isSortable = true) - private String hotelName; - - @SearchableField(analyzerName = "en.lucene") - private String description; - - @SearchableField(analyzerName = "fr.lucene") - private String descriptionFr; - - @SearchableField(isFilterable = true, isFacetable = true) - private List tags; - - // Complex fields are included automatically in an index if not ignored. - private Address address; - - /** - * Creates a new Hotel object. - * - * @param hotelId The unique identifier of the hotel. - */ - public Hotel(String hotelId) { - this.hotelId = hotelId; - } - - /** - * Gets the unique identifier of the hotel. - * - * @return The unique identifier of the hotel. - */ - public String getHotelId() { - return hotelId; - } - - /** - * Gets the name of the hotel. - * - * @return The name of the hotel. - */ - public String getHotelName() { - return hotelName; - } - - /** - * Sets the name of the hotel. - * - * @param hotelName The name of the hotel. - * @return The updated Hotel object. - */ - public Hotel setHotelName(String hotelName) { - this.hotelName = hotelName; - return this; - } - - /** - * Gets the description for the hotel. - * - * @return The description for the hotel. - */ - public String getDescription() { - return description; - } - - /** - * Sets the description for the hotel. - * - * @param description The description for the hotel. - * @return The updated Hotel object. - */ - public Hotel setDescription(String description) { - this.description = description; - return this; - } - - /** - * Gets the French description for the hotel. - * - * @return The French description for the hotel. - */ - public String getDescriptionFr() { - return descriptionFr; - } - - /** - * Sets the French description for the hotel. - * - * @param descriptionFr The French description for the hotel. - * @return The updated Hotel object. - */ - public Hotel setDescriptionFr(String descriptionFr) { - this.descriptionFr = descriptionFr; - return this; - } - - /** - * Gets the tags for the hotel. - * - * @return The tags for the hotel. - */ - public List getTags() { - return Collections.unmodifiableList(tags); - } - - /** - * Sets the tags for the hotel. - * - * @param tags The tags for the hotel. - * @return The updated Hotel object. - */ - public Hotel setTags(List tags) { - this.tags = new ArrayList<>(tags); - return this; - } - - /** - * Gets the address of the hotel. - * - * @return The address of the hotel. - */ - public Address getAddress() { - return address; - } - - /** - * Sets the address of the hotel. - * - * @param address The address of the hotel. - * @return The updated Hotel object. - */ - public Hotel setAddress(Address address) { - this.address = address; - return this; - } - } - - /** - * An address. - */ - public static final class Address { - @SearchableField - private String streetAddress; - - @SearchableField(isFilterable = true, isSortable = true, isFacetable = true) - private String city; - - @SearchableField(isFilterable = true, isSortable = true, isFacetable = true) - private String stateProvince; - - @SearchableField( - synonymMapNames = { "synonymMapName" }, - isFilterable = true, - isSortable = true, - isFacetable = true) - private String country; - - @SearchableField(isFilterable = true, isSortable = true, isFacetable = true) - private String postalCode; - - /** - * Gets the street address of the address. - * - * @return The street address of the address. - */ - public String getStreetAddress() { - return streetAddress; - } - - /** - * Sets the street address of the address. - * - * @param streetAddress The street address of the address. - * @return The updated Address object. - */ - public Address setStreetAddress(String streetAddress) { - this.streetAddress = streetAddress; - return this; - } - - /** - * Gets the city of the address. - * - * @return The city of the address. - */ - public String getCity() { - return city; - } - - /** - * Sets the city of the address. - * - * @param city The city of the address. - * @return The updated Address object. - */ - public Address setCity(String city) { - this.city = city; - return this; - } - - /** - * Gets the state or province of the address. - * - * @return The state or province of the address. - */ - public String getStateProvince() { - return stateProvince; - } - - /** - * Sets the state or province of the address. - * - * @param stateProvince The state or province of the address. - * @return The updated Address object. - */ - public Address setStateProvince(String stateProvince) { - this.stateProvince = stateProvince; - return this; - } - - /** - * Gets the country of the address. - * - * @return The country of the address. - */ - public String getCountry() { - return country; - } - - /** - * Sets the country of the address. - * - * @param country The country of the address. - * @return The updated Address object. - */ - public Address setCountry(String country) { - this.country = country; - return this; - } - - /** - * Gets the postal code of the address. - * - * @return The postal code of the address. - */ - public String getPostalCode() { - return postalCode; - } - - /** - * Sets the postal code of the address. - * - * @param postalCode The postal code of the address. - * @return The updated Address object. - */ - public Address setPostalCode(String postalCode) { - this.postalCode = postalCode; - return this; - } - } -} diff --git a/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/indexes/CreateIndexerExample.java b/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/indexes/CreateIndexerExample.java deleted file mode 100644 index faeb6f8ea207..000000000000 --- a/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/indexes/CreateIndexerExample.java +++ /dev/null @@ -1,76 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.search.documents.indexes; - -import com.azure.core.credential.AzureKeyCredential; -import com.azure.core.http.rest.Response; -import com.azure.core.util.Configuration; -import com.azure.search.documents.indexes.models.FieldMapping; -import com.azure.search.documents.indexes.models.IndexingParameters; -import com.azure.search.documents.indexes.models.IndexingSchedule; -import com.azure.search.documents.indexes.models.SearchIndexer; - -import java.time.Duration; -import java.util.Collections; -import java.util.List; - -public class CreateIndexerExample { - - /** - * This example shows how to create a new Indexer in a Cognitive Search Service. - *

- * From the Azure portal, get your Azure AI Search service URL and API key, - * and set the values of these environment variables: - */ - private static final String ENDPOINT = Configuration.getGlobalConfiguration().get("AZURE_COGNITIVE_SEARCH_ENDPOINT"); - private static final String ADMIN_KEY = Configuration.getGlobalConfiguration().get("AZURE_COGNITIVE_SEARCH_API_KEY"); - - - private static final String INDEX_NAME = "hotels-sample-index"; - private static final String DATA_SOURCE_NAME = "hotels-sample"; - private static final String INDEXER_NAME = "hotels-indexer-test"; - - public static void main(String[] args) { - SearchIndexerAsyncClient indexerAsyncClient = new SearchIndexerClientBuilder() - .endpoint(ENDPOINT) - .credential(new AzureKeyCredential(ADMIN_KEY)) - .buildAsyncClient(); - - createOrUpdateIndexer(indexerAsyncClient); - } - - private static void createOrUpdateIndexer(SearchIndexerAsyncClient searchIndexerAsyncClient) { - // Create indexer parameters - IndexingParameters indexingParameters = new IndexingParameters() - .setBatchSize(50) - .setMaxFailedItems(10) - .setMaxFailedItemsPerBatch(10); - - // Create field mappings - List fieldMappings = Collections.singletonList(new FieldMapping("id") - .setTargetFieldName("HotelId")); - - // Create schedule - IndexingSchedule indexingSchedule = new IndexingSchedule(Duration.ofHours(12)); - - // Create the indexer - SearchIndexer indexer = new SearchIndexer(INDEXER_NAME, DATA_SOURCE_NAME, INDEX_NAME) - .setParameters(indexingParameters) - .setFieldMappings(fieldMappings) - .setSchedule(indexingSchedule); - - System.out.println(String.format("Creating Indexer: %s", indexer.getName())); - Response response = searchIndexerAsyncClient.createOrUpdateIndexerWithResponse( - indexer, false - ).block(); - - if (response != null) { - System.out.println(String.format("Response code: %s", response.getStatusCode())); - - SearchIndexer createdIndexer = response.getValue(); - System.out.println(String - .format("Created indexer name: %s, ETag: %s", createdIndexer.getName(), createdIndexer.getETag())); - } - } -} diff --git a/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/indexes/CreateSkillsetExample.java b/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/indexes/CreateSkillsetExample.java deleted file mode 100644 index ed5b550e4846..000000000000 --- a/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/indexes/CreateSkillsetExample.java +++ /dev/null @@ -1,118 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.search.documents.indexes; - -import com.azure.core.credential.AzureKeyCredential; -import com.azure.core.util.Configuration; -import com.azure.search.documents.indexes.models.InputFieldMappingEntry; -import com.azure.search.documents.indexes.models.OcrSkill; -import com.azure.search.documents.indexes.models.OutputFieldMappingEntry; -import com.azure.search.documents.indexes.models.SearchIndexerSkill; -import com.azure.search.documents.indexes.models.SearchIndexerSkillset; -import com.azure.search.documents.indexes.models.WebApiSkill; - -import java.util.Arrays; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; - -public class CreateSkillsetExample { - - /** - * From the Azure portal, get your Azure AI Search service URL and API key, - * and set the values of these environment variables: - */ - private static final String ENDPOINT = Configuration.getGlobalConfiguration().get("AZURE_COGNITIVE_SEARCH_ENDPOINT"); - private static final String ADMIN_KEY = Configuration.getGlobalConfiguration().get("AZURE_COGNITIVE_SEARCH_ADMIN_KEY"); - private static final String OCR_SKILLSET_NAME = "ocr-skillset"; - private static final String CUSTOM_SKILLSET_NAME = "custom-skillset"; - - public static void main(String[] args) { - SearchIndexerClient searchIndexerClient = new SearchIndexerClientBuilder() - .endpoint(ENDPOINT) - .credential(new AzureKeyCredential(ADMIN_KEY)) - .buildClient(); - - createOcrSkillset(searchIndexerClient); - createCustomSkillset(searchIndexerClient); - cleanupSkillset(searchIndexerClient); - } - - private static void createOcrSkillset(SearchIndexerClient searchIndexerClient) { - // Sample OCR definition - // https://docs.microsoft.com/azure/search/cognitive-search-skill-ocr#sample-definition - - List inputs = Collections.singletonList( - new InputFieldMappingEntry("image") - .setSource("/document/normalized_images/*") - ); - - List outputs = Arrays.asList( - new OutputFieldMappingEntry("text") - .setTargetName("mytext"), - new OutputFieldMappingEntry("layoutText") - .setTargetName("myLayoutText") - ); - - List skills = Collections.singletonList( - new OcrSkill(inputs, outputs) - .setShouldDetectOrientation(true) - .setDefaultLanguageCode(null) - .setName("myocr") - .setDescription("Extracts text (plain and structured) from image.") - .setContext("/document/normalized_images/*") - ); - - SearchIndexerSkillset skillset = new SearchIndexerSkillset(OCR_SKILLSET_NAME, skills) - .setDescription("Extracts text (plain and structured) from image."); - - System.out.println(String.format("Creating OCR skillset '%s'", skillset.getName())); - - SearchIndexerSkillset createdSkillset = searchIndexerClient.createSkillset(skillset); - - System.out.println("Created OCR skillset"); - System.out.println(String.format("Name: %s", createdSkillset.getName())); - System.out.println(String.format("ETag: %s", createdSkillset.getETag())); - - System.out.println("\n"); - } - - private static void createCustomSkillset(SearchIndexerClient searchIndexerClient) { - HashMap headers = new HashMap<>(); - headers.put("Ocp-Apim-Subscription-Key", "foobar"); - - List inputs = Collections.singletonList( - new InputFieldMappingEntry("text") - .setSource("/document/mytext") - ); - - List outputs = Collections.singletonList( - new OutputFieldMappingEntry("textItems") - .setTargetName("myTextItems") - ); - - SearchIndexerSkill webApiSkill = new WebApiSkill(inputs, outputs, "https://example.com") - .setHttpMethod("POST") // Supports only "POST" and "PUT" HTTP methods - .setHttpHeaders(headers) - .setName("webapi-skill") - .setDescription("A WebApiSkill that can be used to call a custom web api function"); - - SearchIndexerSkillset skillset = new SearchIndexerSkillset(CUSTOM_SKILLSET_NAME, - Collections.singletonList(webApiSkill)) - .setDescription("Skillset for testing custom skillsets"); - - System.out.println(String.format("Creating custom skillset '%s'", skillset.getName())); - - SearchIndexerSkillset createdSkillset = searchIndexerClient.createSkillset(skillset); - - System.out.println("Created custom skillset"); - System.out.println(String.format("Name: %s", createdSkillset.getName())); - System.out.println(String.format("ETag: %s", createdSkillset.getETag())); - } - - private static void cleanupSkillset(SearchIndexerClient searchIndexerClient) { - searchIndexerClient.deleteSkillset(OCR_SKILLSET_NAME); - searchIndexerClient.deleteSkillset(CUSTOM_SKILLSET_NAME); - } -} diff --git a/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/indexes/DataSourceExample.java b/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/indexes/DataSourceExample.java deleted file mode 100644 index f7e7cffd7d5c..000000000000 --- a/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/indexes/DataSourceExample.java +++ /dev/null @@ -1,149 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.search.documents.indexes; - -import com.azure.core.credential.AzureKeyCredential; -import com.azure.core.http.rest.PagedIterable; -import com.azure.core.util.Configuration; -import com.azure.search.documents.indexes.models.DataChangeDetectionPolicy; -import com.azure.search.documents.indexes.models.HighWaterMarkChangeDetectionPolicy; -import com.azure.search.documents.indexes.models.SearchIndexerDataContainer; -import com.azure.search.documents.indexes.models.SearchIndexerDataSourceConnection; -import com.azure.search.documents.indexes.models.SearchIndexerDataSourceType; - -import java.util.Collection; -import java.util.HashSet; -import java.util.UUID; - -/** - * This sample demonstrates how to create an Azure AI Search data source for SQL Server/Azure SQL, - * Azure Cosmos DB, Blob Storage and Table Storage. - * To use it, create the respective databases/storage services and replace their connection strings below. - */ -public class DataSourceExample { - /** - * From the Azure portal, get your Azure AI Search service URL and API key, - * and set the values of these environment variables: - */ - private static final String ENDPOINT = Configuration.getGlobalConfiguration().get("AZURE_COGNITIVE_SEARCH_ENDPOINT"); - private static final String ADMIN_KEY = Configuration.getGlobalConfiguration().get("AZURE_COGNITIVE_SEARCH_ADMIN_KEY"); - private static final String TABLE_STORAGE_CONNECTION_STRING = ""; - private static final String COSMOS_CONNECTION_STRING = ""; - private static final String BLOB_STORAGE_CONNECTION_STRING = ""; - private static final String SQL_CONNECTION_STRING = ""; - - public static void main(String[] args) { - SearchIndexerClient client = new SearchIndexerClientBuilder() - .endpoint(ENDPOINT) - .credential(new AzureKeyCredential(ADMIN_KEY)) - .buildClient(); - - /* - * Store the names of the created data sources so that we can delete them later - * without affecting other resources. - * */ - Collection names = new HashSet<>(); - - names.add(createSqlDataSource(client)); - names.add(createCosmosDataSource(client)); - names.add(createBlobDataSource(client)); - names.add(createTableStorageDataSource(client)); - - /* - * Get all existing data sources; list should include the ones we just created. - * */ - PagedIterable dataSources = client.listDataSourceConnections(); - for (SearchIndexerDataSourceConnection dataSource : dataSources) { - if (names.contains(dataSource.getName())) { - System.out.println(String.format("Found data source %s of type %s", dataSource.getName(), - dataSource.getType().toString())); - } - } - - /* - * Delete the data sources we just created. - * */ - for (String name : names) { - deleteDataSource(client, name); - } - } - - private static void deleteDataSource(SearchIndexerClient client, String dataSourceName) { - try { - client.deleteDataSourceConnection(dataSourceName); - } catch (Exception ex) { - System.err.println(ex.toString()); - } - } - - private static SearchIndexerDataSourceConnection createSampleDatasource(SearchIndexerDataSourceType type, - String connectionString, SearchIndexerDataContainer container, - DataChangeDetectionPolicy dataChangeDetectionPolicy) { - return new SearchIndexerDataSourceConnection(generateDataSourceName(), type, connectionString, container) - .setDataChangeDetectionPolicy(dataChangeDetectionPolicy); - } - - private static String createDataSource( - SearchIndexerClient client, - SearchIndexerDataSourceType type, - String connectionString, - SearchIndexerDataContainer container, - DataChangeDetectionPolicy dataChangeDetectionPolicy) { - - SearchIndexerDataSourceConnection dataSource = createSampleDatasource(type, connectionString, container, - dataChangeDetectionPolicy); - try { - client.createOrUpdateDataSourceConnection(dataSource); - } catch (Exception ex) { - System.err.println(ex.toString()); - } - return dataSource.getName(); - } - - private static String createTableStorageDataSource(SearchIndexerClient client) { - return createDataSource( - client, - SearchIndexerDataSourceType.AZURE_TABLE, - TABLE_STORAGE_CONNECTION_STRING, - new SearchIndexerDataContainer("testtable") // Replace your table name here - .setQuery("PartitionKey eq 'test'"), // Add your query here or remove this if you don't need one - null - ); - } - - private static String createCosmosDataSource(SearchIndexerClient client) { - return createDataSource( - client, - SearchIndexerDataSourceType.COSMOS_DB, - COSMOS_CONNECTION_STRING, - new SearchIndexerDataContainer("testcollection") // Replace your collection name here - .setQuery(null), // Add your query here or remove this if you don't need one - new HighWaterMarkChangeDetectionPolicy("_ts") - ); - } - - private static String createBlobDataSource(SearchIndexerClient client) { - return createDataSource( - client, - SearchIndexerDataSourceType.AZURE_BLOB, - BLOB_STORAGE_CONNECTION_STRING, - new SearchIndexerDataContainer("testcontainer") // Replace your container name here - .setQuery("testfolder"), // Add your folder here or remove this if you want to index all folders within the container - null - ); - } - - private static String createSqlDataSource(SearchIndexerClient client) { - return createDataSource( - client, - SearchIndexerDataSourceType.AZURE_SQL, - SQL_CONNECTION_STRING, - new SearchIndexerDataContainer("testtable"), // Replace your table or view name here - null); // Or new SqlIntegratedChangeTrackingPolicy() if your database has change tracking enabled - } - - private static String generateDataSourceName() { - return "datasource" + UUID.randomUUID().toString(); - } -} diff --git a/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/indexes/LifecycleSetupExample.java b/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/indexes/LifecycleSetupExample.java deleted file mode 100644 index 600375ad4ba8..000000000000 --- a/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/indexes/LifecycleSetupExample.java +++ /dev/null @@ -1,192 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.search.documents.indexes; - -import com.azure.core.credential.AzureKeyCredential; -import com.azure.core.util.Configuration; -import com.azure.search.documents.indexes.models.EntityRecognitionSkill; -import com.azure.search.documents.indexes.models.EntityRecognitionSkillVersion; -import com.azure.search.documents.indexes.models.HighWaterMarkChangeDetectionPolicy; -import com.azure.search.documents.indexes.models.IndexingSchedule; -import com.azure.search.documents.indexes.models.InputFieldMappingEntry; -import com.azure.search.documents.indexes.models.LexicalAnalyzerName; -import com.azure.search.documents.indexes.models.OutputFieldMappingEntry; -import com.azure.search.documents.indexes.models.SearchField; -import com.azure.search.documents.indexes.models.SearchFieldDataType; -import com.azure.search.documents.indexes.models.SearchIndex; -import com.azure.search.documents.indexes.models.SearchIndexer; -import com.azure.search.documents.indexes.models.SearchIndexerDataContainer; -import com.azure.search.documents.indexes.models.SearchIndexerDataSourceConnection; -import com.azure.search.documents.indexes.models.SearchIndexerDataSourceType; -import com.azure.search.documents.indexes.models.SearchIndexerSkill; -import com.azure.search.documents.indexes.models.SearchIndexerSkillset; -import com.azure.search.documents.indexes.models.SearchSuggester; - -import java.time.Duration; -import java.util.Arrays; -import java.util.Collections; -import java.util.List; - -/** - * This scenario assumes an existing search solution and uses a pre-population data source with sample data set For more - * information visit Azure AI Search Sample Data: https://docs.microsoft.com/samples/azure-samples/azure-search-sample-data/azure-search-sample-data/ - */ -public class LifecycleSetupExample { - /** - * From the Azure portal, get your Azure AI Search service URL and API admin key, and set the values of these - * environment variables: - */ - private static final String ENDPOINT = Configuration.getGlobalConfiguration() - .get("AZURE_COGNITIVE_SEARCH_ENDPOINT"); - private static final String ADMIN_KEY = Configuration.getGlobalConfiguration() - .get("AZURE_COGNITIVE_SEARCH_ADMIN_KEY"); - - // Using hard coded connection string to pre-populated Cosmos DB database with sample data set - // For more information visit https://github.com/Azure-Samples/azure-search-sample-data - private static final String COSMOS_CONNECTION_STRING = Configuration.getGlobalConfiguration() - .get("AZURE_COSMOS_CONNECTION_STRING"); - private static final String COSMOS_COLLECTION_NAME = "hotels"; - - private static final String INDEX_NAME = "hotels-sample-index1"; - private static final String DATASOURCE_NAME = "hotels-sample-datasource1"; - private static final String SKILLSET_NAME = "hotels-sample-skillset1"; - private static final String INDEXER_NAME = "hotels-sample-indexer1"; - private static final String SUGGESTER_NAME = "sg"; - - public static void main(String[] args) { - SearchIndexClient indexClient = createIndexClient(); - SearchIndexerClient indexerClient = createIndexerClient(); - // Create a data source for a Cosmos DB database - SearchIndexerDataSourceConnection dataSource = createCosmosDataSource(indexerClient); - - System.out.println("Created DataSource " + dataSource.getName()); - - // Create an index - SearchIndex index = createIndex(indexClient); - System.out.println("Created Index " + index.getName()); - - // Create a skillset for Cognitive Services - SearchIndexerSkillset skillset = createSkillset(indexerClient); - System.out.println("Created Skillset " + skillset.getName()); - - // Create an indexer that uses the skillset and data source and loads the index - SearchIndexer indexer = createIndexer(indexerClient, dataSource, skillset, index); - System.out.println("Created Indexer " + indexer.getName()); - - // Update indexer schedule - updateIndexerSchedule(indexerClient, indexer); - System.out.println("Updated Indexer Schedule " + indexer.getName()); - - // Clean up resources. - indexClient.deleteIndex(INDEX_NAME); - indexerClient.deleteIndexer(INDEXER_NAME); - } - - private static SearchIndexClient createIndexClient() { - return new SearchIndexClientBuilder() - .endpoint(ENDPOINT) - .credential(new AzureKeyCredential(ADMIN_KEY)) - .buildClient(); - } - - private static SearchIndexerClient createIndexerClient() { - return new SearchIndexerClientBuilder() - .endpoint(ENDPOINT) - .credential(new AzureKeyCredential(ADMIN_KEY)) - .buildClient(); - } - - private static void updateIndexerSchedule(SearchIndexerClient client, SearchIndexer indexer) { - IndexingSchedule indexingSchedule = new IndexingSchedule(Duration.ofMinutes(10)); - indexer.setSchedule(indexingSchedule); - - client.createOrUpdateIndexer(indexer); - } - - private static SearchIndexer createIndexer(SearchIndexerClient client, SearchIndexerDataSourceConnection dataSource, - SearchIndexerSkillset skillset, SearchIndex index) { - SearchIndexer indexer = new SearchIndexer(INDEXER_NAME, dataSource.getName(), index.getName()) - .setSkillsetName(skillset.getName()); - - return client.createOrUpdateIndexer(indexer); - } - - private static SearchIndexerSkillset createSkillset(SearchIndexerClient client) { - List inputs = Collections.singletonList( - new InputFieldMappingEntry("text") - .setSource("/document/Description") - ); - - List outputs = Collections.singletonList( - new OutputFieldMappingEntry("locations") - .setTargetName("locations") - ); - - - SearchIndexerSkill skill = new EntityRecognitionSkill(inputs, outputs, EntityRecognitionSkillVersion.V3) - .setName("#1") - .setDescription("Entity Recognition Skill") - .setContext("/document/Description"); - - SearchIndexerSkillset skillset = new SearchIndexerSkillset(SKILLSET_NAME, Collections.singletonList(skill)) - .setDescription("Skillset for testing default configuration"); - - - return client.createOrUpdateSkillset(skillset); - } - - private static SearchIndex createIndex(SearchIndexClient client) { - - List fields = Arrays.asList(new SearchField("HotelId", SearchFieldDataType.STRING) - .setKey(Boolean.TRUE) - .setFacetable(Boolean.TRUE) - .setFilterable(Boolean.TRUE) - .setHidden(Boolean.FALSE) - .setSearchable(Boolean.FALSE) - .setSortable(Boolean.FALSE), - new SearchField("HotelName", SearchFieldDataType.STRING) - .setFacetable(Boolean.FALSE) - .setFilterable(Boolean.FALSE) - .setHidden(Boolean.FALSE) - .setKey(Boolean.FALSE) - .setSearchable(Boolean.TRUE) - .setSortable(Boolean.FALSE) - .setAnalyzerName(LexicalAnalyzerName.EN_MICROSOFT), - new SearchField("Description", SearchFieldDataType.STRING) - .setSearchable(Boolean.TRUE) - .setFilterable(Boolean.FALSE) - .setHidden(Boolean.FALSE) - .setSortable(Boolean.FALSE) - .setFacetable(Boolean.FALSE) - .setAnalyzerName(LexicalAnalyzerName.EN_MICROSOFT), - new SearchField("Tags", SearchFieldDataType.collection(SearchFieldDataType.STRING)) - .setFacetable(Boolean.TRUE) - .setFilterable(Boolean.TRUE) - .setHidden(Boolean.FALSE) - .setSearchable(Boolean.TRUE) - .setAnalyzerName(LexicalAnalyzerName.EN_MICROSOFT)); - // Index definition - SearchIndex index = new SearchIndex(INDEX_NAME, fields); - - // Set Suggester - index.setSuggesters(new SearchSuggester(SUGGESTER_NAME, Collections.singletonList("Tags"))); - - return client.createOrUpdateIndex(index); - } - - private static SearchIndexerDataSourceConnection createCosmosDataSource(SearchIndexerClient client) { - - SearchIndexerDataContainer dataContainer = new SearchIndexerDataContainer(COSMOS_COLLECTION_NAME); - HighWaterMarkChangeDetectionPolicy highWaterMarkChangeDetectionPolicy = - new HighWaterMarkChangeDetectionPolicy("_ts"); - - SearchIndexerDataSourceConnection dataSource = new SearchIndexerDataSourceConnection(DATASOURCE_NAME, - SearchIndexerDataSourceType.COSMOS_DB, COSMOS_CONNECTION_STRING, dataContainer) - .setDataChangeDetectionPolicy(highWaterMarkChangeDetectionPolicy); - - return client.createOrUpdateDataSourceConnection(dataSource); - } - - -} diff --git a/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/indexes/ListIndexersExample.java b/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/indexes/ListIndexersExample.java deleted file mode 100644 index 4b01610e6577..000000000000 --- a/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/indexes/ListIndexersExample.java +++ /dev/null @@ -1,50 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.search.documents.indexes; - -import com.azure.core.credential.AzureKeyCredential; -import com.azure.core.http.rest.PagedResponse; -import com.azure.core.util.Configuration; -import com.azure.search.documents.indexes.models.SearchIndexer; - -import java.util.List; - -public class ListIndexersExample { - - /** - * This example shows how to list all existing indexers in a Cognitive Search Service. - *

- * From the Azure portal, get your Azure AI Search service URL and API key, - * and set the values of these environment variables: - */ - - private static final String ENDPOINT = Configuration.getGlobalConfiguration() - .get("AZURE_COGNITIVE_SEARCH_ENDPOINT"); - private static final String ADMIN_KEY = Configuration.getGlobalConfiguration() - .get("AZURE_COGNITIVE_SEARCH_ADMIN_KEY"); - - public static void main(String[] args) { - SearchIndexerAsyncClient indexerAsyncClient = new SearchIndexerClientBuilder() - .endpoint(ENDPOINT) - .credential(new AzureKeyCredential(ADMIN_KEY)) - .buildAsyncClient(); - - listIndexers(indexerAsyncClient); - } - - private static void listIndexers(SearchIndexerAsyncClient indexerAsyncClient) { - PagedResponse response = indexerAsyncClient.listIndexers() - .byPage().blockFirst(); - - if (response != null) { - System.out.printf("Response code: %s%n", response.getStatusCode()); - - List indexers = response.getValue(); - System.out.println("Found the following indexers:"); - for (SearchIndexer indexer : indexers) { - System.out.printf("Indexer name: %s, ETag: %s%n", indexer.getName(), indexer.getETag()); - } - } - } -} diff --git a/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/models/Hotel.java b/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/models/Hotel.java deleted file mode 100644 index 7aa1133e926c..000000000000 --- a/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/models/Hotel.java +++ /dev/null @@ -1,59 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -package com.azure.search.documents.models; - -import com.azure.search.documents.indexes.SearchableField; -import com.azure.search.documents.indexes.SimpleField; -import com.fasterxml.jackson.annotation.JsonProperty; - -import java.util.ArrayList; -import java.util.List; -import java.util.Objects; - -public class Hotel { - private String hotelId; - private List tags; - - public Hotel() { - this.tags = new ArrayList<>(); - } - - @JsonProperty(value = "HotelId") - @SimpleField(isKey = true) - public String getHotelId() { - return this.hotelId; - } - - public Hotel setHotelId(String hotelId) { - this.hotelId = hotelId; - return this; - } - - @JsonProperty(value = "Tags") - @SearchableField(isFilterable = true, analyzerName = "en.lucene") - public List getTags() { - return this.tags; - } - - public Hotel setTags(List tags) { - this.tags = tags; - return this; - } - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (!(o instanceof Hotel)) { - return false; - } - Hotel hotel = (Hotel) o; - return Objects.equals(hotelId, hotel.hotelId) && Objects.equals(tags, hotel.tags); - } - - @Override - public int hashCode() { - return Objects.hash(hotelId, tags); - } -} diff --git a/sdk/search/azure-search-documents/src/test/README.md b/sdk/search/azure-search-documents/src/test/README.md deleted file mode 100644 index fc22b46f9b89..000000000000 --- a/sdk/search/azure-search-documents/src/test/README.md +++ /dev/null @@ -1,74 +0,0 @@ -# Test Framework - -This SDK uses the TestBase core class to record and playback http sessions, to perform integration tests with Search service in Azure. - -## Usage - -The class: **SearchIndexClientTestBase** is the base test class which other test classes, that need to perform integration tests, must extend it. - -These test classes then can use the base client builder, and run the relevant build method. - -### Code example - -```java -public class SyncTests extends SearchIndexClientTestBase { - - private SearchIndexClient asyncClient; - - @Override - void beforeTest() { - super.beforeTest(); - - createHotelIndex(); - asyncClient = getSearchIndexClientBuilder("hotels").buildAsyncClient(); - } - - @Test - public void uploadResultSucceeds() throws Exception { - Document doc = new Document(); - doc.put("HotelId", "1"); - - List docs = new ArrayList<>(); - docs.add(doc); - - DocumentIndexResult result = asyncClient.uploadDocuments(docs).block(); - assert result.results().get(0).statusCode() == 200; - } -} -``` - -Before running the tests on PLAYBACK mode, you need to run them on RECORD mode to record the http sessions. - -### Recording http sessions - -1. Add the following environment variables to your development SDK to be used in JUnit runs: - * AZURE_CLIENT_ID: *Client ID in Microsoft Entra ID* - [How to create a Client ID in Azure Portal](https://learn.microsoft.com/azure/active-directory/develop/quickstart-register-app) - * AZURE_CLIENT_SECRET: *Client ID Secret* - * AZURE_TENANT_ID: *Tenant ID in Microsoft Entra ID* - * AZURE_SUBSCRIPTION_ID: *Azure subscription ID* - * AZURE_TEST_MODE: **RECORD** *for recording* (**PLAYBACK** *for playback mode*) - * AZURE_TEST_ENVIRONMENT (optional): **DOGFOOD** if performing internal testing. Defaults to public Azure if omitted or set to any other value - -2. Run the tests. - - > Please note: In RECORD mode, every test is creating a new testing environment in Azure before the test, and deleting it after the test. This process takes some time, so the tests in this mode (RECORD) are slower. - -3. After test runs finish, you can find the recorded sessions under the project's target folder: - - `target/test-classes/session-records` - - Every test will have its own session file. - -4. Copy the records to the project's test resources folder: - - `test/resources/session-records` - -> The session files should also be submitted to the project's repository, so the tests in the CI build will use them in playback mode. - -### Running tests in PLAYBACK mode - -To run tests in Playback mode: - -1. Set the value of the **AZURE_TEST_MODE** environment variable to *'PLAYBACK'* (or delete it). You can also delete all other environment variables. -2. Run the tests. diff --git a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/AutocompleteTests.java b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/AutocompleteTests.java deleted file mode 100644 index 933e9e5e238b..000000000000 --- a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/AutocompleteTests.java +++ /dev/null @@ -1,489 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -package com.azure.search.documents; - -import com.azure.core.exception.HttpResponseException; -import com.azure.core.http.rest.PagedIterableBase; -import com.azure.core.test.TestProxyTestBase; -import com.azure.core.test.TestMode; -import com.azure.core.util.Context; -import com.azure.search.documents.indexes.SearchIndexClient; -import com.azure.search.documents.models.AutocompleteItem; -import com.azure.search.documents.models.AutocompleteMode; -import com.azure.search.documents.models.AutocompleteOptions; -import com.azure.search.documents.util.AutocompletePagedFlux; -import com.azure.search.documents.util.AutocompletePagedIterable; -import com.azure.search.documents.util.AutocompletePagedResponse; -import org.junit.jupiter.api.AfterAll; -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.parallel.Execution; -import org.junit.jupiter.api.parallel.ExecutionMode; -import reactor.test.StepVerifier; - -import java.net.HttpURLConnection; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.Iterator; -import java.util.List; -import java.util.stream.Collectors; - -import static com.azure.search.documents.TestHelpers.setupSharedIndex; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertInstanceOf; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.junit.jupiter.api.Assertions.assertTrue; - -@Execution(ExecutionMode.CONCURRENT) -public class AutocompleteTests extends SearchTestBase { - private static final String INDEX_NAME = "azsearch-autocomplete-shared-instance"; - - private static SearchIndexClient searchIndexClient; - private SearchClient client; - private SearchAsyncClient asyncClient; - - @BeforeAll - public static void setupClass() { - TestProxyTestBase.setupClass(); - - if (TEST_MODE == TestMode.PLAYBACK) { - return; - } - - searchIndexClient = setupSharedIndex(INDEX_NAME, HOTELS_TESTS_INDEX_DATA_JSON, HOTELS_DATA_JSON); - } - - @Override - protected void beforeTest() { - client = getSearchClientBuilder(INDEX_NAME, true).buildClient(); - asyncClient = getSearchClientBuilder(INDEX_NAME, false).buildAsyncClient(); - } - - @AfterAll - protected static void cleanupClass() { - if (TEST_MODE != TestMode.PLAYBACK) { - searchIndexClient.deleteIndex(INDEX_NAME); - } - } - - @Test - public void canAutocompleteThrowsWhenGivenBadSuggesterNameSync() { - AutocompleteOptions params = new AutocompleteOptions().setAutocompleteMode(AutocompleteMode.ONE_TERM); - - PagedIterableBase results - = client.autocomplete("very po", "Invalid suggester", params, Context.NONE); - - HttpResponseException ex - = assertThrows(HttpResponseException.class, () -> results.iterableByPage().iterator().next()); - assertEquals(HttpURLConnection.HTTP_BAD_REQUEST, ex.getResponse().getStatusCode()); - } - - @Test - public void canAutocompleteThrowsWhenGivenBadSuggesterNameAsync() { - AutocompleteOptions params = new AutocompleteOptions().setAutocompleteMode(AutocompleteMode.ONE_TERM); - - StepVerifier.create(asyncClient.autocomplete("very po", "Invalid suggester", params, Context.NONE).byPage()) - .thenRequest(1) - .verifyErrorSatisfies(throwable -> { - HttpResponseException ex = assertInstanceOf(HttpResponseException.class, throwable); - assertEquals(HttpURLConnection.HTTP_BAD_REQUEST, ex.getResponse().getStatusCode()); - }); - } - - @Test - public void canAutocompleteDefaultsToOneTermModeSync() { - List expected = Arrays.asList("point", "police", "polite", "pool", "popular"); - - autocompleteAndValidateSync(client.autocomplete("po", "sg"), expected, expected); - } - - @Test - public void canAutocompleteDefaultsToOneTermModeAsync() { - List expected = Arrays.asList("point", "police", "polite", "pool", "popular"); - - autocompleteAndValidateAsync(asyncClient.autocomplete("po", "sg"), expected, expected); - } - - @Test - public void canAutocompleteOneTermWithContextSync() { - List expectedText = Arrays.asList("very police", "very polite", "very popular"); - List expectedQueryPlusText - = Arrays.asList("looking for very police", "looking for very polite", "looking for very popular"); - - AutocompleteOptions params = new AutocompleteOptions(); - params.setAutocompleteMode(AutocompleteMode.ONE_TERM_WITH_CONTEXT); - - autocompleteAndValidateSync(client.autocomplete("looking for very po", "sg", params, Context.NONE), - expectedText, expectedQueryPlusText); - } - - @Test - public void canAutocompleteOneTermWithContextAsync() { - List expectedText = Arrays.asList("very police", "very polite", "very popular"); - List expectedQueryPlusText - = Arrays.asList("looking for very police", "looking for very polite", "looking for very popular"); - - AutocompleteOptions params = new AutocompleteOptions(); - params.setAutocompleteMode(AutocompleteMode.ONE_TERM_WITH_CONTEXT); - - autocompleteAndValidateAsync(asyncClient.autocomplete("looking for very po", "sg", params), expectedText, - expectedQueryPlusText); - } - - @Test - public void canAutocompleteExcludesFieldsNotInSuggesterSync() { - AutocompleteOptions params = new AutocompleteOptions(); - params.setAutocompleteMode(AutocompleteMode.ONE_TERM); - params.setSearchFields("HotelName"); - - Iterator results - = client.autocomplete("luxu", "sg", params, Context.NONE).iterableByPage().iterator(); - - // One page, with 0 items - assertEquals(0, results.next().getValue().size()); - assertFalse(results.hasNext()); - } - - @Test - public void canAutocompleteExcludesFieldsNotInSuggesterAsync() { - AutocompleteOptions params = new AutocompleteOptions(); - params.setAutocompleteMode(AutocompleteMode.ONE_TERM); - params.setSearchFields("HotelName"); - - StepVerifier.create(asyncClient.autocomplete("luxu", "sg", params).byPage()) - .assertNext(page -> assertEquals(0, page.getValue().size())) - .verifyComplete(); - } - - @Test - public void canAutocompleteFuzzyIsOffByDefaultSync() { - AutocompleteOptions params = new AutocompleteOptions(); - params.setAutocompleteMode(AutocompleteMode.ONE_TERM); - - Iterator results - = client.autocomplete("pi", "sg", params, Context.NONE).iterableByPage().iterator(); - - // One page, with 0 items - assertEquals(0, results.next().getValue().size()); - assertFalse(results.hasNext()); - } - - @Test - public void canAutocompleteFuzzyIsOffByDefaultAsync() { - AutocompleteOptions params = new AutocompleteOptions(); - params.setAutocompleteMode(AutocompleteMode.ONE_TERM); - - StepVerifier.create(asyncClient.autocomplete("pi", "sg", params).byPage()) - .assertNext(page -> assertEquals(0, page.getValue().size())) - .verifyComplete(); - } - - @Test - public void canAutocompleteOneTermSync() { - List expected = Arrays.asList("point", "police", "polite", "pool", "popular"); - - AutocompleteOptions params = new AutocompleteOptions().setAutocompleteMode(AutocompleteMode.ONE_TERM); - - autocompleteAndValidateSync(client.autocomplete("po", "sg", params, Context.NONE), expected, expected); - } - - @Test - public void canAutocompleteOneTermAsync() { - List expected = Arrays.asList("point", "police", "polite", "pool", "popular"); - - AutocompleteOptions params = new AutocompleteOptions().setAutocompleteMode(AutocompleteMode.ONE_TERM); - - autocompleteAndValidateAsync(asyncClient.autocomplete("po", "sg", params), expected, expected); - } - - @Test - public void canAutocompleteStaticallyTypedDocumentsSync() { - List expectedText = Arrays.asList("point", "police", "polite", "pool", "popular"); - List expectedQueryPlusText - = Arrays.asList("very point", "very police", "very polite", "very pool", "very popular"); - - AutocompleteOptions params - = new AutocompleteOptions().setAutocompleteMode(AutocompleteMode.ONE_TERM).setUseFuzzyMatching(false); - - autocompleteAndValidateSync(client.autocomplete("very po", "sg", params, Context.NONE), expectedText, - expectedQueryPlusText); - } - - @Test - public void canAutocompleteStaticallyTypedDocumentsAsync() { - List expectedText = Arrays.asList("point", "police", "polite", "pool", "popular"); - List expectedQueryPlusText - = Arrays.asList("very point", "very police", "very polite", "very pool", "very popular"); - - AutocompleteOptions params - = new AutocompleteOptions().setAutocompleteMode(AutocompleteMode.ONE_TERM).setUseFuzzyMatching(false); - - autocompleteAndValidateAsync(asyncClient.autocomplete("very po", "sg", params), expectedText, - expectedQueryPlusText); - } - - @Test - public void canAutocompleteThrowsWhenRequestIsMalformedSync() { - PagedIterableBase results = client.autocomplete("very po", ""); - - HttpResponseException ex - = assertThrows(HttpResponseException.class, () -> results.iterableByPage().iterator().next()); - assertEquals(HttpURLConnection.HTTP_BAD_REQUEST, ex.getResponse().getStatusCode()); - } - - @Test - public void canAutocompleteThrowsWhenRequestIsMalformedAsync() { - StepVerifier.create(asyncClient.autocomplete("very po", "")).thenRequest(1).verifyErrorSatisfies(throwable -> { - HttpResponseException ex = assertInstanceOf(HttpResponseException.class, throwable); - assertEquals(HttpURLConnection.HTTP_BAD_REQUEST, ex.getResponse().getStatusCode()); - }); - } - - @Test - public void canAutocompleteTwoTermsSync() { - List expected - = Arrays.asList("point motel", "police station", "polite staff", "pool a", "popular hotel"); - - AutocompleteOptions params = new AutocompleteOptions().setAutocompleteMode(AutocompleteMode.TWO_TERMS); - - autocompleteAndValidateSync(client.autocomplete("po", "sg", params, Context.NONE), expected, expected); - } - - @Test - public void canAutocompleteTwoTermsAsync() { - List expected - = Arrays.asList("point motel", "police station", "polite staff", "pool a", "popular hotel"); - - AutocompleteOptions params = new AutocompleteOptions().setAutocompleteMode(AutocompleteMode.TWO_TERMS); - - autocompleteAndValidateAsync(asyncClient.autocomplete("po", "sg", params), expected, expected); - } - - @Test - public void testAutocompleteCanUseHitHighlightingSync() { - List expectedText = Arrays.asList("pool", "popular"); - List expectedQueryPlusText = Arrays.asList("pool", "popular"); - - AutocompleteOptions params = new AutocompleteOptions().setAutocompleteMode(AutocompleteMode.ONE_TERM) - .setFilter("HotelName eq 'EconoStay' or HotelName eq 'Fancy Stay'") - .setHighlightPreTag("") - .setHighlightPostTag(""); - - autocompleteAndValidateSync(client.autocomplete("po", "sg", params, Context.NONE), expectedText, - expectedQueryPlusText); - } - - @Test - public void testAutocompleteCanUseHitHighlightingAsync() { - List expectedText = Arrays.asList("pool", "popular"); - List expectedQueryPlusText = Arrays.asList("pool", "popular"); - - AutocompleteOptions params = new AutocompleteOptions().setAutocompleteMode(AutocompleteMode.ONE_TERM) - .setFilter("HotelName eq 'EconoStay' or HotelName eq 'Fancy Stay'") - .setHighlightPreTag("") - .setHighlightPostTag(""); - - autocompleteAndValidateAsync(asyncClient.autocomplete("po", "sg", params), expectedText, expectedQueryPlusText); - } - - @Test - public void testAutocompleteWithMultipleSelectedFieldsSync() { - List expected = Arrays.asList("model", "modern"); - - AutocompleteOptions params = new AutocompleteOptions().setAutocompleteMode(AutocompleteMode.ONE_TERM) - .setSearchFields("HotelName", "Description"); - - autocompleteAndValidateSync(client.autocomplete("mod", "sg", params, Context.NONE), expected, expected); - } - - @Test - public void testAutocompleteWithMultipleSelectedFieldsAsync() { - List expected = Arrays.asList("model", "modern"); - - AutocompleteOptions params = new AutocompleteOptions().setAutocompleteMode(AutocompleteMode.ONE_TERM) - .setSearchFields("HotelName", "Description"); - - autocompleteAndValidateAsync(asyncClient.autocomplete("mod", "sg", params), expected, expected); - } - - @Test - public void testAutocompleteWithSelectedFieldsSync() { - List expected = Collections.singletonList("modern"); - - AutocompleteOptions params = new AutocompleteOptions().setAutocompleteMode(AutocompleteMode.ONE_TERM) - .setSearchFields("HotelName") - .setFilter("HotelId eq '7'"); - - autocompleteAndValidateSync(client.autocomplete("mod", "sg", params, Context.NONE), expected, expected); - } - - @Test - public void testAutocompleteWithSelectedFieldsAsync() { - List expected = Collections.singletonList("modern"); - - AutocompleteOptions params = new AutocompleteOptions().setAutocompleteMode(AutocompleteMode.ONE_TERM) - .setSearchFields("HotelName") - .setFilter("HotelId eq '7'"); - - autocompleteAndValidateAsync(asyncClient.autocomplete("mod", "sg", params), expected, expected); - } - - @Test - public void testAutocompleteTopTrimsResultsSync() { - List expected = Arrays.asList("point", "police"); - - AutocompleteOptions params = new AutocompleteOptions().setAutocompleteMode(AutocompleteMode.ONE_TERM).setTop(2); - - autocompleteAndValidateSync(client.autocomplete("po", "sg", params, Context.NONE), expected, expected); - } - - @Test - public void testAutocompleteTopTrimsResultsAsync() { - List expected = Arrays.asList("point", "police"); - - AutocompleteOptions params = new AutocompleteOptions().setAutocompleteMode(AutocompleteMode.ONE_TERM).setTop(2); - - autocompleteAndValidateAsync(asyncClient.autocomplete("po", "sg", params), expected, expected); - } - - @Test - public void testAutocompleteWithFilterSync() { - List expected = Collections.singletonList("polite"); - - AutocompleteOptions params = new AutocompleteOptions().setAutocompleteMode(AutocompleteMode.ONE_TERM) - .setFilter("search.in(HotelId, '6,7')"); - - autocompleteAndValidateSync(client.autocomplete("po", "sg", params, Context.NONE), expected, expected); - } - - @Test - public void testAutocompleteWithFilterAsync() { - List expected = Collections.singletonList("polite"); - - AutocompleteOptions params = new AutocompleteOptions().setAutocompleteMode(AutocompleteMode.ONE_TERM) - .setFilter("search.in(HotelId, '6,7')"); - - autocompleteAndValidateAsync(asyncClient.autocomplete("po", "sg", params), expected, expected); - } - - @Test - public void testAutocompleteOneTermWithContextWithFuzzySync() { - List expected = Collections.singletonList("very polite"); - - AutocompleteOptions params - = new AutocompleteOptions().setAutocompleteMode(AutocompleteMode.ONE_TERM_WITH_CONTEXT) - .setUseFuzzyMatching(true); - - autocompleteAndValidateSync(client.autocomplete("very polit", "sg", params, Context.NONE), expected, expected); - } - - @Test - public void testAutocompleteOneTermWithContextWithFuzzyAsync() { - List expected = Collections.singletonList("very polite"); - - AutocompleteOptions params - = new AutocompleteOptions().setAutocompleteMode(AutocompleteMode.ONE_TERM_WITH_CONTEXT) - .setUseFuzzyMatching(true); - - autocompleteAndValidateAsync(asyncClient.autocomplete("very polit", "sg", params), expected, expected); - } - - @Test - public void testAutocompleteOneTermWithFuzzySync() { - List expected = Arrays.asList("model", "modern"); - - AutocompleteOptions params - = new AutocompleteOptions().setAutocompleteMode(AutocompleteMode.ONE_TERM).setUseFuzzyMatching(true); - - autocompleteAndValidateSync(client.autocomplete("mod", "sg", params, Context.NONE), expected, expected); - } - - @Test - public void testAutocompleteOneTermWithFuzzyAsync() { - List expected = Arrays.asList("model", "modern"); - - AutocompleteOptions params - = new AutocompleteOptions().setAutocompleteMode(AutocompleteMode.ONE_TERM).setUseFuzzyMatching(true); - - autocompleteAndValidateAsync(asyncClient.autocomplete("mod", "sg", params), expected, expected); - } - - @Test - public void testAutocompleteTwoTermsWithFuzzySync() { - List expected = Arrays.asList("model suites", "modern architecture", "modern stay"); - - AutocompleteOptions params - = new AutocompleteOptions().setAutocompleteMode(AutocompleteMode.TWO_TERMS).setUseFuzzyMatching(true); - - autocompleteAndValidateSync(client.autocomplete("mod", "sg", params, Context.NONE), expected, expected); - } - - @Test - public void testAutocompleteTwoTermsWithFuzzyAsync() { - List expected = Arrays.asList("model suites", "modern architecture", "modern stay"); - - AutocompleteOptions params - = new AutocompleteOptions().setAutocompleteMode(AutocompleteMode.TWO_TERMS).setUseFuzzyMatching(true); - - autocompleteAndValidateAsync(asyncClient.autocomplete("mod", "sg", params), expected, expected); - } - - @Test - public void testAutocompleteWithFilterAndFuzzySync() { - List expected = Collections.singletonList("modern"); - - AutocompleteOptions params = new AutocompleteOptions().setAutocompleteMode(AutocompleteMode.ONE_TERM) - .setUseFuzzyMatching(true) - .setFilter("HotelId ne '6' and (HotelName eq 'Modern Stay' or Tags/any(t : t eq 'budget'))"); - - autocompleteAndValidateSync(client.autocomplete("mod", "sg", params, Context.NONE), expected, expected); - } - - @Test - public void testAutocompleteWithFilterAndFuzzyAsync() { - List expected = Collections.singletonList("modern"); - - AutocompleteOptions params = new AutocompleteOptions().setAutocompleteMode(AutocompleteMode.ONE_TERM) - .setUseFuzzyMatching(true) - .setFilter("HotelId ne '6' and (HotelName eq 'Modern Stay' or Tags/any(t : t eq 'budget'))"); - - autocompleteAndValidateAsync(asyncClient.autocomplete("mod", "sg", params), expected, expected); - } - - private void autocompleteAndValidateSync(AutocompletePagedIterable autocomplete, List expectedTexts, - List expectedQueryPlusText) { - validateResults(autocomplete.stream().collect(Collectors.toList()), expectedTexts, expectedQueryPlusText); - } - - private void autocompleteAndValidateAsync(AutocompletePagedFlux autocomplete, List expectedTexts, - List expectedQueryPlusText) { - StepVerifier.create(autocomplete.collectList()) - .assertNext(results -> validateResults(results, expectedTexts, expectedQueryPlusText)) - .verifyComplete(); - } - - /** - * Compare the autocomplete results with the expected strings - * - * @param items results of autocompletion - * @param expectedText expected text - * @param expectedQueryPlusText expected query plus text - */ - private static void validateResults(List items, List expectedText, - List expectedQueryPlusText) { - assertEquals(expectedText.size(), expectedQueryPlusText.size()); // Validate test is set up properly - assertEquals(expectedText.size(), items.size()); - - // Convert passed Lists into ArrayLists so they're mutable. - ArrayList mutableText = new ArrayList<>(expectedText); - ArrayList mutableQueryPlusText = new ArrayList<>(expectedQueryPlusText); - - for (AutocompleteItem item : items) { - // Since these are Strings we can use List.remove and validate it removed a value. - assertTrue(mutableText.remove(item.getText())); - assertTrue(mutableQueryPlusText.remove(item.getQueryPlusText())); - } - } -} diff --git a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/ContextRequestIdTests.java b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/ContextRequestIdTests.java deleted file mode 100644 index b1f7ed92e913..000000000000 --- a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/ContextRequestIdTests.java +++ /dev/null @@ -1,188 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.search.documents; - -import com.azure.core.http.HttpClient; -import com.azure.core.http.HttpHeaderName; -import com.azure.core.http.HttpHeaders; -import com.azure.core.http.HttpRequest; -import com.azure.core.http.HttpResponse; -import com.azure.core.http.policy.AddHeadersFromContextPolicy; -import com.azure.core.http.policy.FixedDelay; -import com.azure.core.http.policy.RetryPolicy; -import com.azure.core.test.utils.MockTokenCredential; -import com.azure.core.util.Context; -import com.azure.core.util.CoreUtils; -import com.azure.search.documents.indexes.SearchIndexAsyncClient; -import com.azure.search.documents.indexes.SearchIndexClient; -import com.azure.search.documents.indexes.SearchIndexClientBuilder; -import com.azure.search.documents.indexes.SearchIndexerAsyncClient; -import com.azure.search.documents.indexes.SearchIndexerClient; -import com.azure.search.documents.indexes.SearchIndexerClientBuilder; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.parallel.Execution; -import org.junit.jupiter.api.parallel.ExecutionMode; -import reactor.core.publisher.Mono; -import reactor.test.StepVerifier; - -import java.time.Duration; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertInstanceOf; -import static org.junit.jupiter.api.Assertions.assertThrows; - -/** - * Tests passing {@code x-ms-client-request-id} using {@link Context}. - */ -@Execution(ExecutionMode.CONCURRENT) -public class ContextRequestIdTests { - private static final HttpHeaderName REQUEST_ID_HEADER = HttpHeaderName.fromString("x-ms-client-request-id"); - private static final RetryPolicy RETRY_POLICY = new RetryPolicy(new FixedDelay(0, Duration.ofMillis(1))); - - @Test - public void searchClient() { - String expectedRequestId = CoreUtils.randomUuid().toString(); - - SearchClient client = new SearchClientBuilder().indexName("index") - .endpoint("https://test.search.windows.net") - .credential(new MockTokenCredential()) - .retryPolicy(RETRY_POLICY) - .httpClient(new RequestIdVerifyingHttpClient(expectedRequestId)) - .buildClient(); - - Context context = new Context(AddHeadersFromContextPolicy.AZURE_REQUEST_HTTP_HEADERS_KEY, - createRequestIdHeaders(expectedRequestId)); - - verifySync(() -> client.getDocumentCountWithResponse(context), expectedRequestId); - } - - @Test - public void searchAsyncClient() { - String expectedRequestId = CoreUtils.randomUuid().toString(); - - SearchAsyncClient client = new SearchClientBuilder().indexName("index") - .endpoint("https://test.search.windows.net") - .credential(new MockTokenCredential()) - .retryPolicy(RETRY_POLICY) - .httpClient(new RequestIdVerifyingHttpClient(expectedRequestId)) - .buildAsyncClient(); - - reactor.util.context.Context subscriberContext = reactor.util.context.Context - .of(AddHeadersFromContextPolicy.AZURE_REQUEST_HTTP_HEADERS_KEY, createRequestIdHeaders(expectedRequestId)); - - verifyAsync(client.getDocumentCountWithResponse().contextWrite(subscriberContext), expectedRequestId); - } - - @Test - public void searchIndexClient() { - String expectedRequestId = CoreUtils.randomUuid().toString(); - - SearchIndexClient client = new SearchIndexClientBuilder().endpoint("https://test.search.windows.net") - .credential(new MockTokenCredential()) - .retryPolicy(RETRY_POLICY) - .httpClient(new RequestIdVerifyingHttpClient(expectedRequestId)) - .buildClient(); - - Context context = new Context(AddHeadersFromContextPolicy.AZURE_REQUEST_HTTP_HEADERS_KEY, - createRequestIdHeaders(expectedRequestId)); - - verifySync(() -> client.getIndexWithResponse("index", context), expectedRequestId); - } - - @Test - public void searchIndexAsyncClient() { - String expectedRequestId = CoreUtils.randomUuid().toString(); - - SearchIndexAsyncClient client = new SearchIndexClientBuilder().endpoint("https://test.search.windows.net") - .credential(new MockTokenCredential()) - .retryPolicy(RETRY_POLICY) - .httpClient(new RequestIdVerifyingHttpClient(expectedRequestId)) - .buildAsyncClient(); - - reactor.util.context.Context subscriberContext = reactor.util.context.Context - .of(AddHeadersFromContextPolicy.AZURE_REQUEST_HTTP_HEADERS_KEY, createRequestIdHeaders(expectedRequestId)); - - verifyAsync(client.getIndexStatisticsWithResponse("index").contextWrite(subscriberContext), expectedRequestId); - } - - @Test - public void searchIndexerClient() { - String expectedRequestId = CoreUtils.randomUuid().toString(); - - SearchIndexerClient client = new SearchIndexerClientBuilder().endpoint("https://test.search.windows.net") - .credential(new MockTokenCredential()) - .retryPolicy(RETRY_POLICY) - .httpClient(new RequestIdVerifyingHttpClient(expectedRequestId)) - .buildClient(); - - Context context = new Context(AddHeadersFromContextPolicy.AZURE_REQUEST_HTTP_HEADERS_KEY, - createRequestIdHeaders(expectedRequestId)); - - verifySync(() -> client.getIndexerWithResponse("indexer", context), expectedRequestId); - } - - @Test - public void searchIndexerAsyncClient() { - String expectedRequestId = CoreUtils.randomUuid().toString(); - - SearchIndexerAsyncClient client = new SearchIndexerClientBuilder().endpoint("https://test.search.windows.net") - .credential(new MockTokenCredential()) - .retryPolicy(RETRY_POLICY) - .httpClient(new RequestIdVerifyingHttpClient(expectedRequestId)) - .buildAsyncClient(); - - reactor.util.context.Context subscriberContext = reactor.util.context.Context - .of(AddHeadersFromContextPolicy.AZURE_REQUEST_HTTP_HEADERS_KEY, createRequestIdHeaders(expectedRequestId)); - - verifyAsync(client.getIndexerWithResponse("indexer").contextWrite(subscriberContext), expectedRequestId); - } - - private static HttpHeaders createRequestIdHeaders(String requestId) { - return new HttpHeaders().set(REQUEST_ID_HEADER, requestId); - } - - private static void verifySync(Runnable requestRunner, String expectedRequestId) { - RuntimeException ex = assertThrows(RuntimeException.class, requestRunner::run); - assertEquals(expectedRequestId, ex.getMessage()); - } - - private static void verifyAsync(Mono requestMono, String expectedRequestId) { - StepVerifier.create(requestMono).verifyErrorSatisfies(throwable -> { - RuntimeException ex = assertInstanceOf(RuntimeException.class, throwable); - assertEquals(expectedRequestId, ex.getMessage()); - }); - } - - private static final class RequestIdVerifyingHttpClient implements HttpClient { - private final String expectedRequestId; - - private RequestIdVerifyingHttpClient(String expectedRequestId) { - this.expectedRequestId = expectedRequestId; - } - - @Override - public Mono send(HttpRequest request) { - String requestId = request.getHeaders().getValue(REQUEST_ID_HEADER); - assertEquals(expectedRequestId, requestId); - - return Mono.error(new RuntimeException(requestId)); - } - - @Override - public Mono send(HttpRequest request, Context context) { - String requestId = request.getHeaders().getValue(REQUEST_ID_HEADER); - assertEquals(expectedRequestId, requestId); - - return Mono.error(new RuntimeException(requestId)); - } - - @Override - public HttpResponse sendSync(HttpRequest request, Context context) { - String requestId = request.getHeaders().getValue(REQUEST_ID_HEADER); - assertEquals(expectedRequestId, requestId); - - throw new RuntimeException(requestId); - } - } -} diff --git a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/GeographyPointTests.java b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/GeographyPointTests.java deleted file mode 100644 index 91a40eabc470..000000000000 --- a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/GeographyPointTests.java +++ /dev/null @@ -1,189 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.search.documents; - -import com.azure.core.models.GeoPoint; -import com.azure.core.models.GeoPosition; -import com.azure.core.test.TestMode; -import com.azure.core.util.Context; -import com.azure.search.documents.indexes.SearchIndexClient; -import com.azure.search.documents.indexes.SearchIndexClientBuilder; -import com.azure.search.documents.indexes.models.SearchField; -import com.azure.search.documents.indexes.models.SearchFieldDataType; -import com.azure.search.documents.indexes.models.SearchIndex; -import com.azure.search.documents.models.SearchOptions; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonProperty; -import org.junit.jupiter.api.AfterAll; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.Test; -import reactor.core.publisher.Flux; -import reactor.core.publisher.Mono; -import reactor.test.StepVerifier; - -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Objects; -import java.util.function.Function; -import java.util.stream.Collectors; - -/** - * This class tests indexes using OData type GeographyPoint. - */ -public class GeographyPointTests extends SearchTestBase { - private static final List SEARCH_FIELDS = Arrays.asList( - new SearchField("id", SearchFieldDataType.STRING).setKey(true), - new SearchField("geography_point", SearchFieldDataType.GEOGRAPHY_POINT).setFilterable(true).setSortable(true), - new SearchField("description", SearchFieldDataType.STRING).setSearchable(true)); - - private static final GeoPoint SPACE_NEEDLE = new GeoPoint(-122.348616, 47.622151); - private static final GeoPoint PIKES_PLACE_MARKET = new GeoPoint(-122.340529, 47.608564); - private static final GeoPoint PARADISE_VISITOR_CENTER = new GeoPoint(-121.736604, 46.786549); - private static final GeoPoint EMPIRE_STATE_BUILDER = new GeoPoint(new GeoPosition(-73.985707, 40.748521)); - - private static final String INDEX_NAME = "azs-java-shared-geography-point-index"; - - private static SearchIndexClient searchIndexClient; - - private SearchClient searchClient; - private SearchAsyncClient searchAsyncClient; - - private static List getDocuments() { - return Arrays.asList(new SimpleDocument("1", SPACE_NEEDLE, "Tourist location"), - new SimpleDocument("2", PIKES_PLACE_MARKET, "Tourist location"), - new SimpleDocument("3", PARADISE_VISITOR_CENTER, "Tourist location"), - new SimpleDocument("4", EMPIRE_STATE_BUILDER, "Tourist location")); - } - - private static Map getExpectedDocuments() { - return getDocuments().stream().collect(Collectors.toMap(SimpleDocument::getId, Function.identity())); - } - - @BeforeAll - public static void createSharedIndex() { - if (TEST_MODE != TestMode.PLAYBACK) { - searchIndexClient = new SearchIndexClientBuilder().endpoint(ENDPOINT) - .credential(TestHelpers.getTestTokenCredential()) - .retryPolicy(SERVICE_THROTTLE_SAFE_RETRY_POLICY) - .buildClient(); - - searchIndexClient.createIndex(new SearchIndex(INDEX_NAME, SEARCH_FIELDS)); - searchIndexClient.getSearchClient(INDEX_NAME).uploadDocuments(getDocuments()); - - TestHelpers.sleepIfRunningAgainstService(2000); - } - } - - @AfterAll - public static void deleteSharedIndex() { - if (TEST_MODE != TestMode.PLAYBACK) { - searchIndexClient.deleteIndex(INDEX_NAME); - } - } - - @Override - protected void beforeTest() { - super.beforeTest(); - - searchClient = getSearchClientBuilder(INDEX_NAME, true).buildClient(); - searchAsyncClient = getSearchClientBuilder(INDEX_NAME, false).buildAsyncClient(); - } - - @Test - public void canRoundTripGeographyPointsSync() { - Map expectedDocuments = getExpectedDocuments(); - Map actualDocuments = new HashMap<>(); - - actualDocuments.put("1", searchClient.getDocument("1", SimpleDocument.class)); - actualDocuments.put("2", searchClient.getDocument("2", SimpleDocument.class)); - actualDocuments.put("3", searchClient.getDocument("3", SimpleDocument.class)); - actualDocuments.put("4", searchClient.getDocument("4", SimpleDocument.class)); - - compareMaps(expectedDocuments, actualDocuments, Assertions::assertEquals); - - actualDocuments = searchClient.search("Tourist location", new SearchOptions().setOrderBy("id"), Context.NONE) - .stream() - .map(doc -> doc.getDocument(SimpleDocument.class)) - .collect(Collectors.toMap(SimpleDocument::getId, Function.identity())); - - compareMaps(expectedDocuments, actualDocuments, Assertions::assertEquals); - } - - @Test - public void canRoundTripGeographyPointsAsync() { - Map expectedDocuments = getExpectedDocuments(); - - Mono> getDocumentsByIdMono = Flux.just("1", "2", "3", "4") - .flatMap(id -> searchAsyncClient.getDocument(id, SimpleDocument.class)) - .collectMap(SimpleDocument::getId); - - StepVerifier.create(getDocumentsByIdMono) - .assertNext(actualDocuments -> compareMaps(expectedDocuments, actualDocuments, Assertions::assertEquals)) - .verifyComplete(); - - Mono> searchDocumentsMono - = searchAsyncClient.search("Tourist location", new SearchOptions().setOrderBy("id")) - .map(doc -> doc.getDocument(SimpleDocument.class)) - .collectMap(SimpleDocument::getId); - - StepVerifier.create(searchDocumentsMono) - .assertNext(actualDocuments -> compareMaps(expectedDocuments, actualDocuments, Assertions::assertEquals)) - .verifyComplete(); - } - - public static final class SimpleDocument { - @JsonProperty("id") - private final String id; - - @JsonProperty("geography_point") - private final GeoPoint geoPoint; - - @JsonProperty("description") - private final String description; - - @JsonCreator - public SimpleDocument(@JsonProperty("id") String id, @JsonProperty("geography_point") GeoPoint geoPoint, - @JsonProperty("description") String description) { - this.id = id; - this.geoPoint = geoPoint; - this.description = description; - } - - public String getId() { - return id; - } - - public GeoPoint getGeoPoint() { - return geoPoint; - } - - public String getDescription() { - return description; - } - - @Override - public boolean equals(Object obj) { - if (!(obj instanceof SimpleDocument)) { - return false; - } - - if (obj == this) { - return true; - } - - SimpleDocument other = (SimpleDocument) obj; - return Objects.equals(id, other.id) - && Objects.equals(geoPoint.getCoordinates(), other.geoPoint.getCoordinates()) - && Objects.equals(description, other.description); - } - - @Override - public int hashCode() { - return Objects.hash(id, geoPoint.getCoordinates(), description); - } - } -} diff --git a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/IndexBatchTests.java b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/IndexBatchTests.java deleted file mode 100644 index 7dab49f9e9d0..000000000000 --- a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/IndexBatchTests.java +++ /dev/null @@ -1,330 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -package com.azure.search.documents; - -import com.azure.search.documents.indexes.models.IndexDocumentsBatch; -import com.azure.search.documents.models.IndexAction; -import com.azure.search.documents.models.IndexActionType; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.parallel.Execution; -import org.junit.jupiter.api.parallel.ExecutionMode; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.List; -import java.util.stream.Collectors; - -import static org.junit.jupiter.api.Assertions.assertEquals; - -@Execution(ExecutionMode.CONCURRENT) -public class IndexBatchTests { - - @Test - public void uploadDocument() { - SearchDocument searchDocument = new SearchDocument(); - searchDocument.put("Id", "1"); - - IndexAction indexAction - = new IndexAction().setActionType(IndexActionType.UPLOAD).setDocument(searchDocument); - - IndexDocumentsBatch expected - = new IndexDocumentsBatch().addActions(Collections.singletonList(indexAction)); - - IndexDocumentsBatch actual - = new IndexDocumentsBatch().addUploadActions(Collections.singletonList(searchDocument)); - - validate(expected, actual); - } - - @Test - public void uploadDocuments() { - SearchDocument doc1 = new SearchDocument(); - doc1.put("Id", "1"); - - SearchDocument doc2 = new SearchDocument(); - doc2.put("Id", "2"); - - SearchDocument doc3 = new SearchDocument(); - doc3.put("Id", "3"); - - List docs = Arrays.asList(doc1, doc2, doc3); - List> indexActions = docs.stream() - .map(doc -> new IndexAction().setActionType(IndexActionType.UPLOAD).setDocument(doc)) - .collect(Collectors.toList()); - - IndexDocumentsBatch expectedBatch - = new IndexDocumentsBatch().addActions(indexActions); - - IndexDocumentsBatch actualBatch - = new IndexDocumentsBatch().addUploadActions(docs); - - validate(expectedBatch, actualBatch); - } - - @Test - public void mergeDocument() { - SearchDocument searchDocument = new SearchDocument(); - searchDocument.put("Id", "1"); - - IndexAction indexAction - = new IndexAction().setActionType(IndexActionType.MERGE).setDocument(searchDocument); - - IndexDocumentsBatch expected - = new IndexDocumentsBatch().addActions(Collections.singletonList(indexAction)); - - IndexDocumentsBatch actual - = new IndexDocumentsBatch().addMergeActions(Collections.singletonList(searchDocument)); - - validate(expected, actual); - } - - @Test - public void mergeDocuments() { - SearchDocument doc1 = new SearchDocument(); - doc1.put("Id", "1"); - - SearchDocument doc2 = new SearchDocument(); - doc2.put("Id", "2"); - - SearchDocument doc3 = new SearchDocument(); - doc3.put("Id", "3"); - - List docs = Arrays.asList(doc1, doc2, doc3); - List> indexActions = docs.stream() - .map(doc -> new IndexAction().setActionType(IndexActionType.MERGE).setDocument(doc)) - .collect(Collectors.toList()); - - IndexDocumentsBatch expectedBatch - = new IndexDocumentsBatch().addActions(indexActions); - - IndexDocumentsBatch actualBatch - = new IndexDocumentsBatch().addMergeActions(docs); - - validate(expectedBatch, actualBatch); - } - - @Test - public void mergeOrUploadDocument() { - SearchDocument searchDocument = new SearchDocument(); - searchDocument.put("Id", "1"); - - IndexAction indexAction - = new IndexAction().setActionType(IndexActionType.MERGE_OR_UPLOAD) - .setDocument(searchDocument); - - IndexDocumentsBatch expected - = new IndexDocumentsBatch().addActions(Collections.singletonList(indexAction)); - - IndexDocumentsBatch actual = new IndexDocumentsBatch() - .addMergeOrUploadActions(Collections.singletonList(searchDocument)); - - validate(expected, actual); - } - - @Test - public void mergeOrUploadDocuments() { - SearchDocument doc1 = new SearchDocument(); - doc1.put("Id", "1"); - - SearchDocument doc2 = new SearchDocument(); - doc2.put("Id", "2"); - - SearchDocument doc3 = new SearchDocument(); - doc3.put("Id", "3"); - - List docs = Arrays.asList(doc1, doc2, doc3); - List> indexActions = docs.stream() - .map(doc -> new IndexAction().setActionType(IndexActionType.MERGE_OR_UPLOAD) - .setDocument(doc)) - .collect(Collectors.toList()); - - IndexDocumentsBatch expectedBatch - = new IndexDocumentsBatch().addActions(indexActions); - - IndexDocumentsBatch actualBatch - = new IndexDocumentsBatch().addMergeOrUploadActions(docs); - - validate(expectedBatch, actualBatch); - } - - @Test - public void deleteDocument() { - SearchDocument searchDocument = new SearchDocument(); - searchDocument.put("Id", "1"); - - IndexAction indexAction - = new IndexAction().setActionType(IndexActionType.DELETE).setDocument(searchDocument); - - IndexDocumentsBatch expected - = new IndexDocumentsBatch().addActions(Collections.singletonList(indexAction)); - - IndexDocumentsBatch actual - = new IndexDocumentsBatch().addDeleteActions(Collections.singletonList(searchDocument)); - - validate(expected, actual); - } - - @Test - public void deleteDocuments() { - SearchDocument doc1 = new SearchDocument(); - doc1.put("Id", "1"); - - SearchDocument doc2 = new SearchDocument(); - doc2.put("Id", "2"); - - SearchDocument doc3 = new SearchDocument(); - doc3.put("Id", "3"); - - List docs = Arrays.asList(doc1, doc2, doc3); - List> indexActions = docs.stream() - .map(doc -> new IndexAction().setActionType(IndexActionType.DELETE).setDocument(doc)) - .collect(Collectors.toList()); - - IndexDocumentsBatch expectedBatch - = new IndexDocumentsBatch().addActions(indexActions); - - IndexDocumentsBatch actualBatch - = new IndexDocumentsBatch().addDeleteActions(docs); - - validate(expectedBatch, actualBatch); - } - - @Test - public void canBuildIndexBatchWithMultipleActionsAndSingleDocument() { - SearchDocument documentToMerge = new SearchDocument(); - documentToMerge.put("Id", "merge"); - - SearchDocument documentToMergeOrUpload = new SearchDocument(); - documentToMergeOrUpload.put("Id", "mergeOrUpload"); - - SearchDocument documentToUpload = new SearchDocument(); - documentToUpload.put("Id", "upload"); - - SearchDocument documentToDelete = new SearchDocument(); - documentToDelete.put("Id", "delete"); - - IndexAction mergeAction - = new IndexAction().setActionType(IndexActionType.MERGE).setDocument(documentToMerge); - - IndexAction mergeOrUploadAction - = new IndexAction().setActionType(IndexActionType.MERGE_OR_UPLOAD) - .setDocument(documentToMergeOrUpload); - - IndexAction deleteAction - = new IndexAction().setActionType(IndexActionType.DELETE).setDocument(documentToDelete); - - IndexAction uploadAction - = new IndexAction().setActionType(IndexActionType.UPLOAD).setDocument(documentToUpload); - - IndexDocumentsBatch expected = new IndexDocumentsBatch() - .addActions(Arrays.asList(mergeAction, mergeOrUploadAction, deleteAction, uploadAction)); - - IndexDocumentsBatch actual - = new IndexDocumentsBatch().addMergeActions(Collections.singletonList(documentToMerge)) - .addMergeOrUploadActions(Collections.singletonList(documentToMergeOrUpload)) - .addDeleteActions(Collections.singletonList(documentToDelete)) - .addUploadActions(Collections.singletonList(documentToUpload)); - - validate(expected, actual); - } - - @Test - public void canBuildIndexBatchWithMultipleActionsAndMultipleDocuments() { - List documentsToMerge = new ArrayList<>(); - - SearchDocument merge1 = new SearchDocument(); - merge1.put("Id", "merge1"); - documentsToMerge.add(merge1); - - SearchDocument merge2 = new SearchDocument(); - merge2.put("Id", "merge2"); - documentsToMerge.add(merge2); - - List documentsToDelete = new ArrayList<>(); - - SearchDocument delete1 = new SearchDocument(); - delete1.put("Id", "delete1"); - documentsToDelete.add(delete1); - - SearchDocument delete2 = new SearchDocument(); - delete2.put("Id", "delete2"); - documentsToDelete.add(delete2); - - List documentsToMergeOrUpload = new ArrayList<>(); - - SearchDocument mergeOrUpload1 = new SearchDocument(); - mergeOrUpload1.put("Id", "mergeOrUpload1"); - documentsToMergeOrUpload.add(mergeOrUpload1); - - SearchDocument mergeOrUpload2 = new SearchDocument(); - mergeOrUpload2.put("Id", "mergeOrUpload2"); - documentsToMergeOrUpload.add(mergeOrUpload2); - - List documentsToUpload = new ArrayList<>(); - - SearchDocument upload1 = new SearchDocument(); - upload1.put("Id", "upload1"); - documentsToUpload.add(upload1); - - SearchDocument upload2 = new SearchDocument(); - upload2.put("Id", "upload2"); - documentsToUpload.add(upload2); - - IndexAction mergeAction1 - = new IndexAction().setActionType(IndexActionType.MERGE) - .setDocument(documentsToMerge.get(0)); - - IndexAction mergeAction2 - = new IndexAction().setActionType(IndexActionType.MERGE) - .setDocument(documentsToMerge.get(1)); - - IndexAction mergeOrUploadAction1 - = new IndexAction().setActionType(IndexActionType.MERGE_OR_UPLOAD) - .setDocument(documentsToMergeOrUpload.get(0)); - - IndexAction mergeOrUploadAction2 - = new IndexAction().setActionType(IndexActionType.MERGE_OR_UPLOAD) - .setDocument(documentsToMergeOrUpload.get(1)); - - IndexAction deleteAction1 - = new IndexAction().setActionType(IndexActionType.DELETE) - .setDocument(documentsToDelete.get(0)); - - IndexAction deleteAction2 - = new IndexAction().setActionType(IndexActionType.DELETE) - .setDocument(documentsToDelete.get(1)); - - IndexAction uploadAction1 - = new IndexAction().setActionType(IndexActionType.UPLOAD) - .setDocument(documentsToUpload.get(0)); - - IndexAction uploadAction2 - = new IndexAction().setActionType(IndexActionType.UPLOAD) - .setDocument(documentsToUpload.get(1)); - - IndexDocumentsBatch expected = new IndexDocumentsBatch() - .addActions(Arrays.asList(mergeAction1, mergeAction2, mergeOrUploadAction1, mergeOrUploadAction2, - deleteAction1, deleteAction2, uploadAction1, uploadAction2)); - - IndexDocumentsBatch actual - = new IndexDocumentsBatch().addMergeActions(documentsToMerge) - .addMergeOrUploadActions(documentsToMergeOrUpload) - .addDeleteActions(documentsToDelete) - .addUploadActions(documentsToUpload); - - validate(expected, actual); - } - - private void validate(IndexDocumentsBatch expected, IndexDocumentsBatch actual) { - assertEquals(expected.getActions().size(), actual.getActions().size()); - - for (int i = 0; i < actual.getActions().size(); i++) { - IndexAction expectedIndexAction = expected.getActions().get(i); - IndexAction actualIndexAction = actual.getActions().get(i); - - assertEquals(expectedIndexAction.getActionType(), actualIndexAction.getActionType()); - assertEquals(expectedIndexAction.getDocument(), actualIndexAction.getDocument()); - } - } -} diff --git a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/IndexingTests.java b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/IndexingTests.java deleted file mode 100644 index f04331482623..000000000000 --- a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/IndexingTests.java +++ /dev/null @@ -1,1508 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -package com.azure.search.documents; - -import com.azure.core.http.rest.Response; -import com.azure.core.models.GeoPoint; -import com.azure.core.test.TestProxyTestBase; -import com.azure.core.test.TestMode; -import com.azure.core.test.annotation.LiveOnly; -import com.azure.core.util.Context; -import com.azure.search.documents.indexes.SearchIndexClient; -import com.azure.search.documents.indexes.models.IndexDocumentsBatch; -import com.azure.search.documents.models.IndexBatchException; -import com.azure.search.documents.models.IndexDocumentsOptions; -import com.azure.search.documents.models.IndexDocumentsResult; -import com.azure.search.documents.models.IndexingResult; -import com.azure.search.documents.test.environment.models.Author; -import com.azure.search.documents.test.environment.models.Book; -import com.azure.search.documents.test.environment.models.Hotel; -import com.azure.search.documents.test.environment.models.HotelAddress; -import com.azure.search.documents.test.environment.models.HotelRoom; -import com.azure.search.documents.test.environment.models.LoudHotel; -import io.netty.handler.codec.http.HttpResponseStatus; -import org.junit.jupiter.api.AfterAll; -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.parallel.Execution; -import org.junit.jupiter.api.parallel.ExecutionMode; -import reactor.core.publisher.Mono; -import reactor.test.StepVerifier; - -import java.net.HttpURLConnection; -import java.time.Instant; -import java.time.LocalDateTime; -import java.time.OffsetDateTime; -import java.time.ZoneOffset; -import java.time.format.DateTimeFormatter; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.Date; -import java.util.HashMap; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import java.util.function.BiConsumer; - -import static com.azure.search.documents.TestHelpers.assertHttpResponseException; -import static com.azure.search.documents.TestHelpers.assertMapEquals; -import static com.azure.search.documents.TestHelpers.assertObjectEquals; -import static com.azure.search.documents.TestHelpers.setupSharedIndex; -import static com.azure.search.documents.TestHelpers.verifyHttpResponseError; -import static com.azure.search.documents.TestHelpers.waitForIndexing; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertInstanceOf; -import static org.junit.jupiter.api.Assertions.assertNull; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.junit.jupiter.api.Assertions.assertTrue; - -@Execution(ExecutionMode.CONCURRENT) -public class IndexingTests extends SearchTestBase { - private static final String BOOKS_INDEX_JSON = "BooksIndexData.json"; - - // Don't use more than three shared instances at once to support testing against free instances which only support - // three indexes. - private static final String HOTEL_INDEX_NAME = "azsearch-indexing-shared-hotel-instance"; - private static final String EMPTY_INDEX_NAME = "azsearch-indexing-shared-empty-instance"; - private static final String BOOKS_INDEX_NAME = "azsearch-indexing-shared-books-instance"; - - private static SearchIndexClient searchIndexClient; - - @BeforeAll - public static void setupClass() { - TestProxyTestBase.setupClass(); - - if (TEST_MODE == TestMode.PLAYBACK) { - return; - } - - searchIndexClient = setupSharedIndex(HOTEL_INDEX_NAME, HOTELS_TESTS_INDEX_DATA_JSON, null); - setupSharedIndex(EMPTY_INDEX_NAME, HOTELS_TESTS_INDEX_DATA_JSON, null); - setupSharedIndex(BOOKS_INDEX_NAME, BOOKS_INDEX_JSON, null); - } - - @AfterAll - public static void cleanupClass() { - if (TEST_MODE != TestMode.PLAYBACK) { - searchIndexClient.deleteIndex(HOTEL_INDEX_NAME); - searchIndexClient.deleteIndex(EMPTY_INDEX_NAME); - searchIndexClient.deleteIndex(BOOKS_INDEX_NAME); - } - } - - private SearchClient getClient(String indexName) { - return getSearchClientBuilder(indexName, true).buildClient(); - } - - private SearchAsyncClient getAsyncClient(String indexName) { - return getSearchClientBuilder(indexName, false).buildAsyncClient(); - } - - private String getRandomDocumentKey() { - return testResourceNamer.randomName("key", 32); - } - - @Test - public void countingDocsOfNewIndexGivesZeroSync() { - SearchClient client = getClient(EMPTY_INDEX_NAME); - - assertEquals(0L, client.getDocumentCount()); - } - - @Test - public void countingDocsOfNewIndexGivesZeroAsync() { - SearchAsyncClient asyncClient = getAsyncClient(EMPTY_INDEX_NAME); - - StepVerifier.create(asyncClient.getDocumentCount()) - .assertNext(actual -> assertEquals(0, actual)) - .verifyComplete(); - } - - @Test - @LiveOnly - public void indexDoesNotThrowWhenAllActionsSucceedSync() { - // Disable `("$..key")` sanitizer - // if (!interceptorManager.isLiveMode()) { - // interceptorManager.removeSanitizers("AZSDK3447")); - // } - SearchClient client = getClient(HOTEL_INDEX_NAME); - - String expectedHotelId = getRandomDocumentKey(); - List hotels = Collections.singletonList(new Hotel().hotelId(expectedHotelId)); - - List result = client.uploadDocuments(hotels).getResults(); - assertIndexActionSucceeded(expectedHotelId, result.get(0), 201); - } - - @Test - @LiveOnly - public void indexDoesNotThrowWhenAllActionsSucceedAsync() { - // Disable `("$..key")` sanitizer - // if (!interceptorManager.isLiveMode()) { - // interceptorManager.removeSanitizers("AZSDK3447")); - // } - SearchAsyncClient asyncClient = getAsyncClient(HOTEL_INDEX_NAME); - - String expectedHotelId = getRandomDocumentKey(); - List hotels = Collections.singletonList(new Hotel().hotelId(expectedHotelId)); - - StepVerifier.create(asyncClient.uploadDocuments(hotels)) - .assertNext(result -> assertIndexActionSucceeded(expectedHotelId, result.getResults().get(0), 201)) - .verifyComplete(); - } - - @Test - @LiveOnly - public void canIndexWithPascalCaseFieldsSync() { - // Disable `("$..key")` sanitizer - // if (!interceptorManager.isLiveMode()) { - // interceptorManager.removeSanitizers("AZSDK3447")); - // } - SearchClient client = getClient(BOOKS_INDEX_NAME); - - String isbn = getRandomDocumentKey(); - List books = new ArrayList<>(); - books.add(new Book().ISBN(isbn) - .title("Lord of the Rings") - .author(new Author().firstName("J.R.R").lastName("Tolkien"))); - - List result = client.uploadDocuments(books).getResults(); - assertIndexActionSucceeded(isbn, result.get(0), 201); - } - - @Test - @LiveOnly - public void canIndexWithPascalCaseFieldsAsync() { - // Disable `("$..key")` sanitizer - // if (!interceptorManager.isLiveMode()) { - // interceptorManager.removeSanitizers("AZSDK3447")); - // } - SearchAsyncClient asyncClient = getAsyncClient(BOOKS_INDEX_NAME); - - String isbn = getRandomDocumentKey(); - List books = new ArrayList<>(); - books.add(new Book().ISBN(isbn) - .title("Lord of the Rings") - .author(new Author().firstName("J.R.R").lastName("Tolkien"))); - - StepVerifier.create(asyncClient.uploadDocuments(books)) - .assertNext(result -> assertIndexActionSucceeded(isbn, result.getResults().get(0), 201)) - .verifyComplete(); - } - - @Test - @LiveOnly - public void canDeleteBatchByKeysSync() { - // Disable `("$..key")` sanitizer - // if (!interceptorManager.isLiveMode()) { - // interceptorManager.removeSanitizers("AZSDK3447")); - // } - SearchClient client = getClient(HOTEL_INDEX_NAME); - - String hotel1Key = getRandomDocumentKey(); - String hotel2Key = getRandomDocumentKey(); - - client.uploadDocuments(Arrays.asList(new Hotel().hotelId(hotel1Key), new Hotel().hotelId(hotel2Key))); - - waitForIndexing(); - - IndexDocumentsBatch deleteBatch - = new IndexDocumentsBatch().addDeleteActions("HotelId", Arrays.asList(hotel1Key, hotel2Key)); - - IndexDocumentsResult documentIndexResult = client.indexDocuments(deleteBatch); - - assertEquals(2, documentIndexResult.getResults().size()); - assertIndexActionSucceeded(hotel1Key, documentIndexResult.getResults().get(0), 200); - assertIndexActionSucceeded(hotel2Key, documentIndexResult.getResults().get(1), 200); - } - - @Test - @LiveOnly - public void canDeleteBatchByKeysAsync() { - // Disable `("$..key")` sanitizer - // if (!interceptorManager.isLiveMode()) { - // interceptorManager.removeSanitizers("AZSDK3447")); - // } - SearchAsyncClient asyncClient = getAsyncClient(HOTEL_INDEX_NAME); - - String hotel1Key = getRandomDocumentKey(); - String hotel2Key = getRandomDocumentKey(); - - asyncClient.uploadDocuments(Arrays.asList(new Hotel().hotelId(hotel1Key), new Hotel().hotelId(hotel2Key))) - .block(); - - waitForIndexing(); - - IndexDocumentsBatch deleteBatch - = new IndexDocumentsBatch().addDeleteActions("HotelId", Arrays.asList(hotel1Key, hotel2Key)); - - StepVerifier.create(asyncClient.indexDocuments(deleteBatch)).assertNext(result -> { - assertEquals(2, result.getResults().size()); - assertIndexActionSucceeded(hotel1Key, result.getResults().get(0), 200); - assertIndexActionSucceeded(hotel2Key, result.getResults().get(1), 200); - }).verifyComplete(); - } - - @Test - @LiveOnly - public void indexDoesNotThrowWhenDeletingDocumentWithExtraFieldsSync() { - // Disable `("$..key")` sanitizer - // if (!interceptorManager.isLiveMode()) { - // interceptorManager.removeSanitizers("AZSDK3447")); - // } - SearchClient client = getClient(HOTEL_INDEX_NAME); - - String hotelId = getRandomDocumentKey(); - Hotel hotel = new Hotel().hotelId(hotelId).category("Luxury"); - List hotels = Collections.singletonList(hotel); - - client.uploadDocuments(hotels); - waitForIndexing(); - - hotel.category("ignored"); - IndexDocumentsResult documentIndexResult = client.deleteDocuments(hotels); - - assertEquals(1, documentIndexResult.getResults().size()); - assertIndexActionSucceeded(hotelId, documentIndexResult.getResults().get(0), 200); - } - - @Test - @LiveOnly - public void indexDoesNotThrowWhenDeletingDocumentWithExtraFieldsAsync() { - // Disable `("$..key")` sanitizer - // if (!interceptorManager.isLiveMode()) { - // interceptorManager.removeSanitizers("AZSDK3447")); - // } - SearchAsyncClient asyncClient = getAsyncClient(HOTEL_INDEX_NAME); - - String hotelId = getRandomDocumentKey(); - Hotel hotel = new Hotel().hotelId(hotelId).category("Luxury"); - List hotels = Collections.singletonList(hotel); - - asyncClient.uploadDocuments(hotels).block(); - waitForIndexing(); - - hotel.category("ignored"); - - StepVerifier.create(asyncClient.deleteDocuments(hotels)).assertNext(result -> { - assertEquals(1, result.getResults().size()); - assertIndexActionSucceeded(hotelId, result.getResults().get(0), 200); - }).verifyComplete(); - } - - @Test - @LiveOnly - public void indexDoesNotThrowWhenDeletingDynamicDocumentWithExtraFieldsSync() { - // Disable `("$..key")` sanitizer - // if (!interceptorManager.isLiveMode()) { - // interceptorManager.removeSanitizers("AZSDK3447")); - // } - SearchClient client = getClient(HOTEL_INDEX_NAME); - - String hotelId = getRandomDocumentKey(); - SearchDocument searchDocument = new SearchDocument(); - searchDocument.put("HotelId", hotelId); - searchDocument.put("Category", "Luxury"); - List docs = Collections.singletonList(searchDocument); - - client.uploadDocuments(docs); - - waitForIndexing(); - - searchDocument.put("Category", "ignored"); - IndexDocumentsResult documentIndexResult = client.deleteDocuments(docs); - - assertEquals(1, documentIndexResult.getResults().size()); - assertIndexActionSucceeded(hotelId, documentIndexResult.getResults().get(0), 200); - } - - @Test - @LiveOnly - public void indexDoesNotThrowWhenDeletingDynamicDocumentWithExtraFieldsAsync() { - // Disable `("$..key")` sanitizer - // if (!interceptorManager.isLiveMode()) { - // interceptorManager.removeSanitizers("AZSDK3447")); - // } - SearchAsyncClient asyncClient = getAsyncClient(HOTEL_INDEX_NAME); - - String hotelId = getRandomDocumentKey(); - SearchDocument searchDocument = new SearchDocument(); - searchDocument.put("HotelId", hotelId); - searchDocument.put("Category", "Luxury"); - List docs = Collections.singletonList(searchDocument); - - asyncClient.uploadDocuments(docs).block(); - waitForIndexing(); - - searchDocument.put("Category", "ignored"); - - StepVerifier.create(asyncClient.deleteDocuments(docs)).assertNext(result -> { - assertEquals(1, result.getResults().size()); - assertIndexActionSucceeded(hotelId, result.getResults().get(0), 200); - }).verifyComplete(); - } - - @Test - @LiveOnly - public void canIndexStaticallyTypedDocumentsSync() { - // Disable `("$..key")` sanitizer - // if (!interceptorManager.isLiveMode()) { - // interceptorManager.removeSanitizers("AZSDK3447")); - // } - SearchClient client = getClient(HOTEL_INDEX_NAME); - - String hotel1Id = getRandomDocumentKey(); - String hotel2Id = getRandomDocumentKey(); - String hotel3Id = getRandomDocumentKey(); - Hotel hotel1 = prepareStaticallyTypedHotel(hotel1Id); - Hotel hotel2 = prepareStaticallyTypedHotel(hotel2Id); - Hotel hotel3 = prepareStaticallyTypedHotel(hotel3Id); - Hotel nonExistingHotel = prepareStaticallyTypedHotel("nonExistingHotel"); // merging with a non-existing document - Hotel randomHotel = prepareStaticallyTypedHotel("randomId"); // deleting a non existing document - - IndexDocumentsBatch batch - = new IndexDocumentsBatch().addUploadActions(Collections.singletonList(hotel1)) - .addDeleteActions(Collections.singletonList(randomHotel)) - .addMergeActions(Collections.singletonList(nonExistingHotel)) - .addMergeOrUploadActions(Collections.singletonList(hotel3)) - .addUploadActions(Collections.singletonList(hotel2)); - - IndexBatchException ex = assertThrows(IndexBatchException.class, () -> client.indexDocumentsWithResponse(batch, - new IndexDocumentsOptions().setThrowOnAnyError(true), Context.NONE)); - - List results = ex.getIndexingResults(); - assertEquals(results.size(), batch.getActions().size()); - - assertSuccessfulIndexResult(results.get(0), hotel1Id, 201); - assertSuccessfulIndexResult(results.get(1), "randomId", 200); - assertFailedIndexResult(results.get(2), "nonExistingHotel", 404); - assertSuccessfulIndexResult(results.get(3), hotel3Id, 201); - assertSuccessfulIndexResult(results.get(4), hotel2Id, 201); - - for (Hotel hotel : Arrays.asList(hotel1, hotel2, hotel3)) { - Hotel actual = client.getDocument(hotel.hotelId(), Hotel.class); - assertObjectEquals(hotel, actual, true); - } - } - - @Test - @LiveOnly - public void canIndexStaticallyTypedDocumentsAsync() { - // Disable `("$..key")` sanitizer - // if (!interceptorManager.isLiveMode()) { - // interceptorManager.removeSanitizers("AZSDK3447")); - // } - SearchAsyncClient asyncClient = getAsyncClient(HOTEL_INDEX_NAME); - - String hotel1Id = getRandomDocumentKey(); - String hotel2Id = getRandomDocumentKey(); - String hotel3Id = getRandomDocumentKey(); - Hotel hotel1 = prepareStaticallyTypedHotel(hotel1Id); - Hotel hotel2 = prepareStaticallyTypedHotel(hotel2Id); - Hotel hotel3 = prepareStaticallyTypedHotel(hotel3Id); - Hotel nonExistingHotel = prepareStaticallyTypedHotel("nonExistingHotel"); // merging with a non-existing document - Hotel randomHotel = prepareStaticallyTypedHotel("randomId"); // deleting a non existing document - - IndexDocumentsBatch batch - = new IndexDocumentsBatch().addUploadActions(Collections.singletonList(hotel1)) - .addDeleteActions(Collections.singletonList(randomHotel)) - .addMergeActions(Collections.singletonList(nonExistingHotel)) - .addMergeOrUploadActions(Collections.singletonList(hotel3)) - .addUploadActions(Collections.singletonList(hotel2)); - - StepVerifier - .create(asyncClient.indexDocumentsWithResponse(batch, new IndexDocumentsOptions().setThrowOnAnyError(true))) - .verifyErrorSatisfies(throwable -> { - IndexBatchException ex = assertInstanceOf(IndexBatchException.class, throwable); - - List results = ex.getIndexingResults(); - assertEquals(results.size(), batch.getActions().size()); - - assertSuccessfulIndexResult(results.get(0), hotel1Id, 201); - assertSuccessfulIndexResult(results.get(1), "randomId", 200); - assertFailedIndexResult(results.get(2), "nonExistingHotel", 404); - assertSuccessfulIndexResult(results.get(3), hotel3Id, 201); - assertSuccessfulIndexResult(results.get(4), hotel2Id, 201); - }); - - for (Hotel hotel : Arrays.asList(hotel1, hotel2, hotel3)) { - getAndValidateDocumentAsync(asyncClient, hotel.hotelId(), Hotel.class, hotel, - (expected, actual) -> assertObjectEquals(expected, actual, true)); - } - } - - @Test - @LiveOnly - public void canIndexDynamicDocumentsNotThrowSync() { - // Disable `("$..key")` sanitizer - // if (!interceptorManager.isLiveMode()) { - // interceptorManager.removeSanitizers("AZSDK3447")); - // } - SearchClient client = getClient(HOTEL_INDEX_NAME); - - String hotel1Id = getRandomDocumentKey(); - String hotel2Id = getRandomDocumentKey(); - String hotel3Id = getRandomDocumentKey(); - SearchDocument hotel1 = prepareDynamicallyTypedHotel(hotel1Id); - SearchDocument hotel2 = prepareDynamicallyTypedHotel(hotel2Id); - SearchDocument hotel3 = prepareDynamicallyTypedHotel(hotel3Id); - SearchDocument nonExistingHotel = prepareDynamicallyTypedHotel("nonExistingHotel"); // deleting a non existing document - SearchDocument randomHotel = prepareDynamicallyTypedHotel("randomId"); // deleting a non existing document - - IndexDocumentsBatch batch - = new IndexDocumentsBatch().addUploadActions(Collections.singletonList(hotel1)) - .addDeleteActions(Collections.singletonList(randomHotel)) - .addMergeActions(Collections.singletonList(nonExistingHotel)) - .addMergeOrUploadActions(Collections.singletonList(hotel3)) - .addUploadActions(Collections.singletonList(hotel2)); - - Response resultResponse = client.indexDocumentsWithResponse(batch, - new IndexDocumentsOptions().setThrowOnAnyError(false), Context.NONE); - List results = resultResponse.getValue().getResults(); - assertEquals(resultResponse.getStatusCode(), 207); - assertSuccessfulIndexResult(results.get(0), hotel1Id, 201); - assertSuccessfulIndexResult(results.get(1), "randomId", 200); - assertFailedIndexResult(results.get(2), "nonExistingHotel", 404); - assertSuccessfulIndexResult(results.get(3), hotel3Id, 201); - assertSuccessfulIndexResult(results.get(4), hotel2Id, 201); - - for (SearchDocument hotel : Arrays.asList(hotel1, hotel2, hotel3)) { - SearchDocument actual = client.getDocument(hotel.get("HotelId").toString(), SearchDocument.class); - assertMapEquals(hotel, actual, true); - } - } - - @Test - @LiveOnly - public void canIndexDynamicDocumentsNotThrowAsync() { - // Disable `("$..key")` sanitizer - // if (!interceptorManager.isLiveMode()) { - // interceptorManager.removeSanitizers("AZSDK3447")); - // } - SearchAsyncClient asyncClient = getAsyncClient(HOTEL_INDEX_NAME); - - String hotel1Id = getRandomDocumentKey(); - String hotel2Id = getRandomDocumentKey(); - String hotel3Id = getRandomDocumentKey(); - SearchDocument hotel1 = prepareDynamicallyTypedHotel(hotel1Id); - SearchDocument hotel2 = prepareDynamicallyTypedHotel(hotel2Id); - SearchDocument hotel3 = prepareDynamicallyTypedHotel(hotel3Id); - SearchDocument nonExistingHotel = prepareDynamicallyTypedHotel("nonExistingHotel"); // deleting a non existing document - SearchDocument randomHotel = prepareDynamicallyTypedHotel("randomId"); // deleting a non existing document - - IndexDocumentsBatch batch - = new IndexDocumentsBatch().addUploadActions(Collections.singletonList(hotel1)) - .addDeleteActions(Collections.singletonList(randomHotel)) - .addMergeActions(Collections.singletonList(nonExistingHotel)) - .addMergeOrUploadActions(Collections.singletonList(hotel3)) - .addUploadActions(Collections.singletonList(hotel2)); - - StepVerifier - .create( - asyncClient.indexDocumentsWithResponse(batch, new IndexDocumentsOptions().setThrowOnAnyError(false))) - .assertNext(resultResponse -> { - List results = resultResponse.getValue().getResults(); - assertEquals(resultResponse.getStatusCode(), 207); - assertSuccessfulIndexResult(results.get(0), hotel1Id, 201); - assertSuccessfulIndexResult(results.get(1), "randomId", 200); - assertFailedIndexResult(results.get(2), "nonExistingHotel", 404); - assertSuccessfulIndexResult(results.get(3), hotel3Id, 201); - assertSuccessfulIndexResult(results.get(4), hotel2Id, 201); - }) - .verifyComplete(); - - for (SearchDocument hotel : Arrays.asList(hotel1, hotel2, hotel3)) { - getAndValidateDocumentAsync(asyncClient, hotel.get("HotelId").toString(), SearchDocument.class, hotel, - (expected, actual) -> assertMapEquals(expected, actual, true)); - } - } - - @Test - @LiveOnly - public void canIndexDynamicDocumentsThrowOnErrorSync() { - // Disable `("$..key")` sanitizer - // if (!interceptorManager.isLiveMode()) { - // interceptorManager.removeSanitizers("AZSDK3447")); - // } - SearchClient client = getClient(HOTEL_INDEX_NAME); - - String hotel1Id = getRandomDocumentKey(); - String hotel2Id = getRandomDocumentKey(); - String hotel3Id = getRandomDocumentKey(); - SearchDocument hotel1 = prepareDynamicallyTypedHotel(hotel1Id); - SearchDocument hotel2 = prepareDynamicallyTypedHotel(hotel2Id); - SearchDocument hotel3 = prepareDynamicallyTypedHotel(hotel3Id); - SearchDocument nonExistingHotel = prepareDynamicallyTypedHotel("nonExistingHotel"); // deleting a non existing document - SearchDocument randomHotel = prepareDynamicallyTypedHotel("randomId"); // deleting a non existing document - - IndexDocumentsBatch batch - = new IndexDocumentsBatch().addUploadActions(Collections.singletonList(hotel1)) - .addDeleteActions(Collections.singletonList(randomHotel)) - .addMergeActions(Collections.singletonList(nonExistingHotel)) - .addMergeOrUploadActions(Collections.singletonList(hotel3)) - .addUploadActions(Collections.singletonList(hotel2)); - - IndexBatchException ex = assertThrows(IndexBatchException.class, () -> client.indexDocuments(batch)); - List results = ex.getIndexingResults(); - assertEquals(results.size(), batch.getActions().size()); - - assertSuccessfulIndexResult(results.get(0), hotel1Id, 201); - assertSuccessfulIndexResult(results.get(1), "randomId", 200); - assertFailedIndexResult(results.get(2), "nonExistingHotel", 404); - assertSuccessfulIndexResult(results.get(3), hotel3Id, 201); - assertSuccessfulIndexResult(results.get(4), hotel2Id, 201); - - for (SearchDocument hotel : Arrays.asList(hotel1, hotel2, hotel3)) { - SearchDocument actual = client.getDocument(hotel.get("HotelId").toString(), SearchDocument.class); - assertMapEquals(hotel, actual, true); - } - } - - @Test - @LiveOnly - public void canIndexDynamicDocumentsThrowOnErrorAsync() { - // Disable `("$..key")` sanitizer - // if (!interceptorManager.isLiveMode()) { - // interceptorManager.removeSanitizers("AZSDK3447")); - // } - SearchAsyncClient asyncClient = getAsyncClient(HOTEL_INDEX_NAME); - - String hotel1Id = getRandomDocumentKey(); - String hotel2Id = getRandomDocumentKey(); - String hotel3Id = getRandomDocumentKey(); - SearchDocument hotel1 = prepareDynamicallyTypedHotel(hotel1Id); - SearchDocument hotel2 = prepareDynamicallyTypedHotel(hotel2Id); - SearchDocument hotel3 = prepareDynamicallyTypedHotel(hotel3Id); - SearchDocument nonExistingHotel = prepareDynamicallyTypedHotel("nonExistingHotel"); // deleting a non existing document - SearchDocument randomHotel = prepareDynamicallyTypedHotel("randomId"); // deleting a non existing document - - IndexDocumentsBatch batch - = new IndexDocumentsBatch().addUploadActions(Collections.singletonList(hotel1)) - .addDeleteActions(Collections.singletonList(randomHotel)) - .addMergeActions(Collections.singletonList(nonExistingHotel)) - .addMergeOrUploadActions(Collections.singletonList(hotel3)) - .addUploadActions(Collections.singletonList(hotel2)); - - StepVerifier.create(asyncClient.indexDocuments(batch)).verifyErrorSatisfies(throwable -> { - IndexBatchException ex = assertInstanceOf(IndexBatchException.class, throwable); - - List results = ex.getIndexingResults(); - assertEquals(results.size(), batch.getActions().size()); - - assertSuccessfulIndexResult(results.get(0), hotel1Id, 201); - assertSuccessfulIndexResult(results.get(1), "randomId", 200); - assertFailedIndexResult(results.get(2), "nonExistingHotel", 404); - assertSuccessfulIndexResult(results.get(3), hotel3Id, 201); - assertSuccessfulIndexResult(results.get(4), hotel2Id, 201); - }); - - for (SearchDocument hotel : Arrays.asList(hotel1, hotel2, hotel3)) { - getAndValidateDocumentAsync(asyncClient, hotel.get("HotelId").toString(), SearchDocument.class, hotel, - (expected, actual) -> assertMapEquals(expected, actual, true)); - } - } - - @Test - public void indexWithInvalidDocumentThrowsExceptionSync() { - SearchClient client = getClient(HOTEL_INDEX_NAME); - - List docs = Collections.singletonList(new SearchDocument()); - - assertHttpResponseException(() -> client.uploadDocuments(docs), HttpURLConnection.HTTP_BAD_REQUEST, null); - } - - @Test - public void indexWithInvalidDocumentThrowsExceptionAsync() { - SearchAsyncClient asyncClient = getAsyncClient(HOTEL_INDEX_NAME); - - List docs = Collections.singletonList(new SearchDocument()); - - StepVerifier.create(asyncClient.uploadDocuments(docs)) - .verifyErrorSatisfies( - throwable -> verifyHttpResponseError(throwable, HttpURLConnection.HTTP_BAD_REQUEST, null)); - } - - @Test - public void canRoundtripBoundaryValuesSync() { - SearchClient client = getClient(HOTEL_INDEX_NAME); - - List boundaryConditionDocs = getBoundaryValues(); - - client.uploadDocuments(boundaryConditionDocs); - waitForIndexing(); - - for (Hotel expected : boundaryConditionDocs) { - Hotel actual = client.getDocument(expected.hotelId(), Hotel.class); - - assertObjectEquals(expected, actual, true); - } - } - - @Test - public void canRoundtripBoundaryValuesAsync() { - SearchAsyncClient asyncClient = getAsyncClient(HOTEL_INDEX_NAME); - - List boundaryConditionDocs = getBoundaryValues(); - - asyncClient.uploadDocuments(boundaryConditionDocs).block(); - waitForIndexing(); - - for (Hotel expected : boundaryConditionDocs) { - getAndValidateDocumentAsync(asyncClient, expected.hotelId(), Hotel.class, expected, - (ignored, actual) -> assertObjectEquals(expected, actual, true)); - } - } - - @Test - public void dynamicDocumentDateTimesRoundTripAsUtcSync() { - SearchClient client = getClient(BOOKS_INDEX_NAME); - - OffsetDateTime utcTime = OffsetDateTime.of(LocalDateTime.of(2010, 1, 1, 0, 0, 0), ZoneOffset.UTC); - // UTC-8 - OffsetDateTime utcTimeMinusEight - = OffsetDateTime.of(LocalDateTime.of(2010, 1, 1, 0, 0, 0), ZoneOffset.ofHours(-8)); - - String isbn1 = getRandomDocumentKey(); - Map book1 = new HashMap<>(); - book1.put("ISBN", isbn1); - book1.put("PublishDate", utcTime); - - String isbn2 = getRandomDocumentKey(); - Map book2 = new HashMap<>(); - book2.put("ISBN", isbn2); - book2.put("PublishDate", utcTimeMinusEight); - - client.uploadDocuments(Arrays.asList(book1, book2)); - waitForIndexing(); - - SearchDocument actualBook1 = client.getDocument(isbn1, SearchDocument.class); - assertEquals(utcTime.format(DateTimeFormatter.ISO_OFFSET_DATE_TIME), actualBook1.get("PublishDate")); - - // Azure AI Search normalizes to UTC, so we compare instants - SearchDocument actualBook2 = client.getDocument(isbn2, SearchDocument.class); - assertEquals( - utcTimeMinusEight.withOffsetSameInstant(ZoneOffset.UTC).format(DateTimeFormatter.ISO_OFFSET_DATE_TIME), - actualBook2.get("PublishDate")); - } - - @Test - public void dynamicDocumentDateTimesRoundTripAsUtcAsync() { - SearchAsyncClient asyncClient = getAsyncClient(BOOKS_INDEX_NAME); - - OffsetDateTime utcTime = OffsetDateTime.of(LocalDateTime.of(2010, 1, 1, 0, 0, 0), ZoneOffset.UTC); - // UTC-8 - OffsetDateTime utcTimeMinusEight - = OffsetDateTime.of(LocalDateTime.of(2010, 1, 1, 0, 0, 0), ZoneOffset.ofHours(-8)); - - String isbn1 = getRandomDocumentKey(); - SearchDocument book1 = new SearchDocument(); - book1.put("ISBN", isbn1); - book1.put("PublishDate", utcTime); - - String isbn2 = getRandomDocumentKey(); - SearchDocument book2 = new SearchDocument(); - book2.put("ISBN", isbn2); - book2.put("PublishDate", utcTimeMinusEight); - - asyncClient.uploadDocuments(Arrays.asList(book1, book2)).block(); - waitForIndexing(); - - getAndValidateDocumentAsync(asyncClient, isbn1, SearchDocument.class, book1, (expected, - actual) -> assertEquals(utcTime.format(DateTimeFormatter.ISO_OFFSET_DATE_TIME), actual.get("PublishDate"))); - - // Azure AI Search normalizes to UTC, so we compare instants - getAndValidateDocumentAsync(asyncClient, isbn2, SearchDocument.class, book2, - (expected, actual) -> assertEquals( - utcTimeMinusEight.withOffsetSameInstant(ZoneOffset.UTC).format(DateTimeFormatter.ISO_OFFSET_DATE_TIME), - actual.get("PublishDate"))); - } - - @Test - public void staticallyTypedDateTimesRoundTripAsUtcSync() { - SearchClient client = getClient(BOOKS_INDEX_NAME); - - String isbn1 = getRandomDocumentKey(); - String isbn2 = getRandomDocumentKey(); - List books = Arrays.asList( - new Book().ISBN(isbn1) - .publishDate(OffsetDateTime.of(LocalDateTime.of(2010, 1, 1, 0, 0, 0), ZoneOffset.UTC)), - new Book().ISBN(isbn2) - .publishDate(OffsetDateTime.of(LocalDateTime.of(2010, 1, 1, 0, 0, 0), ZoneOffset.ofHours(-8)))); - - client.uploadDocuments(books); - - Book actualBook1 = client.getDocument(isbn1, Book.class); - assertEquals(books.get(0).publishDate(), actualBook1.publishDate()); - - // Azure AI Search normalizes to UTC, so we compare instants - Book actualBook2 = client.getDocument(isbn2, Book.class); - assertEquals(books.get(1).publishDate().withOffsetSameInstant(ZoneOffset.UTC), - actualBook2.publishDate().withOffsetSameInstant(ZoneOffset.UTC)); - } - - @Test - public void staticallyTypedDateTimesRoundTripAsUtcAsync() { - SearchAsyncClient asyncClient = getAsyncClient(BOOKS_INDEX_NAME); - - String isbn1 = getRandomDocumentKey(); - String isbn2 = getRandomDocumentKey(); - List books = Arrays.asList( - new Book().ISBN(isbn1) - .publishDate(OffsetDateTime.of(LocalDateTime.of(2010, 1, 1, 0, 0, 0), ZoneOffset.UTC)), - new Book().ISBN(isbn2) - .publishDate(OffsetDateTime.of(LocalDateTime.of(2010, 1, 1, 0, 0, 0), ZoneOffset.ofHours(-8)))); - - asyncClient.uploadDocuments(books).block(); - - getAndValidateDocumentAsync(asyncClient, isbn1, Book.class, null, - (expected, actual) -> assertEquals(books.get(0).publishDate(), actual.publishDate())); - - // Azure AI Search normalizes to UTC, so we compare instants - getAndValidateDocumentAsync(asyncClient, isbn2, Book.class, null, - (expected, actual) -> assertEquals(books.get(1).publishDate().withOffsetSameInstant(ZoneOffset.UTC), - actual.publishDate().withOffsetSameInstant(ZoneOffset.UTC))); - } - - @Test - public void canMergeStaticallyTypedDocumentsSync() { - SearchClient client = getClient(HOTEL_INDEX_NAME); - - String hotelId = getRandomDocumentKey(); - - // Define hotels - Hotel originalDoc = canMergeStaticallyTypedDocumentsOriginal(hotelId); - - // Update category, tags, parking included, rating, and rooms. Erase description, last renovation date, location and address. - Hotel updatedDoc = canMergeStaticallyTypedDocumentsUpdated(hotelId); - - // Fields whose values get updated are updated, and whose values get erased remain the same. - Hotel expectedDoc = canMergeStaticallyTypedDocumentsExpected(hotelId); - - List originalDocs = Collections.singletonList(originalDoc); - client.uploadDocuments(originalDocs); - - client.mergeDocuments(Collections.singletonList(updatedDoc)); - assertObjectEquals(expectedDoc, client.getDocument(hotelId, Hotel.class), true); - - client.mergeDocuments(originalDocs); - assertObjectEquals(originalDoc, client.getDocument(hotelId, Hotel.class), true); - } - - @Test - public void canMergeStaticallyTypedDocumentsAsync() { - SearchAsyncClient asyncClient = getAsyncClient(HOTEL_INDEX_NAME); - - String hotelId = getRandomDocumentKey(); - - // Define hotels - Hotel originalDoc = canMergeStaticallyTypedDocumentsOriginal(hotelId); - - // Update category, tags, parking included, rating, and rooms. Erase description, last renovation date, location and address. - Hotel updatedDoc = canMergeStaticallyTypedDocumentsUpdated(hotelId); - - // Fields whose values get updated are updated, and whose values get erased remain the same. - Hotel expectedDoc = canMergeStaticallyTypedDocumentsExpected(hotelId); - - List originalDocs = Collections.singletonList(originalDoc); - asyncClient.uploadDocuments(originalDocs).block(); - - asyncClient.mergeDocuments(Collections.singletonList(updatedDoc)).block(); - - getAndValidateDocumentAsync(asyncClient, hotelId, Hotel.class, expectedDoc, - (expected, actual) -> assertObjectEquals(expected, actual, true)); - - asyncClient.mergeDocuments(originalDocs).block(); - - getAndValidateDocumentAsync(asyncClient, hotelId, Hotel.class, originalDoc, - (expected, actual) -> assertObjectEquals(expected, actual, true)); - } - - @Test - @LiveOnly - public void mergeDocumentWithoutExistingKeyThrowsIndexingExceptionSync() { - // Disable `("$..key")` sanitizer - // if (!interceptorManager.isLiveMode()) { - // interceptorManager.removeSanitizers("AZSDK3447")); - // } - SearchClient client = getClient(HOTEL_INDEX_NAME); - - String hotelId = getRandomDocumentKey(); - IndexBatchException ex = assertThrows(IndexBatchException.class, - () -> client.mergeDocuments(Collections.singletonList(prepareStaticallyTypedHotel(hotelId)))); - - List results = ex.getIndexingResults(); - assertFailedIndexResult(results.get(0), hotelId, HttpResponseStatus.NOT_FOUND.code()); - assertEquals(1, results.size()); - } - - @Test - @LiveOnly - public void mergeDocumentWithoutExistingKeyThrowsIndexingExceptionAsync() { - // Disable `("$..key")` sanitizer - // if (!interceptorManager.isLiveMode()) { - // interceptorManager.removeSanitizers("AZSDK3447")); - // } - SearchAsyncClient asyncClient = getAsyncClient(HOTEL_INDEX_NAME); - - String hotelId = getRandomDocumentKey(); - StepVerifier.create(asyncClient.mergeDocuments(Collections.singletonList(prepareStaticallyTypedHotel(hotelId)))) - .verifyErrorSatisfies(throwable -> { - IndexBatchException ex = assertInstanceOf(IndexBatchException.class, throwable); - - List results = ex.getIndexingResults(); - assertFailedIndexResult(results.get(0), hotelId, HttpResponseStatus.NOT_FOUND.code()); - assertEquals(1, results.size()); - }); - } - - @Test - public void canSetExplicitNullsInStaticallyTypedDocumentSync() { - SearchClient client = getClient(HOTEL_INDEX_NAME); - - String hotelId = getRandomDocumentKey(); - LoudHotel originalDoc = canSetExplicitNullsInStaticallyTypedDocumentOriginal(hotelId); - LoudHotel updatedDoc = canSetExplicitNullsInStaticallyTypedDocumentUpdated(hotelId); - LoudHotel expectedDoc = canSetExplicitNullsInStaticallyTypedDocumentExpected(hotelId); - - List originalDocs = Collections.singletonList(originalDoc); - client.uploadDocuments(originalDocs); - waitForIndexing(); - - client.mergeDocuments(Collections.singletonList(updatedDoc)); - waitForIndexing(); - - LoudHotel actualDoc1 = client.getDocument(hotelId, LoudHotel.class); - assertObjectEquals(expectedDoc, actualDoc1, true); - - client.uploadDocuments(originalDocs); - waitForIndexing(); - - LoudHotel actualDoc2 = client.getDocument(hotelId, LoudHotel.class); - assertObjectEquals(originalDoc, actualDoc2, true); - } - - @Test - public void canSetExplicitNullsInStaticallyTypedDocumentAsync() { - SearchAsyncClient asyncClient = getAsyncClient(HOTEL_INDEX_NAME); - - String hotelId = getRandomDocumentKey(); - LoudHotel originalDoc = canSetExplicitNullsInStaticallyTypedDocumentOriginal(hotelId); - LoudHotel updatedDoc = canSetExplicitNullsInStaticallyTypedDocumentUpdated(hotelId); - LoudHotel expectedDoc = canSetExplicitNullsInStaticallyTypedDocumentExpected(hotelId); - - List originalDocs = Collections.singletonList(originalDoc); - asyncClient.uploadDocuments(originalDocs).block(); - waitForIndexing(); - - asyncClient.mergeDocuments(Collections.singletonList(updatedDoc)).block(); - waitForIndexing(); - - getAndValidateDocumentAsync(asyncClient, hotelId, LoudHotel.class, expectedDoc, - (expected, actual) -> assertObjectEquals(expected, actual, true)); - - asyncClient.uploadDocuments(originalDocs).block(); - waitForIndexing(); - - getAndValidateDocumentAsync(asyncClient, hotelId, LoudHotel.class, originalDoc, - (expected, actual) -> assertObjectEquals(expected, actual, true)); - } - - @Test - public void canMergeDynamicDocumentsSync() { - SearchClient client = getClient(HOTEL_INDEX_NAME); - - String hotelId = getRandomDocumentKey(); - SearchDocument originalDoc = canMergeDynamicDocumentsOriginal(hotelId); - SearchDocument updatedDoc = canMergeDynamicDocumentsUpdated(hotelId); - SearchDocument expectedDoc = canMergeDynamicDocumentsExpected(hotelId); - - List originalDocs = Collections.singletonList(originalDoc); - client.mergeOrUploadDocuments(originalDocs); - waitForIndexing(); - - client.mergeDocuments(Collections.singletonList(updatedDoc)); - waitForIndexing(); - - SearchDocument actualDoc = client.getDocument(hotelId, SearchDocument.class); - assertObjectEquals(expectedDoc, actualDoc, true); - - client.mergeOrUploadDocuments(originalDocs); - waitForIndexing(); - - actualDoc = client.getDocument(hotelId, SearchDocument.class); - assertMapEquals(originalDoc, actualDoc, false, "properties"); - } - - @Test - public void canMergeDynamicDocumentsAsync() { - SearchAsyncClient asyncClient = getAsyncClient(HOTEL_INDEX_NAME); - - String hotelId = getRandomDocumentKey(); - SearchDocument originalDoc = canMergeDynamicDocumentsOriginal(hotelId); - SearchDocument updatedDoc = canMergeDynamicDocumentsUpdated(hotelId); - SearchDocument expectedDoc = canMergeDynamicDocumentsExpected(hotelId); - - List originalDocs = Collections.singletonList(originalDoc); - asyncClient.mergeOrUploadDocuments(originalDocs).block(); - waitForIndexing(); - - asyncClient.mergeDocuments(Collections.singletonList(updatedDoc)).block(); - waitForIndexing(); - - getAndValidateDocumentAsync(asyncClient, hotelId, SearchDocument.class, expectedDoc, - (expected, actual) -> assertObjectEquals(expected, actual, true)); - - asyncClient.mergeOrUploadDocuments(originalDocs).block(); - waitForIndexing(); - - getAndValidateDocumentAsync(asyncClient, hotelId, SearchDocument.class, originalDoc, - (expected, actual) -> assertObjectEquals(expected, actual, true, "properties")); - } - - @Test - public void canIndexAndAccessResponseSync() { - SearchClient client = getClient(HOTEL_INDEX_NAME); - - String hotel1Id = getRandomDocumentKey(); - String hotel2Id = getRandomDocumentKey(); - String hotel3Id = getRandomDocumentKey(); - String hotel4Id = getRandomDocumentKey(); - - List hotelsToUpload = Arrays.asList(new Hotel().hotelId(hotel1Id), new Hotel().hotelId(hotel2Id)); - - List hotelsToMerge = Collections.singletonList(new Hotel().hotelId(hotel1Id).rating(5)); - - List hotelsToMergeOrUpload - = Arrays.asList(new Hotel().hotelId(hotel3Id).rating(4), new Hotel().hotelId(hotel4Id).rating(1)); - - List hotelsToDelete = Collections.singletonList(new Hotel().hotelId(hotel4Id)); - - IndexDocumentsBatch batch = new IndexDocumentsBatch().addUploadActions(hotelsToUpload) - .addMergeOrUploadActions(hotelsToMergeOrUpload); - - validateIndexResponseSync(client.uploadDocumentsWithResponse(hotelsToUpload, null, Context.NONE), 2); - waitForIndexing(); - - validateIndexResponseSync(client.mergeDocumentsWithResponse(hotelsToMerge, null, Context.NONE), 1); - validateIndexResponseSync(client.mergeOrUploadDocumentsWithResponse(hotelsToMergeOrUpload, null, Context.NONE), - 2); - waitForIndexing(); - - validateIndexResponseSync(client.deleteDocumentsWithResponse(hotelsToDelete, null, Context.NONE), 1); - waitForIndexing(); - - validateIndexResponseSync(client.indexDocumentsWithResponse(batch, null, Context.NONE), 4); - waitForIndexing(); - - assertEquals(4, client.getDocument(hotel3Id, SearchDocument.class).get("Rating")); - } - - @Test - public void canIndexAndAccessResponseAsync() { - SearchAsyncClient asyncClient = getAsyncClient(HOTEL_INDEX_NAME); - - String hotel1Id = getRandomDocumentKey(); - String hotel2Id = getRandomDocumentKey(); - String hotel3Id = getRandomDocumentKey(); - String hotel4Id = getRandomDocumentKey(); - - List hotelsToUpload = Arrays.asList(new Hotel().hotelId(hotel1Id), new Hotel().hotelId(hotel2Id)); - - List hotelsToMerge = Collections.singletonList(new Hotel().hotelId(hotel1Id).rating(5)); - - List hotelsToMergeOrUpload - = Arrays.asList(new Hotel().hotelId(hotel3Id).rating(4), new Hotel().hotelId(hotel4Id).rating(1)); - - List hotelsToDelete = Collections.singletonList(new Hotel().hotelId(hotel4Id)); - - IndexDocumentsBatch batch = new IndexDocumentsBatch().addUploadActions(hotelsToUpload) - .addMergeOrUploadActions(hotelsToMergeOrUpload); - - validateIndexResponseAsync(asyncClient.uploadDocumentsWithResponse(hotelsToUpload, null), 2); - - waitForIndexing(); - - validateIndexResponseAsync(asyncClient.mergeDocumentsWithResponse(hotelsToMerge, null), 1); - validateIndexResponseAsync(asyncClient.mergeOrUploadDocumentsWithResponse(hotelsToMergeOrUpload, null), 2); - - waitForIndexing(); - - validateIndexResponseAsync(asyncClient.deleteDocumentsWithResponse(hotelsToDelete, null), 1); - - waitForIndexing(); - - validateIndexResponseAsync(asyncClient.indexDocumentsWithResponse(batch, null), 4); - - waitForIndexing(); - - getAndValidateDocumentAsync(asyncClient, hotel3Id, SearchDocument.class, null, - (expected, actual) -> assertEquals(4, actual.get("Rating"))); - } - - private static void getAndValidateDocumentAsync(SearchAsyncClient asyncClient, String key, Class type, - T expected, BiConsumer comparator) { - StepVerifier.create(asyncClient.getDocument(key, type)) - .assertNext(actual -> comparator.accept(expected, actual)) - .verifyComplete(); - } - - private static void validateIndexResponseSync(Response response, int resultCount) { - assertEquals(200, response.getStatusCode()); - assertEquals(resultCount, response.getValue().getResults().size()); - } - - private static void validateIndexResponseAsync(Mono> indexDocumentsWithResponse, - int resultCount) { - StepVerifier.create(indexDocumentsWithResponse).assertNext(response -> { - assertEquals(200, response.getStatusCode()); - assertEquals(resultCount, response.getValue().getResults().size()); - }).verifyComplete(); - } - - @SuppressWarnings({ "UseOfObsoleteDateTimeApi" }) - static Hotel prepareStaticallyTypedHotel(String hotelId) { - return new Hotel().hotelId(hotelId) - .hotelName("Fancy Stay") - .description( - "Best hotel in town if you like luxury hotels. They have an amazing infinity pool, a spa, and a really helpful concierge. The location is perfect -- right downtown, close to all the tourist attractions. We highly recommend this hotel.") - .descriptionFr( - "Meilleur hôtel en ville si vous aimez les hôtels de luxe. Ils ont une magnifique piscine à débordement, un spa et un concierge très utile. L'emplacement est parfait – en plein centre, à proximité de toutes les attractions touristiques. Nous recommandons fortement cet hôtel.") - .category("Luxury") - .tags(Arrays.asList("pool", "view", "wifi", "concierge")) - .parkingIncluded(false) - .smokingAllowed(false) - .lastRenovationDate(parseDate("2010-06-27T00:00:00Z")) - .rating(5) - .location(new GeoPoint(-122.131577, 47.678581)) - .address(new HotelAddress().streetAddress("1 Microsoft Way") - .city("Redmond") - .stateProvince("Washington") - .postalCode("98052") - .country("United States")); - } - - SearchDocument prepareDynamicallyTypedHotel(String hotelId) { - - SearchDocument room1 = new SearchDocument(); - room1.put("Description", "Budget Room, 1 Queen Bed"); - room1.put("Description_fr", null); - room1.put("Type", "Budget Room"); - room1.put("BaseRate", 149.99); - room1.put("BedOptions", "1 Queen Bed"); - room1.put("SleepsCount", 2); - room1.put("SmokingAllowed", true); - room1.put("Tags", Arrays.asList("vcr/dvd", "great view")); - - SearchDocument room2 = new SearchDocument(); - room2.put("Description", "Budget Room, 1 King Bed"); - room2.put("Description_fr", null); - room2.put("Type", "Budget Room"); - room2.put("BaseRate", 249.99); - room2.put("BedOptions", "1 King Bed"); - room2.put("SleepsCount", 2); - room2.put("SmokingAllowed", true); - room2.put("Tags", Arrays.asList("vcr/dvd", "seaside view")); - - List rooms = Arrays.asList(room1, room2); - - SearchDocument address = new SearchDocument(); - address.put("StreetAddress", "One Microsoft way"); - address.put("City", "Redmond"); - address.put("StateProvince", "Washington"); - address.put("PostalCode", "98052"); - address.put("Country", "US"); - - // TODO (alzimmer): Determine if this should be used to create the hotel document. - SearchDocument location = new SearchDocument(); - location.put("type", "Point"); - location.put("coordinates", Arrays.asList(-122.131577, 47.678581)); - location.put("crs", null); - - SearchDocument hotel = new SearchDocument(); - hotel.put("HotelId", hotelId); - hotel.put("HotelName", "Fancy Stay Hotel"); - hotel.put("Description", - "Best hotel in town if you like luxury hotels. They have an amazing infinity pool, a spa, and a really helpful concierge. The location is perfect -- right downtown, close to all the tourist attractions. We highly recommend this hotel."); - hotel.put("Description_fr", null); - hotel.put("Address", address); - hotel.put("Location", null); - hotel.put("Category", "Luxury"); - hotel.put("Tags", Arrays.asList("pool", "view", "wifi", "concierge")); - hotel.put("LastRenovationDate", OffsetDateTime.parse("2019-01-30T00:00:00Z")); - hotel.put("ParkingIncluded", true); - hotel.put("SmokingAllowed", true); - hotel.put("Rating", 5); - hotel.put("Rooms", rooms); - - return hotel; - } - - void assertSuccessfulIndexResult(IndexingResult result, String key, int statusCode) { - assertEquals(result.getKey(), key); - assertEquals(result.getStatusCode(), statusCode); - assertTrue(result.isSucceeded()); - } - - static void assertFailedIndexResult(IndexingResult result, String key, int statusCode) { - assertEquals(result.getKey(), key); - assertEquals(result.getStatusCode(), statusCode); - assertEquals(result.getErrorMessage(), "Document not found."); - assertFalse(result.isSucceeded()); - } - - static void assertIndexActionSucceeded(String key, IndexingResult result, int expectedStatusCode) { - assertEquals(key, result.getKey()); - assertTrue(result.isSucceeded()); - assertNull(result.getErrorMessage()); - assertEquals(expectedStatusCode, result.getStatusCode()); - } - - @SuppressWarnings({ "UseOfObsoleteDateTimeApi", "deprecation" }) - List getBoundaryValues() { - Date maxEpoch = Date.from(Instant.ofEpochMilli(253402300799000L)); - Date minEpoch = Date.from(Instant.ofEpochMilli(-2208988800000L)); - return Arrays.asList( - // Minimum values - new Hotel().hotelId(getRandomDocumentKey()) - .category("") - .lastRenovationDate(new Date(minEpoch.getYear(), minEpoch.getMonth(), minEpoch.getDate(), - minEpoch.getHours(), minEpoch.getMinutes(), minEpoch.getSeconds())) - .location(new GeoPoint(-180.0, -90.0)) // South pole, date line from the west - .parkingIncluded(false) - .rating(Integer.MIN_VALUE) - .tags(Collections.emptyList()) - .address(new HotelAddress()) - .rooms(Collections.singletonList(new HotelRoom().baseRate(Double.MIN_VALUE))), - // Maximum values - new Hotel().hotelId(getRandomDocumentKey()) - .category("test") // No meaningful string max since there is no length limit (other than payload size or term length). - .lastRenovationDate(new Date(maxEpoch.getYear(), maxEpoch.getMonth(), maxEpoch.getDate(), - maxEpoch.getHours(), maxEpoch.getMinutes(), maxEpoch.getSeconds())) - .location(new GeoPoint(180.0, 90.0)) // North pole, date line from the east - .parkingIncluded(true) - .rating(Integer.MAX_VALUE) - .tags(Collections.singletonList("test")) // No meaningful string max; see above. - .address(new HotelAddress().city("Maximum")) - .rooms(Collections.singletonList(new HotelRoom().baseRate(Double.MAX_VALUE))), - // Other boundary values #1 - new Hotel().hotelId(getRandomDocumentKey()) - .category(null) - .lastRenovationDate(null) - .location(new GeoPoint(0.0, 0.0)) // Equator, meridian - .parkingIncluded(null) - .rating(null) - .tags(Collections.emptyList()) - .address(new HotelAddress().city("Maximum")) - .rooms(Collections.singletonList(new HotelRoom().baseRate(Double.NEGATIVE_INFINITY))), - // Other boundary values #2 - new Hotel().hotelId(getRandomDocumentKey()) - .location(null) - .tags(Collections.emptyList()) - .rooms(Collections.singletonList(new HotelRoom().baseRate(Double.POSITIVE_INFINITY))), - // Other boundary values #3 - new Hotel().hotelId(getRandomDocumentKey()) - .tags(Collections.emptyList()) - .rooms(Collections.singletonList(new HotelRoom().baseRate(Double.NaN))), - // Other boundary values #4 - new Hotel().hotelId(getRandomDocumentKey()) - .category(null) - .tags(Collections.emptyList()) - .rooms(Collections.emptyList())); - } - - @SuppressWarnings({ "UseOfObsoleteDateTimeApi" }) - private static Hotel canMergeStaticallyTypedDocumentsOriginal(String key) { - // Define hotels - return new Hotel().hotelId(key) - .hotelName("Secret Point Motel") - .description( - "The hotel is ideally located on the main commercial artery of the city in the heart of New York. A few minutes away is Time's Square and the historic centre of the city, as well as other places of interest that make New York one of America's most attractive and cosmopolitan cities.") - .descriptionFr( - "L'hôtel est idéalement situé sur la principale artère commerciale de la ville en plein cœur de New York. A quelques minutes se trouve la place du temps et le centre historique de la ville, ainsi que d'autres lieux d'intérêt qui font de New York l'une des villes les plus attractives et cosmopolites de l'Amérique.") - .category("Boutique") - .tags(Arrays.asList("pool", "air conditioning", "concierge")) - .parkingIncluded(false) - .smokingAllowed(true) - .lastRenovationDate(parseDate("2010-06-27T00:00:00Z")) - .rating(4) - .location(new GeoPoint(-73.975403, 40.760586)) - .address(new HotelAddress().streetAddress("677 5th Ave") - .city("New York") - .stateProvince("NY") - .country("USA") - .postalCode("10022")) - .rooms(Arrays.asList( - new HotelRoom().description("Budget Room, 1 Queen Bed (Cityside)") - .descriptionFr("Chambre Économique, 1 grand lit (côté ville)") - .type("Budget Room") - .baseRate(9.69) - .bedOptions("1 Queen Bed") - .sleepsCount(2) - .smokingAllowed(true) - .tags(new String[] { "vcr/dvd" }), - new HotelRoom().description("Budget Room, 1 King Bed (Mountain View)") - .descriptionFr("Chambre Économique, 1 très grand lit (Mountain View)") - .type("Budget Room") - .baseRate(8.09) - .bedOptions("1 King Bed") - .sleepsCount(2) - .smokingAllowed(true) - .tags(new String[] { "vcr/dvd", "jacuzzi tub" }))); - } - - private static Hotel canMergeStaticallyTypedDocumentsUpdated(String key) { - // Update category, tags, parking included, rating, and rooms. Erase description, last renovation date, location and address. - return new Hotel().hotelId(key) - .hotelName("Secret Point Motel") - .description(null) - .category("Economy") - .tags(Arrays.asList("pool", "air conditioning")) - .parkingIncluded(true) - .lastRenovationDate(null) - .rating(3) - //.location(null) - .address(new HotelAddress()) - .rooms(Collections.singletonList(new HotelRoom().description(null) - .type("Budget Room") - .baseRate(10.5) - .bedOptions("1 Queen Bed") - .sleepsCount(2) - .tags(new String[] { "vcr/dvd", "balcony" }))); - } - - @SuppressWarnings({ "UseOfObsoleteDateTimeApi" }) - private static Hotel canMergeStaticallyTypedDocumentsExpected(String key) { - // Fields whose values get updated are updated, and whose values get erased remain the same. - return new Hotel().hotelId(key) - .hotelName("Secret Point Motel") - .description( - "The hotel is ideally located on the main commercial artery of the city in the heart of New York. A few minutes away is Time's Square and the historic centre of the city, as well as other places of interest that make New York one of America's most attractive and cosmopolitan cities.") - .descriptionFr( - "L'hôtel est idéalement situé sur la principale artère commerciale de la ville en plein cœur de New York. A quelques minutes se trouve la place du temps et le centre historique de la ville, ainsi que d'autres lieux d'intérêt qui font de New York l'une des villes les plus attractives et cosmopolites de l'Amérique.") - .category("Economy") - .tags(Arrays.asList("pool", "air conditioning")) - .parkingIncluded(true) - .smokingAllowed(true) - .lastRenovationDate(parseDate("2010-06-27T00:00:00Z")) - .rating(3) - .location(new GeoPoint(-73.975403, 40.760586)) - .address(new HotelAddress().streetAddress("677 5th Ave") - .city("New York") - .stateProvince("NY") - .country("USA") - .postalCode("10022")) - .rooms(Collections.singletonList(new HotelRoom().description(null) - .type("Budget Room") - .baseRate(10.5) - .bedOptions("1 Queen Bed") - .sleepsCount(2) - .tags(new String[] { "vcr/dvd", "balcony" }))); - } - - @SuppressWarnings({ "UseOfObsoleteDateTimeApi" }) - private static LoudHotel canSetExplicitNullsInStaticallyTypedDocumentOriginal(String key) { - return new LoudHotel().HOTELID(key) - .HOTELNAME("Secret Point Motel") - .DESCRIPTION( - "The hotel is ideally located on the main commercial artery of the city in the heart of New York. A few minutes away is Time's Square and the historic centre of the city, as well as other places of interest that make New York one of America's most attractive and cosmopolitan cities.") - .DESCRIPTIONFRENCH( - "L'hôtel est idéalement situé sur la principale artère commerciale de la ville en plein cœur de New York. A quelques minutes se trouve la place du temps et le centre historique de la ville, ainsi que d'autres lieux d'intérêt qui font de New York l'une des villes les plus attractives et cosmopolites de l'Amérique.") - .CATEGORY("Boutique") - .TAGS(Arrays.asList("pool", "air conditioning", "concierge")) - .PARKINGINCLUDED(false) - .SMOKINGALLOWED(false) - .LASTRENOVATIONDATE(parseDate("1970-01-18T05:00:00Z")) - .RATING(4) - .LOCATION(new GeoPoint(-73.975403, 40.760586)) - .ADDRESS(new HotelAddress().streetAddress("677 5th Ave") - .city("New York") - .stateProvince("NY") - .country("USA") - .postalCode("10022")) - .ROOMS(Arrays.asList( - new HotelRoom().description("Budget Room, 1 Queen Bed (Cityside)") - .descriptionFr("Chambre Économique, 1 grand lit (côté ville)") - .type("Budget Room") - .baseRate(9.69) - .bedOptions("1 Queen Bed") - .sleepsCount(2) - .smokingAllowed(true) - .tags(new String[] { "vcr/dvd" }), - new HotelRoom().description("Budget Room, 1 King Bed (Mountain View)") - .descriptionFr("Chambre Économique, 1 très grand lit (Mountain View)") - .type("Budget Room") - .baseRate(8.09) - .bedOptions("1 King Bed") - .sleepsCount(2) - .smokingAllowed(true) - .tags(new String[] { "vcr/dvd", "jacuzzi tub" }))); - } - - @SuppressWarnings({ "UseOfObsoleteDateTimeApi" }) - private static LoudHotel canSetExplicitNullsInStaticallyTypedDocumentUpdated(String key) { - return new LoudHotel().HOTELID(key) - .DESCRIPTION(null) // This property has JsonInclude.Include.ALWAYS, so this will null out the field. - .CATEGORY(null) // This property doesn't have JsonInclude.Include.ALWAYS, so this should have no effect. - .TAGS(Arrays.asList("pool", "air conditioning")) - .PARKINGINCLUDED(true) - .LASTRENOVATIONDATE(parseDate("1970-01-18T05:00:00Z")) - .RATING(3) - //.LOCATION(null) // This property has JsonInclude.Include.ALWAYS, so this will null out the field. - .ADDRESS(new HotelAddress()) - .ROOMS(Collections.singletonList(new HotelRoom().description(null) - .type("Budget Room") - .baseRate(10.5) - .smokingAllowed(false) - .tags(new String[] { "vcr/dvd", "balcony" }))); - } - - @SuppressWarnings({ "UseOfObsoleteDateTimeApi" }) - private static LoudHotel canSetExplicitNullsInStaticallyTypedDocumentExpected(String key) { - return new LoudHotel().HOTELID(key) - .HOTELNAME("Secret Point Motel") - .DESCRIPTION(null) - .DESCRIPTIONFRENCH( - "L'hôtel est idéalement situé sur la principale artère commerciale de la ville en plein cœur de New York. A quelques minutes se trouve la place du temps et le centre historique de la ville, ainsi que d'autres lieux d'intérêt qui font de New York l'une des villes les plus attractives et cosmopolites de l'Amérique.") - .CATEGORY("Boutique") - .TAGS(Arrays.asList("pool", "air conditioning")) - .PARKINGINCLUDED(true) - .SMOKINGALLOWED(false) - .LASTRENOVATIONDATE(parseDate("1970-01-18T05:00:00Z")) - .RATING(3) - //.LOCATION(null) - .ADDRESS(new HotelAddress().streetAddress("677 5th Ave") - .city("New York") - .stateProvince("NY") - .country("USA") - .postalCode("10022")) - .ROOMS(Collections.singletonList( - // Regardless of NullValueHandling, this should look like the merged doc with unspecified fields as null - // because we don't support partial updates for complex collections. - new HotelRoom().description(null) - .descriptionFr(null) - .type("Budget Room") - .baseRate(10.5) - .bedOptions(null) - .sleepsCount(null) - .smokingAllowed(false) - .tags(new String[] { "vcr/dvd", "balcony" }))); - } - - private static SearchDocument canMergeDynamicDocumentsOriginal(String key) { - SearchDocument originalDoc = new SearchDocument(); - originalDoc.put("HotelId", key); - originalDoc.put("HotelName", "Secret Point Motel"); - originalDoc.put("Description", - "The hotel is ideally located on the main commercial artery of the city in the heart of New York. A few minutes away is Time's Square and the historic centre of the city, as well as other places of interest that make New York one of America's most attractive and cosmopolitan cities."); - originalDoc.put("Description_fr", - "L'hôtel est idéalement situé sur la principale artère commerciale de la ville en plein cœur de New York. A quelques minutes se trouve la place du temps et le centre historique de la ville, ainsi que d'autres lieux d'intérêt qui font de New York l'une des villes les plus attractives et cosmopolites de l'Amérique."); - originalDoc.put("Category", "Boutique"); - originalDoc.put("Tags", Arrays.asList("pool", "air conditioning", "concierge")); - originalDoc.put("ParkingIncluded", false); - originalDoc.put("SmokingAllowed", true); - originalDoc.put("LastRenovationDate", OffsetDateTime.parse("2010-06-27T00:00:00Z")); - originalDoc.put("Rating", 4); - originalDoc.put("Location", new GeoPoint(-73.965403, 40.760586)); - - SearchDocument originalAddress = new SearchDocument(); - originalAddress.put("StreetAddress", "677 5th Ave"); - originalAddress.put("City", "New York"); - originalAddress.put("StateProvince", "NY"); - originalAddress.put("PostalCode", "10022"); - originalAddress.put("Country", "USA"); - originalDoc.put("Address", originalAddress); - - SearchDocument originalRoom1 = new SearchDocument(); - originalRoom1.put("Description", "Budget Room, 1 Queen Bed (Cityside)"); - originalRoom1.put("Description_fr", "Chambre Économique, 1 grand lit (côté ville)"); - originalRoom1.put("Type", "Budget Room"); - originalRoom1.put("BaseRate", 9.69); - originalRoom1.put("BedOptions", "1 Queen Bed"); - originalRoom1.put("SleepsCount", 2); - originalRoom1.put("SmokingAllowed", true); - originalRoom1.put("Tags", Collections.singletonList("vcr/dvd")); - - SearchDocument originalRoom2 = new SearchDocument(); - originalRoom2.put("Description", "Budget Room, 1 King Bed (Mountain View)"); - originalRoom2.put("Description_fr", "Chambre Économique, 1 très grand lit (Mountain View)"); - originalRoom2.put("Type", "Budget Room"); - originalRoom2.put("BaseRate", 8.09); - originalRoom2.put("BedOptions", "1 King Bed"); - originalRoom2.put("SleepsCount", 2); - originalRoom2.put("SmokingAllowed", true); - originalRoom2.put("Tags", Arrays.asList("vcr/dvd", "jacuzzi tub")); - - originalDoc.put("Rooms", Arrays.asList(originalRoom1, originalRoom2)); - - return originalDoc; - } - - private static SearchDocument canMergeDynamicDocumentsUpdated(String key) { - SearchDocument updatedDoc = new SearchDocument(); - updatedDoc.put("HotelId", key); - updatedDoc.put("Description", null); - updatedDoc.put("Category", "Economy"); - updatedDoc.put("Tags", Arrays.asList("pool", "air conditioning")); - updatedDoc.put("ParkingIncluded", true); - updatedDoc.put("LastRenovationDate", null); - updatedDoc.put("Rating", 3); - updatedDoc.put("Location", null); - updatedDoc.put("Address", new SearchDocument()); - - SearchDocument updatedRoom1 = new SearchDocument(); - updatedRoom1.put("Description", null); - updatedRoom1.put("Type", "Budget Room"); - updatedRoom1.put("BaseRate", 10.5); - updatedRoom1.put("BedOptions", "1 Queen Bed"); - updatedRoom1.put("SleepsCount", 2); - updatedRoom1.put("SmokingAllowed", true); - updatedRoom1.put("Tags", Arrays.asList("vcr/dvd", "balcony")); - updatedDoc.put("Rooms", Collections.singletonList(updatedRoom1)); - - return updatedDoc; - } - - private static SearchDocument canMergeDynamicDocumentsExpected(String key) { - SearchDocument expectedDoc = new SearchDocument(); - expectedDoc.put("HotelId", key); - expectedDoc.put("HotelName", "Secret Point Motel"); - expectedDoc.put("Description", null); - expectedDoc.put("Description_fr", - "L'hôtel est idéalement situé sur la principale artère commerciale de la ville en plein cœur de New York. A quelques minutes se trouve la place du temps et le centre historique de la ville, ainsi que d'autres lieux d'intérêt qui font de New York l'une des villes les plus attractives et cosmopolites de l'Amérique."); - expectedDoc.put("Category", "Economy"); - expectedDoc.put("Tags", Arrays.asList("pool", "air conditioning")); - expectedDoc.put("ParkingIncluded", true); - expectedDoc.put("SmokingAllowed", true); - expectedDoc.put("LastRenovationDate", null); - expectedDoc.put("Rating", 3); - expectedDoc.put("Location", null); - - LinkedHashMap expectedAddress = new LinkedHashMap<>(); - expectedAddress.put("StreetAddress", "677 5th Ave"); - expectedAddress.put("City", "New York"); - expectedAddress.put("StateProvince", "NY"); - expectedAddress.put("PostalCode", "10022"); - expectedAddress.put("Country", "USA"); - expectedDoc.put("Address", expectedAddress); - - // This should look like the merged doc with unspecified fields as null because we don't support - // partial updates for complex collections. - LinkedHashMap expectedRoom = new LinkedHashMap<>(); - expectedRoom.put("Description", null); - expectedRoom.put("Description_fr", null); - expectedRoom.put("Type", "Budget Room"); - expectedRoom.put("BaseRate", 10.5); - expectedRoom.put("BedOptions", "1 Queen Bed"); - expectedRoom.put("SleepsCount", 2); - expectedRoom.put("SmokingAllowed", true); - expectedRoom.put("Tags", Arrays.asList("vcr/dvd", "balcony")); - - List> expectedRooms = new ArrayList<>(); - expectedRooms.add(expectedRoom); - expectedDoc.put("Rooms", expectedRooms); - - return expectedDoc; - } -} diff --git a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/LookupTests.java b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/LookupTests.java deleted file mode 100644 index d6261c3a1317..000000000000 --- a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/LookupTests.java +++ /dev/null @@ -1,893 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -package com.azure.search.documents; - -import com.azure.core.http.rest.Response; -import com.azure.core.models.GeoPoint; -import com.azure.core.test.TestProxyTestBase; -import com.azure.core.test.TestMode; -import com.azure.core.util.Context; -import com.azure.search.documents.indexes.SearchIndexClient; -import com.azure.search.documents.indexes.models.IndexDocumentsBatch; -import com.azure.search.documents.indexes.models.SearchField; -import com.azure.search.documents.indexes.models.SearchFieldDataType; -import com.azure.search.documents.indexes.models.SearchIndex; -import com.azure.search.documents.test.environment.models.Hotel; -import com.azure.search.documents.test.environment.models.HotelAddress; -import com.azure.search.documents.test.environment.models.HotelRoom; -import com.azure.search.documents.test.environment.models.ModelWithPrimitiveCollections; -import org.junit.jupiter.api.AfterAll; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.parallel.Execution; -import org.junit.jupiter.api.parallel.ExecutionMode; -import reactor.test.StepVerifier; - -import java.time.Instant; -import java.time.OffsetDateTime; -import java.time.ZoneId; -import java.time.ZoneOffset; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Base64; -import java.util.Collections; -import java.util.Date; -import java.util.List; -import java.util.function.BiConsumer; - -import static com.azure.search.documents.TestHelpers.assertMapEquals; -import static com.azure.search.documents.TestHelpers.assertObjectEquals; -import static com.azure.search.documents.TestHelpers.createSharedSearchIndexClient; -import static com.azure.search.documents.TestHelpers.setupSharedIndex; -import static com.azure.search.documents.TestHelpers.uploadDocument; -import static java.lang.Double.NEGATIVE_INFINITY; -import static java.lang.Double.NaN; -import static java.lang.Double.POSITIVE_INFINITY; -import static org.junit.jupiter.api.Assertions.assertEquals; - -@Execution(ExecutionMode.CONCURRENT) -public class LookupTests extends SearchTestBase { - private static final String HOTEL_INDEX_NAME = "azsearch-lookup-shared-hotel-instance"; - private static final String TYPE_INDEX_NAME = "azsearch-lookup-shared-type-instance"; - - private static SearchIndexClient searchIndexClient; - - @BeforeAll - public static void setupClass() { - TestProxyTestBase.setupClass(); - - if (TEST_MODE == TestMode.PLAYBACK) { - return; - } - - searchIndexClient = setupSharedIndex(HOTEL_INDEX_NAME, HOTELS_TESTS_INDEX_DATA_JSON, null); - setupIndexWithDataTypes(); - } - - @AfterAll - public static void cleanupClass() { - if (TEST_MODE != TestMode.PLAYBACK) { - searchIndexClient.deleteIndex(HOTEL_INDEX_NAME); - searchIndexClient.deleteIndex(TYPE_INDEX_NAME); - } - } - - private SearchClient getClient(String indexName) { - return getSearchClientBuilder(indexName, true).buildClient(); - } - - private SearchAsyncClient getAsyncClient(String indexName) { - return getSearchClientBuilder(indexName, false).buildAsyncClient(); - } - - private String getRandomDocumentKey() { - return testResourceNamer.randomName("key", 32); - } - - @Test - public void canGetStaticallyTypedDocumentSync() { - SearchClient client = getClient(HOTEL_INDEX_NAME); - - Hotel expected = prepareExpectedHotel(getRandomDocumentKey()); - uploadDocument(client, expected); - - Hotel actual = client.getDocument(expected.hotelId(), Hotel.class); - assertObjectEquals(expected, actual, true, "boundingBox"); - } - - @Test - public void canGetStaticallyTypedDocumentAsync() { - SearchAsyncClient asyncClient = getAsyncClient(HOTEL_INDEX_NAME); - - Hotel expected = prepareExpectedHotel(getRandomDocumentKey()); - uploadDocument(asyncClient, expected); - - getAndValidateDocumentAsync(asyncClient, expected.hotelId(), Hotel.class, expected, - (ignored, actual) -> assertObjectEquals(expected, actual, true, "boundingBox")); - } - - @Test - public void canGetStaticallyTypedDocumentWithNullOrEmptyValuesSync() { - SearchClient client = getClient(HOTEL_INDEX_NAME); - - Hotel expected = prepareEmptyHotel(getRandomDocumentKey()); - uploadDocument(client, expected); - - Hotel actual = client.getDocument(expected.hotelId(), Hotel.class); - assertObjectEquals(expected, actual, true); - } - - @Test - public void canGetStaticallyTypedDocumentWithNullOrEmptyValuesAsync() { - SearchAsyncClient asyncClient = getAsyncClient(HOTEL_INDEX_NAME); - - Hotel expected = prepareEmptyHotel(getRandomDocumentKey()); - uploadDocument(asyncClient, expected); - - getAndValidateDocumentAsync(asyncClient, expected.hotelId(), Hotel.class, expected, - (ignored, actual) -> assertObjectEquals(expected, actual, true)); - } - - @Test - public void canGetStaticallyTypedDocumentWithPascalCaseFieldsSync() { - SearchClient client = getClient(HOTEL_INDEX_NAME); - - Hotel expected = preparePascalCaseFieldsHotel(getRandomDocumentKey()); - uploadDocument(client, expected); - - Hotel actual = client.getDocument(expected.hotelId(), Hotel.class); - assertObjectEquals(expected, actual, true); - } - - @Test - public void canGetStaticallyTypedDocumentWithPascalCaseFieldsAsync() { - SearchAsyncClient asyncClient = getAsyncClient(HOTEL_INDEX_NAME); - - Hotel expected = preparePascalCaseFieldsHotel(getRandomDocumentKey()); - uploadDocument(asyncClient, expected); - - getAndValidateDocumentAsync(asyncClient, expected.hotelId(), Hotel.class, expected, - (ignored, actual) -> assertObjectEquals(expected, actual, true)); - } - - @Test - public void canRoundTripStaticallyTypedPrimitiveCollectionsSync() { - SearchClient client = getClient(TYPE_INDEX_NAME); - - ModelWithPrimitiveCollections expected = preparePrimitivesModel(getRandomDocumentKey()); - uploadDocument(client, expected); - - ModelWithPrimitiveCollections actual = client.getDocument(expected.key(), ModelWithPrimitiveCollections.class); - assertObjectEquals(expected, actual, true, "boundingBox"); - } - - @Test - public void canRoundTripStaticallyTypedPrimitiveCollectionsAsync() { - SearchAsyncClient asyncClient = getAsyncClient(TYPE_INDEX_NAME); - - ModelWithPrimitiveCollections expected = preparePrimitivesModel(getRandomDocumentKey()); - uploadDocument(asyncClient, expected); - - getAndValidateDocumentAsync(asyncClient, expected.key(), ModelWithPrimitiveCollections.class, expected, - (ignored, actual) -> assertObjectEquals(expected, actual, true, "boundingBox")); - } - - @Test - public void getStaticallyTypedDocumentSetsUnselectedFieldsToNullSync() { - SearchClient client = getClient(HOTEL_INDEX_NAME); - - Hotel indexedDoc = prepareSelectedFieldsHotel(getRandomDocumentKey()); - Hotel expected = new Hotel().hotelName("Countryside Hotel") - .description("Save up to 50% off traditional hotels. Free WiFi, great location near downtown, " - + "full kitchen, washer & dryer, 24/7 support, bowling alley, fitness center and more.") - .address(new HotelAddress().city("Durham")) - .rooms(Arrays.asList(new HotelRoom().baseRate(2.44), new HotelRoom().baseRate(7.69))); - - uploadDocument(client, indexedDoc); - - List selectedFields = Arrays.asList("Description", "HotelName", "Address/City", "Rooms/BaseRate"); - Response actual - = client.getDocumentWithResponse(indexedDoc.hotelId(), Hotel.class, selectedFields, Context.NONE); - assertObjectEquals(expected, actual.getValue(), true); - } - - @Test - public void getStaticallyTypedDocumentSetsUnselectedFieldsToNullAsync() { - SearchAsyncClient asyncClient = getAsyncClient(HOTEL_INDEX_NAME); - - Hotel indexedDoc = prepareSelectedFieldsHotel(getRandomDocumentKey()); - Hotel expected = new Hotel().hotelName("Countryside Hotel") - .description("Save up to 50% off traditional hotels. Free WiFi, great location near downtown, " - + "full kitchen, washer & dryer, 24/7 support, bowling alley, fitness center and more.") - .address(new HotelAddress().city("Durham")) - .rooms(Arrays.asList(new HotelRoom().baseRate(2.44), new HotelRoom().baseRate(7.69))); - - uploadDocument(asyncClient, indexedDoc); - - List selectedFields = Arrays.asList("Description", "HotelName", "Address/City", "Rooms/BaseRate"); - getAndValidateDocumentAsync(asyncClient, indexedDoc.hotelId(), Hotel.class, selectedFields, expected, - (ignored, actual) -> assertObjectEquals(expected, actual, true)); - } - - @Test - public void canGetDynamicDocumentWithNullOrEmptyValuesSync() { - SearchClient client = getClient(HOTEL_INDEX_NAME); - - String hotelId = getRandomDocumentKey(); - SearchDocument expectedDoc = new SearchDocument(); - expectedDoc.put("HotelId", hotelId); - expectedDoc.put("HotelName", null); - expectedDoc.put("Tags", Collections.emptyList()); - expectedDoc.put("ParkingIncluded", null); - expectedDoc.put("LastRenovationDate", null); - expectedDoc.put("Rating", null); - expectedDoc.put("Location", null); - expectedDoc.put("Address", null); - - SearchDocument room = new SearchDocument(); - room.put("BaseRate", null); - room.put("BedOptions", null); - room.put("SleepsCount", null); - room.put("SmokingAllowed", null); - room.put("Tags", Collections.emptyList()); - - expectedDoc.put("Rooms", Collections.singletonList(room)); - - uploadDocument(client, expectedDoc); - // Select only the fields set in the test case. - List selectedFields = Arrays.asList("HotelId", "HotelName", "Tags", "ParkingIncluded", - "LastRenovationDate", "Rating", "Location", "Address", "Rooms/BaseRate", "Rooms/BedOptions", - "Rooms/SleepsCount", "Rooms/SmokingAllowed", "Rooms/Tags"); - - Response response - = client.getDocumentWithResponse(hotelId, SearchDocument.class, selectedFields, Context.NONE); - assertObjectEquals(expectedDoc, response.getValue(), true); - } - - @Test - public void canGetDynamicDocumentWithNullOrEmptyValuesAsync() { - SearchAsyncClient asyncClient = getAsyncClient(HOTEL_INDEX_NAME); - - String hotelId = getRandomDocumentKey(); - SearchDocument expectedDoc = new SearchDocument(); - expectedDoc.put("HotelId", hotelId); - expectedDoc.put("HotelName", null); - expectedDoc.put("Tags", Collections.emptyList()); - expectedDoc.put("ParkingIncluded", null); - expectedDoc.put("LastRenovationDate", null); - expectedDoc.put("Rating", null); - expectedDoc.put("Location", null); - expectedDoc.put("Address", null); - - SearchDocument room = new SearchDocument(); - room.put("BaseRate", null); - room.put("BedOptions", null); - room.put("SleepsCount", null); - room.put("SmokingAllowed", null); - room.put("Tags", Collections.emptyList()); - - expectedDoc.put("Rooms", Collections.singletonList(room)); - - uploadDocument(asyncClient, expectedDoc); - // Select only the fields set in the test case. - List selectedFields = Arrays.asList("HotelId", "HotelName", "Tags", "ParkingIncluded", - "LastRenovationDate", "Rating", "Location", "Address", "Rooms/BaseRate", "Rooms/BedOptions", - "Rooms/SleepsCount", "Rooms/SmokingAllowed", "Rooms/Tags"); - - getAndValidateDocumentAsync(asyncClient, hotelId, SearchDocument.class, selectedFields, expectedDoc, - (ignored, actual) -> assertObjectEquals(expectedDoc, actual, true)); - } - - @Test - public void getDynamicDocumentWithEmptyObjectsReturnsObjectsFullOfNullsSync() { - SearchClient client = getClient(HOTEL_INDEX_NAME); - - String hotelId = getRandomDocumentKey(); - SearchDocument originalDoc = new SearchDocument(); - originalDoc.put("HotelId", hotelId); - originalDoc.put("Address", new SearchDocument()); - - SearchDocument expectedDoc = new SearchDocument(); - expectedDoc.put("HotelId", hotelId); - - SearchDocument address = new SearchDocument(); - address.put("StreetAddress", null); - address.put("City", null); - address.put("StateProvince", null); - address.put("Country", null); - address.put("PostalCode", null); - expectedDoc.put("Address", address); - - uploadDocument(client, originalDoc); - // Select only the fields set in the test case. - List selectedFields = Arrays.asList("HotelId", "Address"); - - Response response - = client.getDocumentWithResponse(hotelId, SearchDocument.class, selectedFields, Context.NONE); - assertObjectEquals(expectedDoc, response.getValue(), true); - } - - @Test - public void getDynamicDocumentWithEmptyObjectsReturnsObjectsFullOfNullsAsync() { - SearchAsyncClient asyncClient = getAsyncClient(HOTEL_INDEX_NAME); - - String hotelId = getRandomDocumentKey(); - SearchDocument originalDoc = new SearchDocument(); - originalDoc.put("HotelId", hotelId); - originalDoc.put("Address", new SearchDocument()); - - SearchDocument expectedDoc = new SearchDocument(); - expectedDoc.put("HotelId", hotelId); - - SearchDocument address = new SearchDocument(); - address.put("StreetAddress", null); - address.put("City", null); - address.put("StateProvince", null); - address.put("Country", null); - address.put("PostalCode", null); - expectedDoc.put("Address", address); - - uploadDocument(asyncClient, originalDoc); - // Select only the fields set in the test case. - List selectedFields = Arrays.asList("HotelId", "Address"); - - getAndValidateDocumentAsync(asyncClient, hotelId, SearchDocument.class, selectedFields, expectedDoc, - (ignored, actual) -> assertObjectEquals(expectedDoc, actual, true)); - } - - @Test - public void emptyDynamicallyTypedPrimitiveCollectionsRoundTripAsObjectArraysSync() { - SearchClient client = getClient(TYPE_INDEX_NAME); - - String docKey = getRandomDocumentKey(); - - SearchDocument originalDoc = new SearchDocument(); - originalDoc.put("Key", docKey); - originalDoc.put("Dates", new Object[] { }); - originalDoc.put("Doubles", new Double[] { }); - originalDoc.put("Bools", new boolean[] { }); - originalDoc.put("Longs", new Long[] { }); - originalDoc.put("Strings", new String[] { }); - originalDoc.put("Ints", new int[] { }); - originalDoc.put("Points", new Object[] { }); - - SearchDocument expectedDoc = new SearchDocument(); - expectedDoc.put("Key", docKey); - expectedDoc.put("Doubles", Collections.emptyList()); - expectedDoc.put("Bools", Collections.emptyList()); - expectedDoc.put("Longs", Collections.emptyList()); - expectedDoc.put("Strings", Collections.emptyList()); - expectedDoc.put("Ints", Collections.emptyList()); - expectedDoc.put("Points", Collections.emptyList()); - expectedDoc.put("Dates", Collections.emptyList()); - - uploadDocument(client, originalDoc); - - SearchDocument actualDoc = client.getDocument(docKey, SearchDocument.class); - assertEquals(expectedDoc, actualDoc); - } - - @Test - public void emptyDynamicallyTypedPrimitiveCollectionsRoundTripAsObjectArraysAsync() { - SearchAsyncClient asyncClient = getAsyncClient(TYPE_INDEX_NAME); - - String docKey = getRandomDocumentKey(); - - SearchDocument originalDoc = new SearchDocument(); - originalDoc.put("Key", docKey); - originalDoc.put("Dates", new Object[] { }); - originalDoc.put("Doubles", new Double[] { }); - originalDoc.put("Bools", new boolean[] { }); - originalDoc.put("Longs", new Long[] { }); - originalDoc.put("Strings", new String[] { }); - originalDoc.put("Ints", new int[] { }); - originalDoc.put("Points", new Object[] { }); - - SearchDocument expectedDoc = new SearchDocument(); - expectedDoc.put("Key", docKey); - expectedDoc.put("Doubles", Collections.emptyList()); - expectedDoc.put("Bools", Collections.emptyList()); - expectedDoc.put("Longs", Collections.emptyList()); - expectedDoc.put("Strings", Collections.emptyList()); - expectedDoc.put("Ints", Collections.emptyList()); - expectedDoc.put("Points", Collections.emptyList()); - expectedDoc.put("Dates", Collections.emptyList()); - - uploadDocument(asyncClient, originalDoc); - - getAndValidateDocumentAsync(asyncClient, docKey, SearchDocument.class, expectedDoc, Assertions::assertEquals); - } - - @Test - public void emptyDynamicObjectsInCollectionExpandedOnGetWhenCollectionFieldSelectedSync() { - SearchClient client = getClient(HOTEL_INDEX_NAME); - - String hotelId = getRandomDocumentKey(); - SearchDocument originalDoc = new SearchDocument(); - originalDoc.put("HotelId", hotelId); - - SearchDocument originalRoom = new SearchDocument(); - originalRoom.put("BaseRate", null); - originalRoom.put("BedOptions", null); - originalRoom.put("SleepsCount", null); - originalRoom.put("SmokingAllowed", null); - originalRoom.put("Tags", Collections.emptyList()); - originalDoc.put("Rooms", Arrays.asList(new SearchDocument(), originalRoom)); - - SearchDocument expectedDoc = new SearchDocument(); - expectedDoc.put("HotelId", hotelId); - - SearchDocument expectedRoom1 = new SearchDocument(); - expectedRoom1.put("Description", null); - expectedRoom1.put("Description_fr", null); - expectedRoom1.put("Type", null); - expectedRoom1.put("BaseRate", null); - expectedRoom1.put("BedOptions", null); - expectedRoom1.put("SleepsCount", null); - expectedRoom1.put("SmokingAllowed", null); - expectedRoom1.put("Tags", Collections.emptyList()); - - SearchDocument expectedRoom2 = new SearchDocument(); - expectedRoom2.put("Description", null); - expectedRoom2.put("Description_fr", null); - expectedRoom2.put("Type", null); - expectedRoom2.put("BaseRate", null); - expectedRoom2.put("BedOptions", null); - expectedRoom2.put("SleepsCount", null); - expectedRoom2.put("SmokingAllowed", null); - expectedRoom2.put("Tags", Collections.emptyList()); - - expectedDoc.put("Rooms", Arrays.asList(expectedRoom1, expectedRoom2)); - - uploadDocument(client, originalDoc); - List selectedFields = Arrays.asList("HotelId", "Rooms"); - - Response response - = client.getDocumentWithResponse(hotelId, SearchDocument.class, selectedFields, Context.NONE); - assertObjectEquals(expectedDoc, response.getValue(), true); - } - - @Test - public void emptyDynamicObjectsInCollectionExpandedOnGetWhenCollectionFieldSelectedAsync() { - SearchAsyncClient asyncClient = getAsyncClient(HOTEL_INDEX_NAME); - - String hotelId = getRandomDocumentKey(); - SearchDocument originalDoc = new SearchDocument(); - originalDoc.put("HotelId", hotelId); - - SearchDocument originalRoom = new SearchDocument(); - originalRoom.put("BaseRate", null); - originalRoom.put("BedOptions", null); - originalRoom.put("SleepsCount", null); - originalRoom.put("SmokingAllowed", null); - originalRoom.put("Tags", Collections.emptyList()); - originalDoc.put("Rooms", Arrays.asList(new SearchDocument(), originalRoom)); - - SearchDocument expectedDoc = new SearchDocument(); - expectedDoc.put("HotelId", hotelId); - - SearchDocument expectedRoom1 = new SearchDocument(); - expectedRoom1.put("Description", null); - expectedRoom1.put("Description_fr", null); - expectedRoom1.put("Type", null); - expectedRoom1.put("BaseRate", null); - expectedRoom1.put("BedOptions", null); - expectedRoom1.put("SleepsCount", null); - expectedRoom1.put("SmokingAllowed", null); - expectedRoom1.put("Tags", Collections.emptyList()); - - SearchDocument expectedRoom2 = new SearchDocument(); - expectedRoom2.put("Description", null); - expectedRoom2.put("Description_fr", null); - expectedRoom2.put("Type", null); - expectedRoom2.put("BaseRate", null); - expectedRoom2.put("BedOptions", null); - expectedRoom2.put("SleepsCount", null); - expectedRoom2.put("SmokingAllowed", null); - expectedRoom2.put("Tags", Collections.emptyList()); - - expectedDoc.put("Rooms", Arrays.asList(expectedRoom1, expectedRoom2)); - - uploadDocument(asyncClient, originalDoc); - List selectedFields = Arrays.asList("HotelId", "Rooms"); - - getAndValidateDocumentAsync(asyncClient, hotelId, SearchDocument.class, selectedFields, expectedDoc, - (expected, actual) -> assertObjectEquals(expected, actual, true)); - } - - @Test - public void getDynamicDocumentCannotAlwaysDetermineCorrectTypeSync() { - SearchClient client = getClient(HOTEL_INDEX_NAME); - - String hotelId = getRandomDocumentKey(); - SearchDocument indexedDoc = new SearchDocument(); - indexedDoc.put("HotelId", hotelId); - indexedDoc.put("LastRenovationDate", "2017-01-13T14:03:00.7552052-07:00"); - // Test that we don't confuse Geo-JSON & complex types. - indexedDoc.put("Location", new GeoPoint(-73.975403, 40.760586)); - indexedDoc.put("Rooms", - Collections.singletonList(new SearchDocument(Collections.singletonMap("BaseRate", NaN)))); - - SearchDocument expectedDoc = new SearchDocument(); - expectedDoc.put("HotelId", hotelId); - expectedDoc.put("LastRenovationDate", OffsetDateTime.of(2017, 1, 13, 21, 3, 0, 755000000, ZoneOffset.UTC)); - expectedDoc.put("Location", new GeoPoint(-73.975403, 40.760586)); - expectedDoc.put("Rooms", - Collections.singletonList(new SearchDocument(Collections.singletonMap("BaseRate", "NaN")))); - - client.indexDocuments(new IndexDocumentsBatch<>().addUploadActions(Collections.singletonList(indexedDoc))); - - // Select only the fields set in the test case. - List selectedFields = Arrays.asList("HotelId", "LastRenovationDate", "Location", "Rooms/BaseRate"); - assertMapEquals(expectedDoc, - client.getDocumentWithResponse(hotelId, SearchDocument.class, selectedFields, Context.NONE).getValue(), - true, "boundingBox", "properties"); - } - - @Test - public void getDynamicDocumentCannotAlwaysDetermineCorrectTypeAsync() { - SearchAsyncClient asyncClient = getAsyncClient(HOTEL_INDEX_NAME); - - String hotelId = getRandomDocumentKey(); - SearchDocument indexedDoc = new SearchDocument(); - indexedDoc.put("HotelId", hotelId); - indexedDoc.put("LastRenovationDate", "2017-01-13T14:03:00.7552052-07:00"); - // Test that we don't confuse Geo-JSON & complex types. - indexedDoc.put("Location", new GeoPoint(-73.975403, 40.760586)); - indexedDoc.put("Rooms", - Collections.singletonList(new SearchDocument(Collections.singletonMap("BaseRate", NaN)))); - - SearchDocument expectedDoc = new SearchDocument(); - expectedDoc.put("HotelId", hotelId); - expectedDoc.put("LastRenovationDate", OffsetDateTime.of(2017, 1, 13, 21, 3, 0, 755000000, ZoneOffset.UTC)); - expectedDoc.put("Location", new GeoPoint(-73.975403, 40.760586)); - expectedDoc.put("Rooms", - Collections.singletonList(new SearchDocument(Collections.singletonMap("BaseRate", "NaN")))); - - asyncClient.indexDocuments(new IndexDocumentsBatch<>().addUploadActions(Collections.singletonList(indexedDoc))) - .block(); - - // Select only the fields set in the test case. - List selectedFields = Arrays.asList("HotelId", "LastRenovationDate", "Location", "Rooms/BaseRate"); - getAndValidateDocumentAsync(asyncClient, hotelId, SearchDocument.class, selectedFields, expectedDoc, - (expected, actual) -> assertMapEquals(expected, actual, true, "boundingBox", "properties")); - } - - @Test - public void canGetDocumentWithBase64EncodedKeySync() { - SearchClient client = getClient(HOTEL_INDEX_NAME); - - String complexKey = Base64.getEncoder().encodeToString(new byte[] { 1, 2, 3, 4, 5 }); - - SearchDocument expectedDoc = new SearchDocument(); - expectedDoc.put("HotelId", complexKey); - - client.indexDocuments(new IndexDocumentsBatch<>().addUploadActions(Collections.singletonList(expectedDoc))); - assertEquals( - client - .getDocumentWithResponse(complexKey, SearchDocument.class, new ArrayList<>(expectedDoc.keySet()), - Context.NONE) - .getValue(), - expectedDoc); - } - - @Test - public void canGetDocumentWithBase64EncodedKeyAsync() { - SearchAsyncClient asyncClient = getAsyncClient(HOTEL_INDEX_NAME); - - String complexKey = Base64.getEncoder().encodeToString(new byte[] { 1, 2, 3, 4, 5 }); - - SearchDocument expectedDoc = new SearchDocument(); - expectedDoc.put("HotelId", complexKey); - - asyncClient.indexDocuments(new IndexDocumentsBatch<>().addUploadActions(Collections.singletonList(expectedDoc))) - .block(); - - getAndValidateDocumentAsync(asyncClient, complexKey, SearchDocument.class, - new ArrayList<>(expectedDoc.keySet()), expectedDoc, Assertions::assertEquals); - } - - @Test - public void roundTrippingDateTimeOffsetNormalizesToUtcSync() { - SearchClient client = getClient(HOTEL_INDEX_NAME); - - String hotelId = getRandomDocumentKey(); - SearchDocument indexedDoc = new SearchDocument(); - indexedDoc.put("HotelId", hotelId); - indexedDoc.put("LastRenovationDate", OffsetDateTime.parse("2010-06-27T00:00:00-08:00")); - - SearchDocument expectedDoc = new SearchDocument(); - expectedDoc.put("HotelId", hotelId); - - expectedDoc.put("LastRenovationDate", OffsetDateTime.parse("2010-06-27T08:00Z")); - - client.indexDocuments(new IndexDocumentsBatch<>().addUploadActions(Collections.singletonList(indexedDoc))); - SearchDocument actualDoc = client - .getDocumentWithResponse(hotelId, SearchDocument.class, new ArrayList<>(expectedDoc.keySet()), Context.NONE) - .getValue(); - assertMapEquals(expectedDoc, actualDoc, false); - } - - @Test - public void roundTrippingDateTimeOffsetNormalizesToUtcAsync() { - SearchAsyncClient asyncClient = getAsyncClient(HOTEL_INDEX_NAME); - - String hotelId = getRandomDocumentKey(); - SearchDocument indexedDoc = new SearchDocument(); - indexedDoc.put("HotelId", hotelId); - indexedDoc.put("LastRenovationDate", OffsetDateTime.parse("2010-06-27T00:00:00-08:00")); - - SearchDocument expectedDoc = new SearchDocument(); - expectedDoc.put("HotelId", hotelId); - - expectedDoc.put("LastRenovationDate", OffsetDateTime.parse("2010-06-27T08:00Z")); - - asyncClient.indexDocuments(new IndexDocumentsBatch<>().addUploadActions(Collections.singletonList(indexedDoc))) - .block(); - - getAndValidateDocumentAsync(asyncClient, hotelId, SearchDocument.class, new ArrayList<>(expectedDoc.keySet()), - expectedDoc, (expected, actual) -> assertMapEquals(expected, actual, false)); - } - - @Test - public void emptyDynamicObjectsOmittedFromCollectionOnGetWhenSubFieldsSelectedSync() { - SearchClient client = getClient(HOTEL_INDEX_NAME); - - String hotelId = getRandomDocumentKey(); - SearchDocument originalDoc = new SearchDocument(); - originalDoc.put("HotelId", hotelId); - - SearchDocument originalRoom = new SearchDocument(); - originalRoom.put("BaseRate", null); - originalRoom.put("BedOptions", null); - originalRoom.put("SleepsCount", null); - originalRoom.put("SmokingAllowed", null); - originalRoom.put("Tags", Collections.emptyList()); - originalDoc.put("Rooms", Arrays.asList(new SearchDocument(), originalRoom)); - - SearchDocument expectedDoc = new SearchDocument(); - expectedDoc.put("HotelId", hotelId); - - SearchDocument expectedRoom = new SearchDocument(); - expectedRoom.put("BaseRate", null); - expectedRoom.put("BedOptions", null); - expectedRoom.put("SleepsCount", null); - expectedRoom.put("SmokingAllowed", null); - expectedRoom.put("Tags", Collections.emptyList()); - expectedDoc.put("Rooms", Collections.singletonList(expectedRoom)); - - uploadDocument(client, originalDoc); - List selectedFields = Arrays.asList("HotelId", "Rooms/BaseRate", "Rooms/BedOptions", - "Rooms/SleepsCount", "Rooms/SmokingAllowed", "Rooms/Tags"); - - Response response - = client.getDocumentWithResponse(hotelId, SearchDocument.class, selectedFields, Context.NONE); - assertObjectEquals(expectedDoc, response.getValue(), true); - } - - @Test - public void emptyDynamicObjectsOmittedFromCollectionOnGetWhenSubFieldsSelectedAsync() { - SearchAsyncClient asyncClient = getAsyncClient(HOTEL_INDEX_NAME); - - String hotelId = getRandomDocumentKey(); - SearchDocument originalDoc = new SearchDocument(); - originalDoc.put("HotelId", hotelId); - - SearchDocument originalRoom = new SearchDocument(); - originalRoom.put("BaseRate", null); - originalRoom.put("BedOptions", null); - originalRoom.put("SleepsCount", null); - originalRoom.put("SmokingAllowed", null); - originalRoom.put("Tags", Collections.emptyList()); - originalDoc.put("Rooms", Arrays.asList(new SearchDocument(), originalRoom)); - - SearchDocument expectedDoc = new SearchDocument(); - expectedDoc.put("HotelId", hotelId); - - SearchDocument expectedRoom = new SearchDocument(); - expectedRoom.put("BaseRate", null); - expectedRoom.put("BedOptions", null); - expectedRoom.put("SleepsCount", null); - expectedRoom.put("SmokingAllowed", null); - expectedRoom.put("Tags", Collections.emptyList()); - expectedDoc.put("Rooms", Collections.singletonList(expectedRoom)); - - uploadDocument(asyncClient, originalDoc); - List selectedFields = Arrays.asList("HotelId", "Rooms/BaseRate", "Rooms/BedOptions", - "Rooms/SleepsCount", "Rooms/SmokingAllowed", "Rooms/Tags"); - - getAndValidateDocumentAsync(asyncClient, hotelId, SearchDocument.class, selectedFields, expectedDoc, - (expected, actual) -> assertObjectEquals(expected, actual, true)); - } - - @Test - public void dynamicallyTypedPrimitiveCollectionsDoNotAllRoundTripCorrectlySync() { - SearchClient client = getClient(TYPE_INDEX_NAME); - - String docKey = getRandomDocumentKey(); - OffsetDateTime dateTime = OffsetDateTime.parse("2019-08-13T14:30:00Z"); - GeoPoint geoPoint = new GeoPoint(100.0, 1.0); - - SearchDocument indexedDoc = new SearchDocument(); - indexedDoc.put("Key", docKey); - indexedDoc.put("Dates", new OffsetDateTime[] { dateTime }); - indexedDoc.put("Doubles", new Double[] { 0.0, 5.8, POSITIVE_INFINITY, NEGATIVE_INFINITY, NaN }); - indexedDoc.put("Bools", new Boolean[] { true, false }); - indexedDoc.put("Longs", new Long[] { 9999999999999999L, 832372345832523L }); - indexedDoc.put("Strings", new String[] { "hello", "bye" }); - indexedDoc.put("Ints", new int[] { 1, 2, 3, 4, -13, 5, 0 }); - indexedDoc.put("Points", new GeoPoint[] { geoPoint }); - - // This is the expected document when querying the document later - SearchDocument expectedDoc = new SearchDocument(); - expectedDoc.put("Key", docKey); - expectedDoc.put("Doubles", Arrays.asList(0.0, 5.8, "INF", "-INF", "NaN")); - expectedDoc.put("Bools", Arrays.asList(true, false)); - expectedDoc.put("Longs", Arrays.asList(9999999999999999L, 832372345832523L)); - expectedDoc.put("Strings", Arrays.asList("hello", "bye")); - expectedDoc.put("Ints", Arrays.asList(1, 2, 3, 4, -13, 5, 0)); - //expectedDoc.put("Points", Collections.singletonList(geoPoint)); - expectedDoc.put("Dates", Collections.singletonList(dateTime)); - - uploadDocument(client, indexedDoc); - - SearchDocument actualDoc = client.getDocument(docKey, SearchDocument.class); - - assertMapEquals(expectedDoc, actualDoc, true, "properties"); - } - - @Test - public void dynamicallyTypedPrimitiveCollectionsDoNotAllRoundTripCorrectlyAsync() { - SearchAsyncClient asyncClient = getAsyncClient(TYPE_INDEX_NAME); - - String docKey = getRandomDocumentKey(); - OffsetDateTime dateTime = OffsetDateTime.parse("2019-08-13T14:30:00Z"); - GeoPoint geoPoint = new GeoPoint(100.0, 1.0); - - SearchDocument indexedDoc = new SearchDocument(); - indexedDoc.put("Key", docKey); - indexedDoc.put("Dates", new OffsetDateTime[] { dateTime }); - indexedDoc.put("Doubles", new Double[] { 0.0, 5.8, POSITIVE_INFINITY, NEGATIVE_INFINITY, NaN }); - indexedDoc.put("Bools", new Boolean[] { true, false }); - indexedDoc.put("Longs", new Long[] { 9999999999999999L, 832372345832523L }); - indexedDoc.put("Strings", new String[] { "hello", "bye" }); - indexedDoc.put("Ints", new int[] { 1, 2, 3, 4, -13, 5, 0 }); - indexedDoc.put("Points", new GeoPoint[] { geoPoint }); - - // This is the expected document when querying the document later - SearchDocument expectedDoc = new SearchDocument(); - expectedDoc.put("Key", docKey); - expectedDoc.put("Doubles", Arrays.asList(0.0, 5.8, "INF", "-INF", "NaN")); - expectedDoc.put("Bools", Arrays.asList(true, false)); - expectedDoc.put("Longs", Arrays.asList(9999999999999999L, 832372345832523L)); - expectedDoc.put("Strings", Arrays.asList("hello", "bye")); - expectedDoc.put("Ints", Arrays.asList(1, 2, 3, 4, -13, 5, 0)); - //expectedDoc.put("Points", Collections.singletonList(geoPoint)); - expectedDoc.put("Dates", Collections.singletonList(dateTime)); - - uploadDocument(asyncClient, indexedDoc); - - getAndValidateDocumentAsync(asyncClient, docKey, SearchDocument.class, expectedDoc, - (expected, actual) -> assertMapEquals(expected, actual, true, "properties")); - } - - @SuppressWarnings({ "deprecation", "UseOfObsoleteDateTimeApi" }) - static Hotel prepareExpectedHotel(String key) { - Date expectDate = Date.from(Instant.ofEpochMilli(1277582400000L)); - return new Hotel().hotelId(key) - .hotelName("Fancy Stay") - .description( - "Best hotel in town if you like luxury hotels. They have an amazing infinity pool, a spa, and a really helpful concierge. The location is perfect -- right downtown, close to all the tourist attractions. We highly recommend this hotel.") - .descriptionFr( - "Meilleur hôtel en ville si vous aimez les hôtels de luxe. Ils ont une magnifique piscine à débordement, un spa et un concierge très utile. L'emplacement est parfait – en plein centre, à proximité de toutes les attractions touristiques. Nous recommandons fortement cet hôtel.") - .category("Luxury") - .tags(Arrays.asList("pool", "view", "wifi", "concierge")) - .parkingIncluded(false) - .smokingAllowed(false) - .lastRenovationDate(new Date(expectDate.getYear(), expectDate.getMonth(), expectDate.getDate(), - expectDate.getHours(), expectDate.getMinutes(), expectDate.getSeconds())) - .rating(5) - .location(new GeoPoint(-122.131577, 47.678581)) - .rooms(new ArrayList<>()); - } - - private static void getAndValidateDocumentAsync(SearchAsyncClient asyncClient, String key, Class type, - T expected, BiConsumer comparator) { - StepVerifier.create(asyncClient.getDocument(key, type)) - .assertNext(actual -> comparator.accept(expected, actual)) - .verifyComplete(); - } - - private static void getAndValidateDocumentAsync(SearchAsyncClient asyncClient, String key, Class type, - List selectedFields, T expected, BiConsumer comparator) { - StepVerifier.create(asyncClient.getDocumentWithResponse(key, type, selectedFields)) - .assertNext(actual -> comparator.accept(expected, actual.getValue())) - .verifyComplete(); - } - - static Hotel prepareEmptyHotel(String key) { - return new Hotel().hotelId(key) - .tags(new ArrayList<>()) - .rooms(Collections.singletonList(new HotelRoom().tags(new String[0]))); - } - - static Hotel preparePascalCaseFieldsHotel(String key) { - return new Hotel().hotelId(key).hotelName("Lord of the Rings").description("J.R.R").descriptionFr("Tolkien"); - } - - @SuppressWarnings({ "deprecation", "UseOfObsoleteDateTimeApi" }) - static Hotel prepareSelectedFieldsHotel(String key) { - // Since Date doesn't have time zone information to make this test durable against time zones create the Date - // from an OffsetDateTime. - OffsetDateTime dateTime = OffsetDateTime.parse("2010-06-26T17:00:00.000+00:00") - .atZoneSameInstant(ZoneId.systemDefault()) - .toOffsetDateTime(); - - return new Hotel().hotelId(key) - .hotelName("Countryside Hotel") - .description( - "Save up to 50% off traditional hotels. Free WiFi, great location near downtown, full kitchen, washer & dryer, 24/7 support, bowling alley, fitness center and more.") - .descriptionFr( - "Économisez jusqu'à 50% sur les hôtels traditionnels. WiFi gratuit, très bien situé près du centre-ville, cuisine complète, laveuse & sécheuse, support 24/7, bowling, centre de fitness et plus encore.") - .category("Budget") - .tags(Arrays.asList("24-hour front desk service", "coffee in lobby", "restaurant")) - .parkingIncluded(false) - .smokingAllowed(true) - .lastRenovationDate(new Date(dateTime.getYear() - 1900, dateTime.getMonth().ordinal(), - dateTime.getDayOfMonth(), dateTime.getHour(), dateTime.getMinute())) - .rating(3) - .location(new GeoPoint(-78.940483, 35.904160)) - .address(new HotelAddress().streetAddress("6910 Fayetteville Rd") - .city("Durham") - .stateProvince("NC") - .country("USA") - .postalCode("27713")) - .rooms(Arrays.asList( - new HotelRoom().description("Suite, 1 King Bed (Amenities)") - .descriptionFr("Suite, 1 très grand lit (Services)") - .type("Suite") - .baseRate(2.44) - .bedOptions("1 King Bed") - .sleepsCount(2) - .smokingAllowed(true) - .tags(new String[] { "coffee maker" }), - new HotelRoom().description("Budget Room, 1 Queen Bed (Amenities)") - .descriptionFr("Chambre Économique, 1 grand lit (Services)") - .type("Budget Room") - .baseRate(7.69) - .bedOptions("1 Queen Bed") - .sleepsCount(2) - .smokingAllowed(false) - .tags(new String[] { "coffee maker" }))); - } - - static ModelWithPrimitiveCollections preparePrimitivesModel(String key) { - return new ModelWithPrimitiveCollections().key(key) - .bools(new Boolean[] { true, false }) - .dates(new OffsetDateTime[] { - OffsetDateTime.parse("2019-04-14T14:24:00Z"), - OffsetDateTime.parse("1999-12-31T23:59:59Z") }) - .doubles(new Double[] { NEGATIVE_INFINITY, 0.0, 2.78, NaN, 3.25, POSITIVE_INFINITY }) - .ints(new int[] { 1, 2, 3, 4, -13, 5, 0 }) - .longs(new Long[] { -9_999_999_999_999_999L, 832_372_345_832_523L }) - .points(new GeoPoint[] { new GeoPoint(-67.0, 49.0), new GeoPoint(21.0, 47.0) }) - .strings(new String[] { "hello", "2019-04-14T14:56:00-07:00" }); - } - - static void setupIndexWithDataTypes() { - SearchIndex index = new SearchIndex(TYPE_INDEX_NAME).setFields(Arrays.asList( - new SearchField("Key", SearchFieldDataType.STRING).setKey(true).setHidden(false), - new SearchField("Bools", SearchFieldDataType.collection(SearchFieldDataType.BOOLEAN)).setHidden(false), - new SearchField("Dates", SearchFieldDataType.collection(SearchFieldDataType.DATE_TIME_OFFSET)) - .setHidden(false), - new SearchField("Doubles", SearchFieldDataType.collection(SearchFieldDataType.DOUBLE)).setHidden(false), - new SearchField("Points", SearchFieldDataType.collection(SearchFieldDataType.GEOGRAPHY_POINT)) - .setHidden(false), - new SearchField("Ints", SearchFieldDataType.collection(SearchFieldDataType.INT32)).setHidden(false), - new SearchField("Longs", SearchFieldDataType.collection(SearchFieldDataType.INT64)).setHidden(false), - new SearchField("Strings", SearchFieldDataType.collection(SearchFieldDataType.STRING)).setHidden(false))); - - createSharedSearchIndexClient().createOrUpdateIndex(index); - } -} diff --git a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/SearchClientBuilderTests.java b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/SearchClientBuilderTests.java deleted file mode 100644 index 627a22332731..000000000000 --- a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/SearchClientBuilderTests.java +++ /dev/null @@ -1,215 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.search.documents; - -import com.azure.core.credential.AzureKeyCredential; -import com.azure.core.exception.HttpResponseException; -import com.azure.core.http.policy.ExponentialBackoffOptions; -import com.azure.core.http.policy.FixedDelay; -import com.azure.core.http.policy.FixedDelayOptions; -import com.azure.core.http.policy.HttpLogOptions; -import com.azure.core.http.policy.RetryOptions; -import com.azure.core.http.policy.RetryPolicy; -import com.azure.core.test.http.MockHttpResponse; -import com.azure.core.test.utils.MockTokenCredential; -import com.azure.core.util.ClientOptions; -import com.azure.core.util.Header; -import com.azure.search.documents.indexes.SearchIndexClientBuilderTests; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.parallel.Execution; -import org.junit.jupiter.api.parallel.ExecutionMode; -import reactor.core.publisher.Mono; -import reactor.test.StepVerifier; - -import java.net.MalformedURLException; -import java.security.SecureRandom; -import java.time.Duration; -import java.util.Collections; - -import static com.azure.search.documents.indexes.SearchIndexClientBuilderTests.request; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.junit.jupiter.api.Assertions.assertTrue; - -@Execution(ExecutionMode.CONCURRENT) -public class SearchClientBuilderTests { - private static final MockTokenCredential SEARCH_CREDENTIAL = new MockTokenCredential(); - private static final String SEARCH_ENDPOINT = "https://test.search.windows.net"; - private static final String INDEX_NAME = "myindex"; - private static final SearchServiceVersion API_VERSION = SearchServiceVersion.V2020_06_30; - - @Test - public void buildSyncClientTest() { - SearchClient client = new SearchClientBuilder().endpoint(SEARCH_ENDPOINT) - .credential(SEARCH_CREDENTIAL) - .indexName(INDEX_NAME) - .serviceVersion(API_VERSION) - .httpClient(request -> Mono.just(new MockHttpResponse(request, 200))) - .buildClient(); - - assertNotNull(client); - assertEquals(SearchClient.class.getSimpleName(), client.getClass().getSimpleName()); - } - - @Test - public void buildSyncClientUsingDefaultApiVersionTest() { - SearchClient client = new SearchClientBuilder().endpoint(SEARCH_ENDPOINT) - .credential(SEARCH_CREDENTIAL) - .indexName(INDEX_NAME) - .httpClient(request -> Mono.just(new MockHttpResponse(request, 200))) - .buildClient(); - - assertNotNull(client); - assertEquals(SearchClient.class.getSimpleName(), client.getClass().getSimpleName()); - } - - @Test - public void buildAsyncClientTest() { - SearchAsyncClient client = new SearchClientBuilder().endpoint(SEARCH_ENDPOINT) - .credential(SEARCH_CREDENTIAL) - .indexName(INDEX_NAME) - .serviceVersion(API_VERSION) - .httpClient(request -> Mono.just(new MockHttpResponse(request, 200))) - .buildAsyncClient(); - - assertNotNull(client); - assertEquals(SearchAsyncClient.class.getSimpleName(), client.getClass().getSimpleName()); - } - - @Test - public void buildAsyncClientUsingDefaultApiVersionTest() { - SearchAsyncClient client = new SearchClientBuilder().endpoint(SEARCH_ENDPOINT) - .credential(SEARCH_CREDENTIAL) - .indexName(INDEX_NAME) - .httpClient(request -> Mono.just(new MockHttpResponse(request, 200))) - .buildAsyncClient(); - - assertNotNull(client); - assertEquals(SearchAsyncClient.class.getSimpleName(), client.getClass().getSimpleName()); - } - - @Test - public void whenBuildClientAndVerifyPropertiesThenSuccess() { - SearchClient client = new SearchClientBuilder().endpoint(SEARCH_ENDPOINT) - .credential(SEARCH_CREDENTIAL) - .indexName(INDEX_NAME) - .httpClient(request -> Mono.just(new MockHttpResponse(request, 200))) - .buildClient(); - - assertEquals(SEARCH_ENDPOINT, client.getEndpoint()); - assertEquals(INDEX_NAME, client.getIndexName()); - - SearchAsyncClient asyncClient = new SearchClientBuilder().endpoint(SEARCH_ENDPOINT) - .credential(SEARCH_CREDENTIAL) - .indexName(INDEX_NAME) - .httpClient(request -> Mono.just(new MockHttpResponse(request, 200))) - .buildAsyncClient(); - - assertEquals(SEARCH_ENDPOINT, asyncClient.getEndpoint()); - assertEquals(INDEX_NAME, asyncClient.getIndexName()); - } - - @Test - public void emptyEndpointThrowsIllegalArgumentException() { - assertThrows(IllegalArgumentException.class, () -> new SearchClientBuilder().endpoint("")); - } - - @Test - public void nullIndexNameThrowsIllegalArgumentException() { - assertThrows(IllegalArgumentException.class, () -> new SearchClientBuilder().indexName(null)); - } - - @Test - public void emptyIndexNameThrowsIllegalArgumentException() { - assertThrows(IllegalArgumentException.class, () -> new SearchClientBuilder().indexName("")); - } - - @Test - public void credentialWithEmptyApiKeyThrowsIllegalArgumentException() { - assertThrows(IllegalArgumentException.class, - () -> new SearchClientBuilder().credential(new AzureKeyCredential(""))); - } - - @Test - public void indexClientFreshDateOnRetry() throws MalformedURLException { - byte[] randomData = new byte[256]; - new SecureRandom().nextBytes(randomData); - SearchAsyncClient searchAsyncClient = new SearchClientBuilder().endpoint(SEARCH_ENDPOINT) - .credential(SEARCH_CREDENTIAL) - .indexName("test_builder") - .retryOptions(new RetryOptions(new FixedDelayOptions(3, Duration.ofSeconds(1)))) - .httpClient(new SearchIndexClientBuilderTests.FreshDateTestClient()) - .buildAsyncClient(); - - StepVerifier.create(searchAsyncClient.getHttpPipeline().send(request(searchAsyncClient.getEndpoint()))) - .assertNext(response -> assertEquals(200, response.getStatusCode())) - .verifyComplete(); - } - - @SuppressWarnings("deprecation") - @Test - public void clientOptionsIsPreferredOverLogOptions() { - SearchClient searchClient = new SearchClientBuilder().endpoint(SEARCH_ENDPOINT) - .credential(SEARCH_CREDENTIAL) - .indexName("test_builder") - .httpLogOptions(new HttpLogOptions().setApplicationId("anOldApplication")) - .clientOptions(new ClientOptions().setApplicationId("aNewApplication")) - .retryPolicy(new RetryPolicy(new FixedDelay(3, Duration.ofMillis(1)))) - .httpClient(httpRequest -> { - assertTrue(httpRequest.getHeaders().getValue("User-Agent").contains("aNewApplication")); - return Mono.just(new MockHttpResponse(httpRequest, 400)); - }) - .buildClient(); - - assertThrows(HttpResponseException.class, searchClient::getDocumentCount); - } - - @SuppressWarnings("deprecation") - @Test - public void applicationIdFallsBackToLogOptions() { - SearchClient searchClient = new SearchClientBuilder().endpoint(SEARCH_ENDPOINT) - .credential(SEARCH_CREDENTIAL) - .indexName("test_builder") - .httpLogOptions(new HttpLogOptions().setApplicationId("anOldApplication")) - .retryPolicy(new RetryPolicy(new FixedDelay(3, Duration.ofMillis(1)))) - .httpClient(httpRequest -> { - assertTrue(httpRequest.getHeaders().getValue("User-Agent").contains("anOldApplication")); - return Mono.just(new MockHttpResponse(httpRequest, 400)); - }) - .buildClient(); - - assertThrows(HttpResponseException.class, searchClient::getDocumentCount); - } - - @Test - public void clientOptionHeadersAreAddedLast() { - SearchClient searchClient = new SearchClientBuilder().endpoint(SEARCH_ENDPOINT) - .credential(SEARCH_CREDENTIAL) - .indexName("test_builder") - .clientOptions( - new ClientOptions().setHeaders(Collections.singletonList(new Header("User-Agent", "custom")))) - .retryPolicy(new RetryPolicy(new FixedDelay(3, Duration.ofMillis(1)))) - .httpClient(httpRequest -> { - assertEquals("custom", httpRequest.getHeaders().getValue("User-Agent")); - return Mono.just(new MockHttpResponse(httpRequest, 400)); - }) - .buildClient(); - - assertThrows(HttpResponseException.class, searchClient::getDocumentCount); - } - - @Test - public void bothRetryOptionsAndRetryPolicySet() { - assertThrows(IllegalStateException.class, - () -> new SearchClientBuilder().endpoint(SEARCH_ENDPOINT) - .credential(SEARCH_CREDENTIAL) - .indexName(INDEX_NAME) - .serviceVersion(API_VERSION) - .retryOptions(new RetryOptions(new ExponentialBackoffOptions())) - .retryPolicy(new RetryPolicy()) - .httpClient(request -> Mono.just(new MockHttpResponse(request, 200))) - .buildClient()); - } -} diff --git a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/SearchDocumentConverterTests.java b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/SearchDocumentConverterTests.java deleted file mode 100644 index 80804751eefe..000000000000 --- a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/SearchDocumentConverterTests.java +++ /dev/null @@ -1,286 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.search.documents; - -import com.azure.core.models.GeoPoint; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.parallel.Execution; -import org.junit.jupiter.api.parallel.ExecutionMode; - -import java.nio.charset.StandardCharsets; -import java.time.OffsetDateTime; -import java.time.ZoneOffset; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.stream.Collectors; - -import static com.azure.search.documents.TestHelpers.assertMapEquals; -import static com.azure.search.documents.TestHelpers.assertObjectEquals; -import static com.azure.search.documents.TestHelpers.convertStreamToMap; -import static org.junit.jupiter.api.Assertions.assertEquals; - -/** - * Functional tests that ensure expected behavior of deserializing a document. - */ -@Execution(ExecutionMode.CONCURRENT) -public class SearchDocumentConverterTests { - - private static final String TEST_DATE_STRING = "2016-10-10T17:41:05.123-07:00"; - private static final OffsetDateTime TEST_DATE - = OffsetDateTime.of(2016, 10, 10, 17, 41, 5, 123 * 1_000_000, ZoneOffset.of("-07:00")); - - private static SearchDocument deserialize(String json) { - // Deserialization of the search result is done with azure-core (using Jackson as well) - // the result object is a map of key:value, get deserialized directly into the Document object - // Document is simply a Hash Map. - // in this case we simulate creation of the object created by azure-core - SearchDocument doc = new SearchDocument(convertStreamToMap(json.getBytes(StandardCharsets.UTF_8))); - cleanupODataAnnotation(doc); - return doc; - } - - private static void cleanupODataAnnotation(SearchDocument searchDocument) { - // Skip OData @search annotations. These are deserialized separately. - List keysToRemove - = searchDocument.keySet().stream().filter(key -> key.startsWith("@search")).collect(Collectors.toList()); - keysToRemove.forEach(searchDocument::remove); - } - - @Test - public void annotationsAreExcludedFromDocument() { - String json - = "{ \"@search.score\": 3.25, \"field1\": \"value1\", \"field2\": 123, \"@search.someOtherAnnotation\": { \"a\": \"b\" }, \"field3\": 2.78 }"; - SearchDocument expectedDoc = new SearchDocument(); - expectedDoc.put("field1", "value1"); - expectedDoc.put("field2", 123); - expectedDoc.put("field3", 2.78); - - SearchDocument actualDoc = deserialize(json); - assertEquals(expectedDoc, actualDoc); - } - - @Test - public void canReadNullValues() { - String json - = "{\"field1\": null,\"field2\": [ \"hello\", null ], \"field3\": [ null, 123, null ], \"field4\": [ null, { \"name\": \"Bob\" } ]}"; - SearchDocument expectedDoc = new SearchDocument(); - expectedDoc.put("field1", null); - expectedDoc.put("field2", Arrays.asList("hello", null)); - expectedDoc.put("field3", Arrays.asList(null, 123, null)); - expectedDoc.put("field4", Arrays.asList(null, new SearchDocument(Collections.singletonMap("name", "Bob")))); - - SearchDocument actualDoc = deserialize(json); - assertEquals(expectedDoc, actualDoc); - } - - @Test - public void canReadPrimitiveTypes() { - Map values = new HashMap<>(); - values.put("123", 123); - values.put("9999999999999", 9_999_999_999_999L); - values.put("3.25", 3.25); - values.put("\"hello\"", "hello"); - values.put("true", true); - values.put("false", false); - - for (Map.Entry entry : values.entrySet()) { - String jsonValue = entry.getKey(); - Object expectedObject = entry.getValue(); - String json = "{\"field\" :".concat(jsonValue).concat("}"); - SearchDocument expectedDoc = new SearchDocument(Collections.singletonMap("field", expectedObject)); - - SearchDocument actualDoc = deserialize(json); - assertEquals(expectedDoc, actualDoc); - } - } - - @Test - public void canReadArraysOfPrimitiveTypes() { - Map values = new HashMap<>(); - values.put("[\"hello\", \"goodbye\"]", Arrays.asList("hello", "goodbye")); - values.put("[123, 456]", Arrays.asList(123, 456)); - values.put("[9999999999999, -12]", Arrays.asList(9_999_999_999_999L, -12)); - values.put("[3.25, 2.78]", Arrays.asList(3.25, 2.78)); - values.put("[true, false]", Arrays.asList(true, false)); - - for (Map.Entry entry : values.entrySet()) { - String jsonArray = entry.getKey(); - Object expectedArray = entry.getValue(); - String json = "{\"field\" :".concat(jsonArray).concat("}"); - SearchDocument expectedDoc = new SearchDocument(Collections.singletonMap("field", expectedArray)); - - SearchDocument actualDoc = deserialize(json); - assertEquals(expectedDoc, actualDoc); - } - } - - @Test - public void canReadGeoPoint() { - String json = "{ \"field\": { \"type\": \"Point\", \"coordinates\": [-122.131577, 47.678581], " - + "\"crs\":{\"type\":\"name\", \"properties\":{\"name\":\"EPSG:4326\"}}}}"; - SearchDocument expectedDoc - = new SearchDocument(Collections.singletonMap("field", new GeoPoint(-122.131577, 47.678581))); - - SearchDocument actualDoc = deserialize(json); - expectedDoc.forEach((key, value) -> assertObjectEquals(value, actualDoc.get(key), false, "properties")); - } - - @Test - public void canReadGeoPointCollection() { - String json = "{\"field\":[{\"type\":\"Point\", \"coordinates\":[-122.131577, 47.678581], " - + "\"crs\":{\"type\":\"name\", \"properties\":{\"name\":\"EPSG:4326\"}}}, " - + "{\"type\":\"Point\", \"coordinates\":[-121.0, 49.0], " - + "\"crs\":{\"type\":\"name\", \"properties\":{\"name\":\"EPSG:4326\"}}}]}"; - SearchDocument expectedDoc = new SearchDocument(Collections.singletonMap("field", - Arrays.asList(new GeoPoint(-122.131577, 47.678581), new GeoPoint(-121.0, 49.0)))); - - SearchDocument actualDoc = deserialize(json); - assertMapEquals(expectedDoc, actualDoc, true, "properties"); - } - - @Test - public void canReadComplexObject() { - String json = "{\"name\" : \"Boots\", \"details\": {\"sku\" : 123, \"seasons\" : [\"fall\", \"winter\"]}}"; - SearchDocument innerDoc = new SearchDocument(); - innerDoc.put("sku", 123); - innerDoc.put("seasons", Arrays.asList("fall", "winter")); - - SearchDocument expectedDoc = new SearchDocument(); - expectedDoc.put("name", "Boots"); - expectedDoc.put("details", innerDoc); - - SearchDocument actualDoc = deserialize(json); - assertEquals(expectedDoc, actualDoc); - } - - @Test - public void canReadComplexCollection() { - String json - = "{\"stores\" : [{\"name\" : \"North\", \"address\" : {\"city\" : \"Vancouver\", \"country\": \"Canada\"}, \"location\": {\"type\" : \"Point\", \"coordinates\": [-121, 49]}},{\"name\" : \"South\", \"address\" : {\"city\": \"Seattle\", \"country\" : \"USA\"}, \"location\" : {\"type\" : \"Point\", \"coordinates\": [-122.5, 47.6]}}]}"; - - SearchDocument storeAddress1 = new SearchDocument(); - storeAddress1.put("city", "Vancouver"); - storeAddress1.put("country", "Canada"); - - SearchDocument storeLocation1 = new SearchDocument(); - storeLocation1.put("type", "Point"); - storeLocation1.put("coordinates", Arrays.asList(-121, 49)); - - SearchDocument store1 = new SearchDocument(); - store1.put("name", "North"); - store1.put("address", storeAddress1); - store1.put("location", storeLocation1); - - SearchDocument storeAddress2 = new SearchDocument(); - storeAddress2.put("city", "Seattle"); - storeAddress2.put("country", "USA"); - - SearchDocument storeLocation2 = new SearchDocument(); - storeLocation2.put("type", "Point"); - storeLocation2.put("coordinates", Arrays.asList(-122.5, 47.6)); - - SearchDocument store2 = new SearchDocument(); - store2.put("name", "South"); - store2.put("address", storeAddress2); - store2.put("location", storeLocation2); - - SearchDocument expectedDoc - = new SearchDocument(Collections.singletonMap("stores", Arrays.asList(store1, store2))); - - SearchDocument actualDoc = deserialize(json); - assertEquals(expectedDoc, actualDoc); - } - - @Test - public void canReadArraysOfMixedTypes() { - // Azure AI Search won't return payloads like this; This test is only for pinning purposes. - String json - = "{\"field\": [\"hello\", 123, 3.25, { \"type\": \"Point\", \"coordinates\": [-122.131577, 47.678581], " - + "\"crs\":{\"type\":\"name\", \"properties\":{\"name\": \"EPSG:4326\"}}}, " - + "{ \"name\": \"Arthur\", \"quest\": null }] }"; - - GeoPoint point = new GeoPoint(-122.131577, 47.678581); - SearchDocument innerDoc = new SearchDocument(); - innerDoc.put("name", "Arthur"); - innerDoc.put("quest", null); - List value = Arrays.asList("hello", 123, 3.25, point, innerDoc); - - SearchDocument expectedDoc = new SearchDocument(); - expectedDoc.put("field", value); - - SearchDocument actualDoc = deserialize(json); - assertMapEquals(expectedDoc, actualDoc, true, "properties"); - } - - @Test - public void dateTimeStringsAreReadAsDateTime() { - String json = "{\"field1\":\"".concat(TEST_DATE_STRING) - .concat("\",\"field2\" : [\"") - .concat(TEST_DATE_STRING) - .concat("\", \"") - .concat(TEST_DATE_STRING) - .concat("\"]}"); - SearchDocument expectedDoc = new SearchDocument(); - expectedDoc.put("field1", TEST_DATE); - expectedDoc.put("field2", Arrays.asList(TEST_DATE, TEST_DATE)); - - SearchDocument actualDoc = deserialize(json); - assertMapEquals(expectedDoc, actualDoc, false); - } - - @Test - public void emptyArraysReadAsObjectArrays() { - String json = "{ \"field\": [] }"; - - // With no elements, we can't tell what type of collection it is, so we default to object. - SearchDocument expectedDoc = new SearchDocument(); - expectedDoc.put("field", new ArrayList<>()); - - SearchDocument actualDoc = deserialize(json); - assertEquals(expectedDoc, actualDoc); - } - - @Test - public void arraysWithOnlyNullsReadAsStringArrays() { - String json = "{ \"field\": [null, null] }"; - - // With only null elements, we can't tell what type of collection it is. For backward compatibility, we assume type string. - // This shouldn't happen in practice anyway since Azure AI Search generally doesn't allow nulls in collections. - SearchDocument expectedDoc = new SearchDocument(); - List emptyStringList = Arrays.asList(null, null); - expectedDoc.put("field", emptyStringList); - - SearchDocument actualDoc = deserialize(json); - assertEquals(expectedDoc, actualDoc); - } - - @Test - public void specialDoublesAreReadAsStrings() { - String json - = "{\"field1\" : \"NaN\", \"field2\": \"INF\", \"field3\": \"-INF\", \"field4\": [\"NaN\", \"INF\", \"-INF\"], \"field5\": {\"value\":\"-INF\"}}"; - SearchDocument expectedDoc = new SearchDocument(); - expectedDoc.put("field1", "NaN"); - expectedDoc.put("field2", "INF"); - expectedDoc.put("field3", "-INF"); - expectedDoc.put("field4", Arrays.asList("NaN", "INF", "-INF")); - expectedDoc.put("field5", new SearchDocument(Collections.singletonMap("value", "-INF"))); - - SearchDocument actualDoc = deserialize(json); - assertEquals(expectedDoc, actualDoc); - } - - @Test - public void dateTimeStringsInArraysAreReadAsDateTime() { - String json = "{ \"field\": [ \"hello\", \"".concat(TEST_DATE_STRING).concat("\", \"123\" ] }}"); - SearchDocument expectedDoc - = new SearchDocument(Collections.singletonMap("field", Arrays.asList("hello", TEST_DATE, "123"))); - - SearchDocument actualDoc = deserialize(json); - assertMapEquals(expectedDoc, actualDoc, false); - } -} diff --git a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/SearchFilterTests.java b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/SearchFilterTests.java deleted file mode 100644 index afc4c4136e20..000000000000 --- a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/SearchFilterTests.java +++ /dev/null @@ -1,252 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.search.documents; - -import com.azure.core.http.HttpMethod; -import com.azure.core.models.GeoBoundingBox; -import com.azure.core.models.GeoLineString; -import com.azure.core.models.GeoLinearRing; -import com.azure.core.models.GeoPoint; -import com.azure.core.models.GeoPolygon; -import com.azure.core.models.GeoPosition; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.parallel.Execution; -import org.junit.jupiter.api.parallel.ExecutionMode; -import org.junit.jupiter.params.ParameterizedTest; -import org.junit.jupiter.params.provider.Arguments; -import org.junit.jupiter.params.provider.MethodSource; - -import java.time.OffsetDateTime; -import java.time.ZoneOffset; -import java.util.Arrays; -import java.util.Collections; -import java.util.Date; -import java.util.List; -import java.util.stream.Stream; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertThrows; - -/** - * Tests {@link SearchFilter}. - */ -@Execution(ExecutionMode.CONCURRENT) -public class SearchFilterTests { - @Test - public void noArguments() { - assertEquals("Foo eq 2", SearchFilter.create("Foo eq 2")); - } - - @Test - public void oneArgument() { - String actual = SearchFilter.create("Foo eq %d", 2); - assertEquals("Foo eq 2", actual); - } - - @ParameterizedTest - @MethodSource("manyArgumentsSupplier") - public void manyArguments(String expected, String formattableString, Object[] args) { - assertEquals(expected, SearchFilter.create(formattableString, args)); - } - - static Stream manyArgumentsSupplier() { - return Stream.of(Arguments.of("Foo eq 2 and Bar eq 3", "Foo eq %d and Bar eq %d", new Object[] { 2, 3 }), - Arguments.of("Foo eq 2 and Bar eq 3 and Baz eq 4", "Foo eq %d and Bar eq %d and Baz eq %d", - new Object[] { 2, 3, 4 }), - Arguments.of("Foo eq 2 and Bar eq 3 and Baz eq 4 and Qux eq 5", - "Foo eq %d and Bar eq %d and Baz eq %d and Qux eq %d", new Object[] { 2, 3, 4, 5 }), - Arguments.of("Foo eq 2 and Bar eq 3 and Baz eq 4 and Qux eq 5 and Quux eq 6", - "Foo eq %d and Bar eq %d and Baz eq %d and Qux eq %d and Quux eq %d", new Object[] { 2, 3, 4, 5, 6 })); - } - - @Test - public void nullArgument() { - assertEquals("Foo eq null", SearchFilter.create("Foo eq %s", new Object[] { null })); - } - - @Test - public void booleanArgument() { - assertEquals("Foo eq true", SearchFilter.create("Foo eq %b", true)); - assertEquals("Foo eq false", SearchFilter.create("Foo eq %b", false)); - assertEquals("Foo eq false", SearchFilter.create("Foo eq %b", (Boolean) null)); - } - - @ParameterizedTest - @MethodSource("numberArgumentSupplier") - public void numberArgument(String expected, String formattableString, Object arg) { - assertEquals(expected, SearchFilter.create(formattableString, arg)); - } - - static Stream numberArgumentSupplier() { - return Stream.of(Arguments.of("Foo eq 0", "Foo eq %d", (byte) 0), - Arguments.of("Foo eq -2", "Foo eq %d", (byte) -2), Arguments.of("Foo eq 2", "Foo eq %d", (byte) 2), - - Arguments.of("Foo eq 0", "Foo eq %d", Byte.valueOf("0")), - Arguments.of("Foo eq -2", "Foo eq %d", Byte.valueOf("-2")), - Arguments.of("Foo eq 2", "Foo eq %d", Byte.valueOf("2")), - - Arguments.of("Foo eq 0", "Foo eq %d", (short) 0), Arguments.of("Foo eq -2", "Foo eq %d", (short) -2), - Arguments.of("Foo eq 2", "Foo eq %d", (short) 2), - - Arguments.of("Foo eq 0", "Foo eq %d", Short.valueOf("0")), - Arguments.of("Foo eq -2", "Foo eq %d", Short.valueOf("-2")), - Arguments.of("Foo eq 2", "Foo eq %d", Short.valueOf("2")), - - Arguments.of("Foo eq 0", "Foo eq %d", 0), Arguments.of("Foo eq -2", "Foo eq %d", -2), - Arguments.of("Foo eq 2", "Foo eq %d", 2), - - Arguments.of("Foo eq 0", "Foo eq %d", Integer.valueOf("0")), - Arguments.of("Foo eq -2", "Foo eq %d", Integer.valueOf("-2")), - Arguments.of("Foo eq 2", "Foo eq %d", Integer.valueOf("2")), - - Arguments.of("Foo eq 0", "Foo eq %d", 0L), Arguments.of("Foo eq -2", "Foo eq %d", -2L), - Arguments.of("Foo eq 2", "Foo eq %d", 2L), - - Arguments.of("Foo eq 0", "Foo eq %d", Long.valueOf("0")), - Arguments.of("Foo eq -2", "Foo eq %d", Long.valueOf("-2")), - Arguments.of("Foo eq 2", "Foo eq %d", Long.valueOf("2")), - - Arguments.of("Foo eq 0", "Foo eq %.0f", 0F), Arguments.of("Foo eq -2", "Foo eq %.0f", -2F), - Arguments.of("Foo eq 2", "Foo eq %.0f", 2F), - - Arguments.of("Foo eq 0", "Foo eq %.0f", Float.valueOf("0")), - Arguments.of("Foo eq -2", "Foo eq %.0f", Float.valueOf("-2")), - Arguments.of("Foo eq 2", "Foo eq %.0f", Float.valueOf("2")), - - Arguments.of("Foo eq 0", "Foo eq %.0f", 0D), Arguments.of("Foo eq -2", "Foo eq %.0f", -2D), - Arguments.of("Foo eq 2", "Foo eq %.0f", 2D), - - Arguments.of("Foo eq 0", "Foo eq %.0f", Double.valueOf("0")), - Arguments.of("Foo eq -2", "Foo eq %.0f", Double.valueOf("-2")), - Arguments.of("Foo eq 2", "Foo eq %.0f", Double.valueOf("2"))); - } - - @Test - public void decimalArgument() { - assertEquals("Foo eq 2.5", SearchFilter.create("Foo eq %.1f", 2.5F)); - assertEquals("Foo eq 2.5", SearchFilter.create("Foo eq %.1f", 2.5D)); - } - - @Test - public void exponentArgument() { - assertEquals("Foo eq 2.5e+10", SearchFilter.create("Foo eq %.1e", 2.5e10F)); - assertEquals("Foo eq 2.5e+10", SearchFilter.create("Foo eq %.1e", 2.5e10D)); - } - - @ParameterizedTest - @MethodSource("limitArgumentSupplier") - public void limitArgument(String expected, String formattableString, Object arg) { - assertEquals(expected, SearchFilter.create(formattableString, arg)); - } - - static Stream limitArgumentSupplier() { - return Stream.of(Arguments.of("Foo eq NaN", "Foo eq %s", Float.NaN), - Arguments.of("Foo eq INF", "Foo eq %s", Float.POSITIVE_INFINITY), - Arguments.of("Foo eq -INF", "Foo eq %s", Float.NEGATIVE_INFINITY), - - Arguments.of("Foo eq NaN", "Foo eq %s", Double.NaN), - Arguments.of("Foo eq INF", "Foo eq %s", Double.POSITIVE_INFINITY), - Arguments.of("Foo eq -INF", "Foo eq %s", Double.NEGATIVE_INFINITY)); - } - - @Test - public void dateArgument() { - assertEquals("Foo eq 1912-06-23T11:59:59Z", SearchFilter.create("Foo eq %s", - Date.from(OffsetDateTime.of(1912, 6, 23, 11, 59, 59, 0, ZoneOffset.UTC).toInstant()))); - assertEquals("Foo eq 1912-06-23T11:59:59Z", - SearchFilter.create("Foo eq %s", OffsetDateTime.of(1912, 6, 23, 11, 59, 59, 0, ZoneOffset.UTC))); - } - - @ParameterizedTest - @MethodSource("textArgumentSupplier") - public void textArgument(String expected, String formattableString, Object arg) { - assertEquals(expected, SearchFilter.create(formattableString, arg)); - } - - @SuppressWarnings("UnnecessaryBoxing") - static Stream textArgumentSupplier() { - return Stream.of(Arguments.of("Foo eq 'x'", "Foo eq %s", 'x'), Arguments.of("Foo eq ''''", "Foo eq %s", '\''), - Arguments.of("Foo eq '\"'", "Foo eq %s", '"'), - - Arguments.of("Foo eq 'x'", "Foo eq %s", Character.valueOf('x')), - Arguments.of("Foo eq ''''", "Foo eq %s", Character.valueOf('\'')), - Arguments.of("Foo eq '\"'", "Foo eq %s", Character.valueOf('\"')), - - Arguments.of("Foo eq 'bar'", "Foo eq %s", "bar"), Arguments.of("Foo eq 'bar''s'", "Foo eq %s", "bar's"), - Arguments.of("Foo eq '\"bar\"'", "Foo eq %s", "\"bar\""), - - Arguments.of("Foo eq 'bar'", "Foo eq %s", new StringBuilder("bar")), - Arguments.of("Foo eq 'bar''s'", "Foo eq %s", new StringBuilder("bar's")), - Arguments.of("Foo eq '\"bar\"'", "Foo eq %s", new StringBuilder("\"bar\""))); - } - - @Test - public void unknownTypeThrows() { - assertThrows(IllegalArgumentException.class, () -> SearchFilter.create("Foo eq %s", HttpMethod.GET)); - } - - @ParameterizedTest - @MethodSource("geographyArgumentSupplier") - public void geographyArgument(Object geography, String formattableString, String expected) { - assertEquals(expected, SearchFilter.create(formattableString, geography)); - } - - static Stream geographyArgumentSupplier() { - final String formattableString = "Foo eq %s"; - - final String expectedPointFilter = "Foo eq geography'POINT(0 0)'"; - final String expectedPolygonFilter = "Foo eq geography'POLYGON((0 0,0 1,1 1,0 0))'"; - - final List polygonCoordinates = Arrays.asList(new GeoPosition(0D, 0D), new GeoPosition(0D, 1D), - new GeoPosition(1D, 1D), new GeoPosition(0D, 0D)); - - final List polygonCoordinatesWithAltitude = Arrays.asList(new GeoPosition(0D, 0D, 1D), - new GeoPosition(0D, 1D, 1D), new GeoPosition(1D, 1D, 1D), new GeoPosition(0D, 0D, 1D)); - - final GeoBoundingBox boundingBox = new GeoBoundingBox(-1D, -1D, 1D, 1D); - - return Stream.of( - // GeoPosition - Arguments.of(new GeoPosition(0D, 0D), formattableString, expectedPointFilter), - Arguments.of(new GeoPosition(0D, 0D, 1D), formattableString, expectedPointFilter), - - // GeoPoint - Arguments.of(new GeoPoint(0D, 0D), formattableString, expectedPointFilter), - Arguments.of(new GeoPoint(0D, 0D, 1D), formattableString, expectedPointFilter), - Arguments.of(new GeoPoint(new GeoPosition(0D, 0D)), formattableString, expectedPointFilter), - Arguments.of(new GeoPoint(new GeoPosition(0D, 0D, 1D)), formattableString, expectedPointFilter), - Arguments.of(new GeoPoint(new GeoPosition(0D, 0D), boundingBox, Collections.emptyMap()), formattableString, - expectedPointFilter), - - // GeoLineString - Arguments.of(new GeoLineString(polygonCoordinates), formattableString, expectedPolygonFilter), - Arguments.of(new GeoLineString(polygonCoordinates, boundingBox, Collections.emptyMap()), formattableString, - expectedPolygonFilter), - Arguments.of(new GeoLineString(polygonCoordinatesWithAltitude), formattableString, expectedPolygonFilter), - Arguments.of(new GeoLineString(polygonCoordinatesWithAltitude, boundingBox, Collections.emptyMap()), - formattableString, expectedPolygonFilter), - - // GeoPolygon - Arguments.of(new GeoPolygon(new GeoLinearRing(polygonCoordinates)), formattableString, - expectedPolygonFilter), - Arguments.of(new GeoPolygon(new GeoLinearRing(polygonCoordinates), boundingBox, Collections.emptyMap()), - formattableString, expectedPolygonFilter), - Arguments.of(new GeoPolygon(new GeoLinearRing(polygonCoordinatesWithAltitude)), formattableString, - expectedPolygonFilter), - Arguments.of( - new GeoPolygon(new GeoLinearRing(polygonCoordinatesWithAltitude), boundingBox, Collections.emptyMap()), - formattableString, expectedPolygonFilter), - - Arguments.of(new GeoPolygon(Collections.singletonList(new GeoLinearRing(polygonCoordinates))), - formattableString, expectedPolygonFilter), - Arguments.of(new GeoPolygon(Collections.singletonList(new GeoLinearRing(polygonCoordinates)), boundingBox, - Collections.emptyMap()), formattableString, expectedPolygonFilter), - Arguments.of(new GeoPolygon(Collections.singletonList(new GeoLinearRing(polygonCoordinatesWithAltitude))), - formattableString, expectedPolygonFilter), - Arguments.of(new GeoPolygon(Collections.singletonList(new GeoLinearRing(polygonCoordinatesWithAltitude)), - boundingBox, Collections.emptyMap()), formattableString, expectedPolygonFilter) - - ); - } -} diff --git a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/SearchIndexingBufferedSenderBuilderTests.java b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/SearchIndexingBufferedSenderBuilderTests.java deleted file mode 100644 index fd9185047844..000000000000 --- a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/SearchIndexingBufferedSenderBuilderTests.java +++ /dev/null @@ -1,74 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.search.documents; - -import com.azure.core.util.serializer.TypeReference; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.parallel.Execution; -import org.junit.jupiter.api.parallel.ExecutionMode; - -import java.time.Duration; -import java.util.HashMap; -import java.util.Map; - -import static org.junit.jupiter.api.Assertions.assertThrows; - -/** - * Tests {@link SearchClientBuilder.SearchIndexingBufferedSenderBuilder}. - */ -@Execution(ExecutionMode.CONCURRENT) -public class SearchIndexingBufferedSenderBuilderTests { - private static final Map FOOL_SPOTBUGS = new HashMap<>(); - private static final TypeReference> DOCUMENT_TYPE = new TypeReference>() { - }; - - @Test - public void invalidFlushWindowThrows() { - SearchClientBuilder.SearchIndexingBufferedSenderBuilder> options = getBaseOptions(); - Duration interval = FOOL_SPOTBUGS.get("interval"); - assertThrows(NullPointerException.class, () -> options.autoFlushInterval(interval)); - } - - @Test - public void invalidBatchSizeThrows() { - SearchClientBuilder.SearchIndexingBufferedSenderBuilder> options = getBaseOptions(); - assertThrows(IllegalArgumentException.class, () -> options.initialBatchActionCount(0)); - assertThrows(IllegalArgumentException.class, () -> options.initialBatchActionCount(-1)); - } - - @Test - public void invalidMaxRetriesThrows() { - SearchClientBuilder.SearchIndexingBufferedSenderBuilder> options = getBaseOptions(); - assertThrows(IllegalArgumentException.class, () -> options.maxRetriesPerAction(0)); - assertThrows(IllegalArgumentException.class, () -> options.maxRetriesPerAction(-1)); - } - - @Test - public void invalidRetryDelayThrows() { - SearchClientBuilder.SearchIndexingBufferedSenderBuilder> options = getBaseOptions(); - Duration throttlingDelay = FOOL_SPOTBUGS.get("throttlingDelay"); - assertThrows(NullPointerException.class, () -> options.throttlingDelay(throttlingDelay)); - assertThrows(IllegalArgumentException.class, () -> options.throttlingDelay(Duration.ZERO)); - assertThrows(IllegalArgumentException.class, () -> options.throttlingDelay(Duration.ofMillis(-1))); - } - - @Test - public void invalidMaxRetryDelayThrows() { - SearchClientBuilder.SearchIndexingBufferedSenderBuilder> options = getBaseOptions(); - Duration maxThrottlingDelay = FOOL_SPOTBUGS.get("maxThrottlingDelay"); - assertThrows(NullPointerException.class, () -> options.maxThrottlingDelay(maxThrottlingDelay)); - assertThrows(IllegalArgumentException.class, () -> options.maxThrottlingDelay(Duration.ZERO)); - assertThrows(IllegalArgumentException.class, () -> options.maxThrottlingDelay(Duration.ofMillis(-1))); - } - - // @Test - // public void invalidPayloadTooLargeScaleDownThrows() { - // SearchIndexingBufferedSenderOptions options = getBaseOptions(); - // assertThrows(NullPointerException.class, () -> options.setPayloadTooLargeScaleDown(null)); - // } - - private SearchClientBuilder.SearchIndexingBufferedSenderBuilder> getBaseOptions() { - return new SearchClientBuilder().bufferedSender(DOCUMENT_TYPE); - } -} diff --git a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/SearchIndexingBufferedSenderTests.java b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/SearchIndexingBufferedSenderTests.java deleted file mode 100644 index ae56ae11e3c8..000000000000 --- a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/SearchIndexingBufferedSenderTests.java +++ /dev/null @@ -1,482 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.search.documents; - -import com.azure.core.test.annotation.LiveOnly; -import com.azure.core.test.models.BodilessMatcher; -import com.azure.core.util.CoreUtils; -import com.azure.core.util.serializer.TypeReference; -import org.junit.jupiter.api.Test; -import reactor.test.StepVerifier; - -import java.time.Duration; -import java.util.ArrayList; -import java.util.Collections; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import java.util.concurrent.atomic.AtomicInteger; -import java.util.function.Function; -import java.util.stream.Collectors; - -import static com.azure.search.documents.TestHelpers.readJsonFileToList; -import static com.azure.search.documents.TestHelpers.waitForIndexing; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertTrue; - -/** - * Tests {@link SearchIndexingBufferedSender}. - */ -public class SearchIndexingBufferedSenderTests extends SearchTestBase { - private static final TypeReference> HOTEL_DOCUMENT_TYPE; - private static final Function, String> HOTEL_ID_KEY_RETRIEVER; - private String indexToDelete; - private SearchClientBuilder clientBuilder; - - static { - HOTEL_DOCUMENT_TYPE = new TypeReference>() { - }; - HOTEL_ID_KEY_RETRIEVER = document -> String.valueOf(document.get("HotelId")); - } - - private void setupIndex(boolean isSync) { - String indexName = createHotelIndex(); - this.indexToDelete = indexName; - - this.clientBuilder = getSearchClientBuilder(indexName, isSync); - } - - @Override - protected void afterTest() { - super.afterTest(); - - if (!CoreUtils.isNullOrEmpty(indexToDelete)) { - getSearchIndexClientBuilder(true).buildClient().deleteIndex(indexToDelete); - } - } - - /** - * Tests that flushing the batch sends the documents to the service. - */ - @Test - public void flushBatch() { - setupIndex(true); - - SearchClient client = clientBuilder.buildClient(); - SearchIndexingBufferedSender> batchingClient - = clientBuilder.bufferedSender(HOTEL_DOCUMENT_TYPE) - .documentKeyRetriever(HOTEL_ID_KEY_RETRIEVER) - .autoFlush(false) - .buildSender(); - - batchingClient.addUploadActions(readJsonFileToList(HOTELS_DATA_JSON)); - batchingClient.flush(); - - waitForIndexing(); - - assertEquals(10, client.getDocumentCount()); - - batchingClient.close(); - } - - /** - * Tests that flushing the batch sends the documents to the service. - */ - @Test - public void flushBatchAsync() { - setupIndex(false); - - SearchAsyncClient client = clientBuilder.buildAsyncClient(); - SearchIndexingBufferedAsyncSender> batchingClient - = clientBuilder.bufferedSender(HOTEL_DOCUMENT_TYPE) - .documentKeyRetriever(HOTEL_ID_KEY_RETRIEVER) - .autoFlush(false) - .buildAsyncSender(); - - StepVerifier - .create(batchingClient.addUploadActions(readJsonFileToList(HOTELS_DATA_JSON)).then(batchingClient.flush())) - .verifyComplete(); - - waitForIndexing(); - - StepVerifier.create(client.getDocumentCount()).assertNext(count -> assertEquals(10, count)).verifyComplete(); - - StepVerifier.create(batchingClient.close()).verifyComplete(); - } - - /** - * Tests that the batch will automatically flush when the configured batch size is reached, if configured for auto - * flushing. - */ - @Test - public void autoFlushBatchOnSize() { - setupIndex(true); - - SearchClient client = clientBuilder.buildClient(); - SearchIndexingBufferedSender> batchingClient - = clientBuilder.bufferedSender(HOTEL_DOCUMENT_TYPE) - .documentKeyRetriever(HOTEL_ID_KEY_RETRIEVER) - .autoFlushInterval(Duration.ofMinutes(5)) - .initialBatchActionCount(10) - .buildSender(); - - batchingClient.addUploadActions(readJsonFileToList(HOTELS_DATA_JSON)); - - waitForIndexing(); - - assertEquals(10, client.getDocumentCount()); - batchingClient.close(); - } - - /** - * Tests that the batch will automatically flush when the configured batch size is reached, if configured for auto - * flushing. - */ - @Test - public void autoFlushBatchOnSizeAsync() { - setupIndex(false); - - SearchAsyncClient client = clientBuilder.buildAsyncClient(); - SearchIndexingBufferedAsyncSender> batchingClient - = clientBuilder.bufferedSender(HOTEL_DOCUMENT_TYPE) - .documentKeyRetriever(HOTEL_ID_KEY_RETRIEVER) - .autoFlushInterval(Duration.ofMinutes(5)) - .initialBatchActionCount(10) - .buildAsyncSender(); - - StepVerifier.create(batchingClient.addUploadActions(readJsonFileToList(HOTELS_DATA_JSON))).verifyComplete(); - - waitForIndexing(); - - StepVerifier.create(client.getDocumentCount()).assertNext(count -> assertEquals(10, count)).verifyComplete(); - - StepVerifier.create(batchingClient.close()).verifyComplete(); - } - - /** - * Tests that batching will automatically flush when the flush windows completes, if configured for auto flushing. - */ - @Test - public void autoFlushBatchOnDelay() { - setupIndex(true); - - SearchClient client = clientBuilder.buildClient(); - SearchIndexingBufferedSender> batchingClient - = clientBuilder.bufferedSender(HOTEL_DOCUMENT_TYPE) - .documentKeyRetriever(HOTEL_ID_KEY_RETRIEVER) - .initialBatchActionCount(10) - .autoFlushInterval(Duration.ofSeconds(3)) - .buildSender(); - - batchingClient.addUploadActions(readJsonFileToList(HOTELS_DATA_JSON)); - - waitForIndexing(); - - assertEquals(10, client.getDocumentCount()); - batchingClient.close(); - } - - /** - * Tests that batching will automatically flush when the flush windows completes, if configured for auto flushing. - */ - @Test - public void autoFlushBatchOnDelayAsync() { - setupIndex(false); - - SearchAsyncClient client = clientBuilder.buildAsyncClient(); - SearchIndexingBufferedAsyncSender> batchingClient - = clientBuilder.bufferedSender(HOTEL_DOCUMENT_TYPE) - .documentKeyRetriever(HOTEL_ID_KEY_RETRIEVER) - .initialBatchActionCount(10) - .autoFlushInterval(Duration.ofSeconds(3)) - .buildAsyncSender(); - - StepVerifier.create(batchingClient.addUploadActions(readJsonFileToList(HOTELS_DATA_JSON))).verifyComplete(); - - waitForIndexing(); - - StepVerifier.create(client.getDocumentCount()).assertNext(count -> assertEquals(10, count)).verifyComplete(); - - StepVerifier.create(batchingClient.close()).verifyComplete(); - } - - /** - * Tests that the batch will flush when the client is closed and documents still exist in the batch. - */ - @Test - public void batchFlushesOnClose() { - setupIndex(true); - - SearchClient client = clientBuilder.buildClient(); - SearchIndexingBufferedSender> batchingClient - = clientBuilder.bufferedSender(HOTEL_DOCUMENT_TYPE) - .documentKeyRetriever(HOTEL_ID_KEY_RETRIEVER) - .buildSender(); - - batchingClient.addUploadActions(readJsonFileToList(HOTELS_DATA_JSON)); - batchingClient.close(); - - waitForIndexing(); - - assertEquals(10, client.getDocumentCount()); - } - - /** - * Tests that the batch will flush when the client is closed and documents still exist in the batch. - */ - @Test - public void batchFlushesOnCloseAsync() { - setupIndex(false); - - SearchAsyncClient client = clientBuilder.buildAsyncClient(); - SearchIndexingBufferedAsyncSender> batchingClient - = clientBuilder.bufferedSender(HOTEL_DOCUMENT_TYPE) - .documentKeyRetriever(HOTEL_ID_KEY_RETRIEVER) - .buildAsyncSender(); - - StepVerifier - .create(batchingClient.addUploadActions(readJsonFileToList(HOTELS_DATA_JSON)).then(batchingClient.close())) - .verifyComplete(); - - waitForIndexing(); - - StepVerifier.create(client.getDocumentCount()).assertNext(count -> assertEquals(10, count)).verifyComplete(); - } - - /** - * Tests that when a batch has documents added but flush, auto-flush, or close is never called the documents don't - * get indexed. - */ - @Test - public void batchGetsDocumentsButNeverFlushes() { - setupIndex(true); - - SearchClient client = clientBuilder.buildClient(); - SearchIndexingBufferedSender> batchingClient - = clientBuilder.bufferedSender(HOTEL_DOCUMENT_TYPE) - .documentKeyRetriever(HOTEL_ID_KEY_RETRIEVER) - .autoFlushInterval(Duration.ofMinutes(5)) - .initialBatchActionCount(1000) - .buildSender(); - - batchingClient.addUploadActions(readJsonFileToList(HOTELS_DATA_JSON)); - - waitForIndexing(); - - assertEquals(0, client.getDocumentCount()); - batchingClient.close(); - } - - /** - * Tests that when a batch has documents added but flush, auto-flush, or close is never called the documents don't - * get indexed. - */ - @Test - public void batchGetsDocumentsButNeverFlushesAsync() { - setupIndex(false); - - SearchAsyncClient client = clientBuilder.buildAsyncClient(); - SearchIndexingBufferedAsyncSender> batchingClient - = clientBuilder.bufferedSender(HOTEL_DOCUMENT_TYPE) - .documentKeyRetriever(HOTEL_ID_KEY_RETRIEVER) - .autoFlushInterval(Duration.ofMinutes(5)) - .initialBatchActionCount(1000) - .buildAsyncSender(); - - StepVerifier.create(batchingClient.addUploadActions(readJsonFileToList(HOTELS_DATA_JSON))).verifyComplete(); - - waitForIndexing(); - - StepVerifier.create(client.getDocumentCount()).assertNext(count -> assertEquals(0, count)).verifyComplete(); - - StepVerifier.create(batchingClient.close()).verifyComplete(); - } - - @Test - @LiveOnly - public void indexManyDocumentsSmallDocumentSets() { - interceptorManager.addMatchers(Collections.singletonList(new BodilessMatcher())); - - setupIndex(true); - - AtomicInteger requestCount = new AtomicInteger(); - AtomicInteger successCount = new AtomicInteger(); - AtomicInteger failedCount = new AtomicInteger(); - - SearchClientBuilder builder = clientBuilder.addPolicy((context, next) -> { - requestCount.incrementAndGet(); - return next.process(); - }); - - SearchClient client = builder.buildClient(); - SearchIndexingBufferedSender> batchingClient = builder.bufferedSender(HOTEL_DOCUMENT_TYPE) - .documentKeyRetriever(HOTEL_ID_KEY_RETRIEVER) - .autoFlushInterval(Duration.ofSeconds(5)) - .initialBatchActionCount(10) - .onActionSucceeded(options -> successCount.incrementAndGet()) - .onActionError(options -> failedCount.incrementAndGet()) - .buildSender(); - - List> documents = readJsonFileToList(HOTELS_DATA_JSON); - for (int i = 0; i < 100; i++) { - final int offset = i; - batchingClient.addUploadActions(documents.stream().map(LinkedHashMap::new).peek(document -> { - int originalId = Integer.parseInt(document.get("HotelId").toString()); - document.put("HotelId", String.valueOf((offset * 10) + originalId)); - }).collect(Collectors.toList())); - } - - batchingClient.close(); - - sleepIfRunningAgainstService(10000); - - assertEquals(1000, successCount.get()); - assertEquals(0, failedCount.get()); - assertTrue(requestCount.get() >= 100); - assertEquals(1000, client.getDocumentCount()); - } - - @Test - @LiveOnly - public void indexManyDocumentsSmallDocumentSetsAsync() { - interceptorManager.addMatchers(Collections.singletonList(new BodilessMatcher())); - - setupIndex(false); - - AtomicInteger requestCount = new AtomicInteger(); - AtomicInteger successCount = new AtomicInteger(); - AtomicInteger failedCount = new AtomicInteger(); - - SearchClientBuilder builder = clientBuilder.addPolicy((context, next) -> { - requestCount.incrementAndGet(); - return next.process(); - }); - - SearchAsyncClient client = builder.buildAsyncClient(); - SearchIndexingBufferedAsyncSender> batchingClient - = builder.bufferedSender(HOTEL_DOCUMENT_TYPE) - .documentKeyRetriever(HOTEL_ID_KEY_RETRIEVER) - .autoFlushInterval(Duration.ofSeconds(5)) - .initialBatchActionCount(10) - .onActionSucceeded(options -> successCount.incrementAndGet()) - .onActionError(options -> failedCount.incrementAndGet()) - .buildAsyncSender(); - - List> documents = readJsonFileToList(HOTELS_DATA_JSON); - for (int i = 0; i < 100; i++) { - final int offset = i; - StepVerifier.create(batchingClient.addUploadActions(documents.stream() - .map(LinkedHashMap::new) - .peek(document -> document.put("HotelId", - String.valueOf((offset * 10) + Integer.parseInt(document.get("HotelId").toString())))) - .collect(Collectors.toList()))).verifyComplete(); - } - - StepVerifier.create(batchingClient.close()).verifyComplete(); - - sleepIfRunningAgainstService(10000); - - assertEquals(1000, successCount.get()); - assertEquals(0, failedCount.get()); - assertTrue(requestCount.get() >= 100); - StepVerifier.create(client.getDocumentCount()).assertNext(count -> assertEquals(1000, count)).verifyComplete(); - } - - @Test - @LiveOnly - public void indexManyDocumentsOneLargeDocumentSet() { - interceptorManager.addMatchers(Collections.singletonList(new BodilessMatcher())); - - setupIndex(true); - - AtomicInteger requestCount = new AtomicInteger(); - AtomicInteger successCount = new AtomicInteger(); - AtomicInteger failedCount = new AtomicInteger(); - - SearchClientBuilder builder = clientBuilder.addPolicy((context, next) -> { - requestCount.incrementAndGet(); - return next.process(); - }); - - SearchClient client = builder.buildClient(); - SearchIndexingBufferedSender> batchingClient = builder.bufferedSender(HOTEL_DOCUMENT_TYPE) - .documentKeyRetriever(HOTEL_ID_KEY_RETRIEVER) - .autoFlushInterval(Duration.ofSeconds(5)) - .initialBatchActionCount(10) - .onActionSucceeded(options -> successCount.incrementAndGet()) - .onActionError(options -> failedCount.incrementAndGet()) - .buildSender(); - - List> documents = readJsonFileToList(HOTELS_DATA_JSON); - List> documentBatch = new ArrayList<>(); - for (int i = 0; i < 100; i++) { - final int offset = i; - documents.stream().map(LinkedHashMap::new).forEach(document -> { - int originalId = Integer.parseInt(document.get("HotelId").toString()); - document.put("HotelId", String.valueOf((offset * 10) + originalId)); - documentBatch.add(document); - }); - } - - batchingClient.addUploadActions(documentBatch); - - batchingClient.close(); - - sleepIfRunningAgainstService(10000); - - assertEquals(1000, successCount.get()); - assertEquals(0, failedCount.get()); - assertTrue(requestCount.get() >= 100); - assertEquals(1000, client.getDocumentCount()); - } - - @Test - @LiveOnly - public void indexManyDocumentsOneLargeDocumentSetAsync() { - interceptorManager.addMatchers(Collections.singletonList(new BodilessMatcher())); - - setupIndex(false); - - AtomicInteger requestCount = new AtomicInteger(); - AtomicInteger successCount = new AtomicInteger(); - AtomicInteger failedCount = new AtomicInteger(); - - SearchClientBuilder builder = clientBuilder.addPolicy((context, next) -> { - requestCount.incrementAndGet(); - return next.process(); - }); - - SearchAsyncClient client = clientBuilder.buildAsyncClient(); - SearchIndexingBufferedAsyncSender> batchingClient - = builder.bufferedSender(HOTEL_DOCUMENT_TYPE) - .documentKeyRetriever(HOTEL_ID_KEY_RETRIEVER) - .autoFlushInterval(Duration.ofSeconds(5)) - .initialBatchActionCount(10) - .onActionSucceeded(options -> successCount.incrementAndGet()) - .onActionError(options -> failedCount.incrementAndGet()) - .buildAsyncSender(); - - List> documents = readJsonFileToList(HOTELS_DATA_JSON); - List> documentBatch = new ArrayList<>(); - for (int i = 0; i < 100; i++) { - final int offset = i; - documents.stream().map(LinkedHashMap::new).forEach(document -> { - int originalId = Integer.parseInt(document.get("HotelId").toString()); - document.put("HotelId", String.valueOf((offset * 10) + originalId)); - documentBatch.add(document); - }); - } - - StepVerifier.create(batchingClient.addUploadActions(documentBatch).then(batchingClient.close())) - .verifyComplete(); - - sleepIfRunningAgainstService(10000); - - assertEquals(1000, successCount.get()); - assertEquals(0, failedCount.get()); - assertTrue(requestCount.get() >= 100); - - StepVerifier.create(client.getDocumentCount()).assertNext(count -> assertEquals(1000, count)).verifyComplete(); - } -} diff --git a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/SearchIndexingBufferedSenderUnitTests.java b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/SearchIndexingBufferedSenderUnitTests.java deleted file mode 100644 index ea42b1a5950f..000000000000 --- a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/SearchIndexingBufferedSenderUnitTests.java +++ /dev/null @@ -1,1536 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -package com.azure.search.documents; - -import com.azure.core.http.HttpClient; -import com.azure.core.http.HttpHeaders; -import com.azure.core.http.HttpRequest; -import com.azure.core.http.HttpResponse; -import com.azure.core.http.policy.FixedDelay; -import com.azure.core.http.policy.RetryPolicy; -import com.azure.core.test.http.AssertingHttpClientBuilder; -import com.azure.core.test.http.MockHttpResponse; -import com.azure.core.util.Context; -import com.azure.core.util.FluxUtil; -import com.azure.core.util.serializer.TypeReference; -import com.azure.json.JsonProviders; -import com.azure.json.JsonReader; -import com.azure.json.JsonWriter; -import com.azure.search.documents.implementation.models.IndexBatch; -import com.azure.search.documents.models.IndexAction; -import com.azure.search.documents.models.IndexActionType; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.function.Executable; -import org.junit.jupiter.api.parallel.Execution; -import org.junit.jupiter.api.parallel.ExecutionMode; -import org.junit.jupiter.params.ParameterizedTest; -import org.junit.jupiter.params.provider.MethodSource; -import reactor.core.publisher.Mono; -import reactor.test.StepVerifier; - -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.UncheckedIOException; -import java.time.Duration; -import java.util.Arrays; -import java.util.Collections; -import java.util.List; -import java.util.Map; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.ForkJoinPool; -import java.util.concurrent.TimeoutException; -import java.util.concurrent.atomic.AtomicInteger; -import java.util.concurrent.atomic.AtomicLong; -import java.util.function.Consumer; -import java.util.function.Function; -import java.util.stream.Collectors; -import java.util.stream.Stream; - -import static com.azure.search.documents.SearchTestBase.ENDPOINT; -import static com.azure.search.documents.SearchTestBase.HOTELS_DATA_JSON; -import static com.azure.search.documents.TestHelpers.getTestTokenCredential; -import static com.azure.search.documents.TestHelpers.readJsonFileToList; -import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.junit.jupiter.api.Assertions.assertTrue; - -@Execution(ExecutionMode.CONCURRENT) -public class SearchIndexingBufferedSenderUnitTests { - private static final TypeReference> HOTEL_DOCUMENT_TYPE; - private static final Function, String> HOTEL_ID_KEY_RETRIEVER; - - static { - HOTEL_DOCUMENT_TYPE = new TypeReference>() { - }; - HOTEL_ID_KEY_RETRIEVER = document -> String.valueOf(document.get("HotelId")); - } - - private static SearchClientBuilder getSearchClientBuilder() { - return new SearchClientBuilder().endpoint(ENDPOINT).indexName("index").credential(getTestTokenCredential()); - } - - private static HttpClient wrapWithAsserting(HttpClient wrappedHttpClient, boolean isSync) { - if (isSync) { - return new AssertingHttpClientBuilder(wrappedHttpClient).assertSync() - .skipRequest((ignored1, ignored2) -> false) - .build(); - } else { - return new AssertingHttpClientBuilder(wrappedHttpClient).assertAsync() - .skipRequest((ignored1, ignored2) -> false) - .build(); - } - } - - /** - * Tests that a batch can timeout while indexing. - */ - @Test - public void flushTimesOut() { - SearchIndexingBufferedSender> batchingClient - = getSearchClientBuilder().httpClient(wrapWithAsserting(request -> { - sleep(5000); - return Mono.just(new MockHttpResponse(request, 207, new HttpHeaders(), createMockResponseData(0, 200))); - }, true)) - .bufferedSender(HOTEL_DOCUMENT_TYPE) - .documentKeyRetriever(HOTEL_ID_KEY_RETRIEVER) - .autoFlush(false) - .buildSender(); - - batchingClient.addUploadActions(readJsonFileToList(HOTELS_DATA_JSON).subList(0, 1)); - - assertThrows(RuntimeException.class, () -> batchingClient.flush(Duration.ofSeconds(1), Context.NONE)); - } - - /** - * Tests that a batch can timeout while indexing. - */ - @Test - public void flushTimesOutAsync() { - SearchIndexingBufferedAsyncSender> batchingClient - = getSearchClientBuilder().httpClient(wrapWithAsserting(request -> { - sleep(5000); - return Mono.just(new MockHttpResponse(request, 207, new HttpHeaders(), createMockResponseData(0, 200))); - }, false)) - .bufferedSender(HOTEL_DOCUMENT_TYPE) - .documentKeyRetriever(HOTEL_ID_KEY_RETRIEVER) - .autoFlush(false) - .buildAsyncSender(); - - StepVerifier.create(batchingClient.addUploadActions(readJsonFileToList(HOTELS_DATA_JSON).subList(0, 1))) - .verifyComplete(); - - StepVerifier.create(batchingClient.flush().timeout(Duration.ofSeconds(1))).verifyError(TimeoutException.class); - } - - /** - * Tests that a batch will retain in-flight documents if the request is cancelled before the response is handled. - */ - @Test - public void inFlightDocumentsAreRetried() { - AtomicInteger callCount = new AtomicInteger(0); - AtomicInteger addedCount = new AtomicInteger(); - AtomicInteger successCount = new AtomicInteger(); - AtomicInteger errorCount = new AtomicInteger(); - AtomicInteger sentCount = new AtomicInteger(); - - SearchIndexingBufferedSender> batchingClient - = getSearchClientBuilder().httpClient(wrapWithAsserting(request -> { - Mono response = Mono.just(new MockHttpResponse(request, 207, new HttpHeaders(), - createMockResponseData(0, 200, 200, 200, 200, 200, 200, 200, 200, 200, 200))); - if (callCount.getAndIncrement() == 0) { - return response.delayElement(Duration.ofSeconds(5)); - } else { - return response; - } - }, true)) - .bufferedSender(HOTEL_DOCUMENT_TYPE) - .documentKeyRetriever(HOTEL_ID_KEY_RETRIEVER) - .autoFlush(false) - .onActionAdded(ignored -> addedCount.incrementAndGet()) - .onActionSent(ignored -> sentCount.incrementAndGet()) - .onActionError(ignored -> errorCount.incrementAndGet()) - .onActionSucceeded(ignored -> successCount.incrementAndGet()) - .buildSender(); - - batchingClient.addUploadActions(readJsonFileToList(HOTELS_DATA_JSON)); - - // First request is setup to timeout. - assertThrows(RuntimeException.class, () -> batchingClient.flush(Duration.ofSeconds(3), Context.NONE)); - - // Second request shouldn't timeout. - assertDoesNotThrow(() -> batchingClient.flush(Duration.ofSeconds(3), Context.NONE)); - - // Then validate that we have the expected number of requests sent and responded. - assertEquals(10, addedCount.get()); - assertEquals(20, sentCount.get()); - assertEquals(0, errorCount.get()); - assertEquals(10, successCount.get()); - } - - /** - * Tests that a batch will retain in-flight documents if the request is cancelled before the response is handled. - */ - @Test - public void inFlightDocumentsAreRetriedAsync() { - AtomicInteger callCount = new AtomicInteger(0); - AtomicInteger addedCount = new AtomicInteger(); - AtomicInteger successCount = new AtomicInteger(); - AtomicInteger errorCount = new AtomicInteger(); - AtomicInteger sentCount = new AtomicInteger(); - - SearchIndexingBufferedAsyncSender> batchingClient - = getSearchClientBuilder().httpClient(wrapWithAsserting(request -> { - Mono response = Mono.just(new MockHttpResponse(request, 207, new HttpHeaders(), - createMockResponseData(0, 200, 200, 200, 200, 200, 200, 200, 200, 200, 200))); - if (callCount.getAndIncrement() == 0) { - return response.delayElement(Duration.ofSeconds(5)); - } else { - return response; - } - }, false)) - .bufferedSender(HOTEL_DOCUMENT_TYPE) - .documentKeyRetriever(HOTEL_ID_KEY_RETRIEVER) - .autoFlush(false) - .onActionAdded(ignored -> addedCount.incrementAndGet()) - .onActionSent(ignored -> sentCount.incrementAndGet()) - .onActionError(ignored -> errorCount.incrementAndGet()) - .onActionSucceeded(ignored -> successCount.incrementAndGet()) - .buildAsyncSender(); - - StepVerifier.create(batchingClient.addUploadActions(readJsonFileToList(HOTELS_DATA_JSON))).verifyComplete(); - - // First request is setup to timeout. - StepVerifier.create(batchingClient.flush().timeout(Duration.ofSeconds(3))).verifyError(TimeoutException.class); - - // Second request shouldn't timeout. - StepVerifier.create(batchingClient.flush().timeout(Duration.ofSeconds(3))).verifyComplete(); - - // Then validate that we have the expected number of requests sent and responded. - assertEquals(10, addedCount.get()); - assertEquals(20, sentCount.get()); - assertEquals(0, errorCount.get()); - assertEquals(10, successCount.get()); - } - - /** - * Tests that when a batch has some failures the indexing hook is properly notified. - */ - @Test - public void batchHasSomeFailures() { - AtomicInteger addedCount = new AtomicInteger(); - AtomicInteger successCount = new AtomicInteger(); - AtomicInteger errorCount = new AtomicInteger(); - AtomicInteger sentCount = new AtomicInteger(); - - SearchIndexingBufferedSender> batchingClient = getSearchClientBuilder() - .httpClient(wrapWithAsserting(request -> Mono.just(new MockHttpResponse(request, 207, new HttpHeaders(), - createMockResponseData(0, 201, 400, 201, 404, 200, 200, 404, 400, 400, 201))), true)) - .bufferedSender(HOTEL_DOCUMENT_TYPE) - .documentKeyRetriever(HOTEL_ID_KEY_RETRIEVER) - .autoFlush(false) - .onActionAdded(options -> addedCount.incrementAndGet()) - .onActionSucceeded(options -> successCount.incrementAndGet()) - .onActionError(options -> errorCount.incrementAndGet()) - .onActionSent(options -> sentCount.incrementAndGet()) - .buildSender(); - - batchingClient.addUploadActions(readJsonFileToList(HOTELS_DATA_JSON)); - - // Exceptions are propagated into the onActionError. - assertDoesNotThrow((Executable) batchingClient::flush); - - assertEquals(10, addedCount.get()); - assertEquals(5, successCount.get()); - assertEquals(5, errorCount.get()); - assertEquals(10, sentCount.get()); - - /* - * No documents failed with retryable errors, so we should expect zero documents are added back into the batch. - */ - assertEquals(0, batchingClient.getActions().size()); - } - - /** - * Tests that when a batch has some failures the indexing hook is properly notified. - */ - @Test - public void batchHasSomeFailuresAsync() { - AtomicInteger addedCount = new AtomicInteger(); - AtomicInteger successCount = new AtomicInteger(); - AtomicInteger errorCount = new AtomicInteger(); - AtomicInteger sentCount = new AtomicInteger(); - - SearchIndexingBufferedAsyncSender> batchingClient = getSearchClientBuilder() - .httpClient(wrapWithAsserting(request -> Mono.just(new MockHttpResponse(request, 207, new HttpHeaders(), - createMockResponseData(0, 201, 400, 201, 404, 200, 200, 404, 400, 400, 201))), false)) - .bufferedSender(HOTEL_DOCUMENT_TYPE) - .documentKeyRetriever(HOTEL_ID_KEY_RETRIEVER) - .autoFlush(false) - .onActionAdded(options -> addedCount.incrementAndGet()) - .onActionSucceeded(options -> successCount.incrementAndGet()) - .onActionError(options -> errorCount.incrementAndGet()) - .onActionSent(options -> sentCount.incrementAndGet()) - .buildAsyncSender(); - - StepVerifier.create(batchingClient.addUploadActions(readJsonFileToList(HOTELS_DATA_JSON))).verifyComplete(); - - // Exceptions are propagated into the onActionError. - StepVerifier.create(batchingClient.flush()).verifyComplete(); - - assertEquals(10, addedCount.get()); - assertEquals(5, successCount.get()); - assertEquals(5, errorCount.get()); - assertEquals(10, sentCount.get()); - - /* - * No documents failed with retryable errors, so we should expect zero documents are added back into the batch. - */ - assertEquals(0, batchingClient.getActions().size()); - } - - /** - * Tests that a batch will retry documents that fail with retryable status code. - */ - @Test - public void retryableDocumentsAreAddedBackToTheBatch() { - AtomicInteger addedCount = new AtomicInteger(); - AtomicInteger successCount = new AtomicInteger(); - AtomicInteger errorCount = new AtomicInteger(); - AtomicInteger sentCount = new AtomicInteger(); - - SearchIndexingBufferedSender> batchingClient = getSearchClientBuilder() - .httpClient(wrapWithAsserting(request -> Mono.just(new MockHttpResponse(request, 207, new HttpHeaders(), - createMockResponseData(0, 201, 409, 201, 422, 200, 200, 503, 409, 422, 201))), true)) - .bufferedSender(HOTEL_DOCUMENT_TYPE) - .documentKeyRetriever(HOTEL_ID_KEY_RETRIEVER) - .autoFlush(false) - .onActionAdded(options -> addedCount.incrementAndGet()) - .onActionSucceeded(options -> successCount.incrementAndGet()) - .onActionError(options -> errorCount.incrementAndGet()) - .onActionSent(options -> sentCount.incrementAndGet()) - .buildSender(); - - batchingClient.addUploadActions(readJsonFileToList(HOTELS_DATA_JSON)); - - // Exceptions are propagated into the onActionError. - assertDoesNotThrow((Executable) batchingClient::flush); - - assertEquals(10, addedCount.get()); - assertEquals(10, sentCount.get()); - assertEquals(5, successCount.get()); - assertEquals(0, errorCount.get()); - - /* - * 5 documents failed with retryable errors, so we should expect 5 documents are added back into the batch. - */ - assertEquals(5, batchingClient.getActions().size()); - } - - /** - * Tests that a batch will retry documents that fail with retryable status code. - */ - @Test - public void retryableDocumentsAreAddedBackToTheBatchAsync() { - AtomicInteger addedCount = new AtomicInteger(); - AtomicInteger successCount = new AtomicInteger(); - AtomicInteger errorCount = new AtomicInteger(); - AtomicInteger sentCount = new AtomicInteger(); - - SearchIndexingBufferedAsyncSender> batchingClient = getSearchClientBuilder() - .httpClient(wrapWithAsserting(request -> Mono.just(new MockHttpResponse(request, 207, new HttpHeaders(), - createMockResponseData(0, 201, 409, 201, 422, 200, 200, 503, 409, 422, 201))), false)) - .bufferedSender(HOTEL_DOCUMENT_TYPE) - .documentKeyRetriever(HOTEL_ID_KEY_RETRIEVER) - .autoFlush(false) - .onActionAdded(options -> addedCount.incrementAndGet()) - .onActionSucceeded(options -> successCount.incrementAndGet()) - .onActionError(options -> errorCount.incrementAndGet()) - .onActionSent(options -> sentCount.incrementAndGet()) - .buildAsyncSender(); - - StepVerifier.create(batchingClient.addUploadActions(readJsonFileToList(HOTELS_DATA_JSON))).verifyComplete(); - - // Exceptions are propagated into the onActionError. - StepVerifier.create(batchingClient.flush()).verifyComplete(); - - assertEquals(10, addedCount.get()); - assertEquals(10, sentCount.get()); - assertEquals(5, successCount.get()); - assertEquals(0, errorCount.get()); - - /* - * 5 documents failed with retryable errors, so we should expect 5 documents are added back into the batch. - */ - assertEquals(5, batchingClient.getActions().size()); - } - - /** - * Tests that a batch splits if the service responds with a 413. - */ - @Test - public void batchSplits() { - AtomicInteger callCount = new AtomicInteger(); - AtomicInteger addedCount = new AtomicInteger(); - AtomicInteger successCount = new AtomicInteger(); - AtomicInteger errorCount = new AtomicInteger(); - AtomicInteger sentCount = new AtomicInteger(); - - SearchIndexingBufferedSender> batchingClient - = getSearchClientBuilder().httpClient(wrapWithAsserting(request -> { - int count = callCount.getAndIncrement(); - if (count == 0) { - return Mono.just(new MockHttpResponse(request, 413)); - } else if (count == 1) { - return createMockBatchSplittingResponse(request, 0, 5); - } else if (count == 2) { - return createMockBatchSplittingResponse(request, 5, 5); - } else { - return Mono.error(new IllegalStateException("Unexpected request.")); - } - }, true)) - .bufferedSender(HOTEL_DOCUMENT_TYPE) - .documentKeyRetriever(HOTEL_ID_KEY_RETRIEVER) - .autoFlush(false) - .initialBatchActionCount(10) - .onActionAdded(options -> addedCount.incrementAndGet()) - .onActionSucceeded(options -> successCount.incrementAndGet()) - .onActionError(options -> errorCount.incrementAndGet()) - .onActionSent(options -> sentCount.incrementAndGet()) - .buildSender(); - - batchingClient.addUploadActions(readJsonFileToList(HOTELS_DATA_JSON)); - - // No exception is thrown as the batch splits and retries successfully. - assertDoesNotThrow((Executable) batchingClient::flush); - - assertEquals(10, addedCount.get()); - assertEquals(10, successCount.get()); - assertEquals(0, errorCount.get()); - assertEquals(20, sentCount.get()); - - /* - * No documents failed, so we should expect zero documents are added back into the batch. - */ - assertEquals(0, batchingClient.getActions().size()); - } - - /** - * Tests that a batch splits if the service responds with a 413. - */ - @Test - public void batchSplitsAsync() { - AtomicInteger callCount = new AtomicInteger(); - AtomicInteger addedCount = new AtomicInteger(); - AtomicInteger successCount = new AtomicInteger(); - AtomicInteger errorCount = new AtomicInteger(); - AtomicInteger sentCount = new AtomicInteger(); - - SearchIndexingBufferedAsyncSender> batchingClient - = getSearchClientBuilder().httpClient(wrapWithAsserting(request -> { - int count = callCount.getAndIncrement(); - if (count == 0) { - return Mono.just(new MockHttpResponse(request, 413)); - } else if (count == 1) { - return createMockBatchSplittingResponse(request, 0, 5); - } else if (count == 2) { - return createMockBatchSplittingResponse(request, 5, 5); - } else { - return Mono.error(new IllegalStateException("Unexpected request.")); - } - }, false)) - .bufferedSender(HOTEL_DOCUMENT_TYPE) - .documentKeyRetriever(HOTEL_ID_KEY_RETRIEVER) - .autoFlush(false) - .initialBatchActionCount(10) - .onActionAdded(options -> addedCount.incrementAndGet()) - .onActionSucceeded(options -> successCount.incrementAndGet()) - .onActionError(options -> errorCount.incrementAndGet()) - .onActionSent(options -> sentCount.incrementAndGet()) - .buildAsyncSender(); - - StepVerifier.create(batchingClient.addUploadActions(readJsonFileToList(HOTELS_DATA_JSON))).verifyComplete(); - - // No exception is thrown as the batch splits and retries successfully. - StepVerifier.create(batchingClient.flush()).verifyComplete(); - - assertEquals(10, addedCount.get()); - assertEquals(10, successCount.get()); - assertEquals(0, errorCount.get()); - assertEquals(20, sentCount.get()); - - /* - * No documents failed, so we should expect zero documents are added back into the batch. - */ - assertEquals(0, batchingClient.getActions().size()); - } - - /** - * Tests that flushing a batch doesn't include duplicate keys. - */ - @Test - public void batchTakesAllNonDuplicateKeys() { - AtomicInteger callCount = new AtomicInteger(); - SearchIndexingBufferedSender> batchingClient - = getSearchClientBuilder().httpClient(wrapWithAsserting(request -> { - int count = callCount.getAndIncrement(); - if (count == 0) { - return Mono.just(new MockHttpResponse(request, 200, new HttpHeaders(), - createMockResponseData(0, 200, 200, 200, 200, 200, 200, 200, 200, 200))); - } else { - return Mono - .just(new MockHttpResponse(request, 200, new HttpHeaders(), createMockResponseData(0, 200))); - } - }, true)).bufferedSender(HOTEL_DOCUMENT_TYPE).documentKeyRetriever(HOTEL_ID_KEY_RETRIEVER).buildSender(); - - List> documents = readJsonFileToList(HOTELS_DATA_JSON); - documents.get(9).put("HotelId", "1"); - - batchingClient.addUploadActions(documents); - - assertDoesNotThrow((Executable) batchingClient::flush); - - /* - * One document shouldn't have been sent as it contains a duplicate key from an earlier document. - */ - assertEquals(1, batchingClient.getActions().size()); - - assertDoesNotThrow((Executable) batchingClient::flush); - - /* - * No documents should remain as no duplicate keys exists. - */ - assertEquals(0, batchingClient.getActions().size()); - } - - /** - * Tests that flushing a batch doesn't include duplicate keys. - */ - @Test - public void batchTakesAllNonDuplicateKeysAsync() { - AtomicInteger callCount = new AtomicInteger(); - SearchIndexingBufferedAsyncSender> batchingClient - = getSearchClientBuilder().httpClient(wrapWithAsserting(request -> { - int count = callCount.getAndIncrement(); - if (count == 0) { - return Mono.just(new MockHttpResponse(request, 200, new HttpHeaders(), - createMockResponseData(0, 200, 200, 200, 200, 200, 200, 200, 200, 200))); - } else { - return Mono - .just(new MockHttpResponse(request, 200, new HttpHeaders(), createMockResponseData(0, 200))); - } - }, false)) - .bufferedSender(HOTEL_DOCUMENT_TYPE) - .documentKeyRetriever(HOTEL_ID_KEY_RETRIEVER) - .buildAsyncSender(); - - List> documents = readJsonFileToList(HOTELS_DATA_JSON); - documents.get(9).put("HotelId", "1"); - - StepVerifier.create(batchingClient.addUploadActions(documents)).verifyComplete(); - - StepVerifier.create(batchingClient.flush()).verifyComplete(); - - /* - * One document shouldn't have been sent as it contains a duplicate key from an earlier document. - */ - assertEquals(1, batchingClient.getActions().size()); - - StepVerifier.create(batchingClient.flush()).verifyComplete(); - - /* - * No documents should remain as no duplicate keys exists. - */ - assertEquals(0, batchingClient.getActions().size()); - } - - @Test - public void batchWithDuplicateKeysBeingRetriedTakesAllNonDuplicateKeys() { - AtomicInteger callCount = new AtomicInteger(); - SearchIndexingBufferedSender> batchingClient - = getSearchClientBuilder().httpClient(wrapWithAsserting(request -> { - int count = callCount.getAndIncrement(); - if (count == 0) { - return Mono.just(new MockHttpResponse(request, 207, new HttpHeaders(), - createMockResponseData(0, 503, 200, 200, 200, 200, 200, 200, 200, 200))); - } else { - return Mono - .just(new MockHttpResponse(request, 200, new HttpHeaders(), createMockResponseData(0, 200))); - } - }, true)).bufferedSender(HOTEL_DOCUMENT_TYPE).documentKeyRetriever(HOTEL_ID_KEY_RETRIEVER).buildSender(); - - List> documents = readJsonFileToList(HOTELS_DATA_JSON); - documents.get(9).put("HotelId", "1"); - - batchingClient.addUploadActions(documents); - - assertDoesNotThrow((Executable) batchingClient::flush); - - /* - * Two documents should be in the batch as one failed with a retryable status code and another wasn't sent as it - * used a duplicate key from the batch that was sent. - */ - assertEquals(2, batchingClient.getActions().size()); - - assertDoesNotThrow((Executable) batchingClient::flush); - - /* - * One document should remain in the batch as it had the same key as another document in the batch. - */ - assertEquals(1, batchingClient.getActions().size()); - - assertDoesNotThrow((Executable) batchingClient::flush); - assertDoesNotThrow((Executable) batchingClient::close); - - /* - * No documents should remain as no duplicate keys exists. - */ - assertEquals(0, batchingClient.getActions().size()); - } - - @Test - public void batchWithDuplicateKeysBeingRetriedTakesAllNonDuplicateKeysAsync() { - AtomicInteger callCount = new AtomicInteger(); - SearchIndexingBufferedAsyncSender> batchingClient - = getSearchClientBuilder().httpClient(wrapWithAsserting(request -> { - int count = callCount.getAndIncrement(); - if (count == 0) { - return Mono.just(new MockHttpResponse(request, 207, new HttpHeaders(), - createMockResponseData(0, 503, 200, 200, 200, 200, 200, 200, 200, 200))); - } else { - return Mono - .just(new MockHttpResponse(request, 200, new HttpHeaders(), createMockResponseData(0, 200))); - } - }, false)) - .bufferedSender(HOTEL_DOCUMENT_TYPE) - .autoFlush(false) - .documentKeyRetriever(HOTEL_ID_KEY_RETRIEVER) - .buildAsyncSender(); - - List> documents = readJsonFileToList(HOTELS_DATA_JSON); - documents.get(9).put("HotelId", "1"); - - StepVerifier.create(batchingClient.addUploadActions(documents)).verifyComplete(); - - StepVerifier.create(batchingClient.flush()).verifyComplete(); - - /* - * Two documents should be in the batch as one failed with a retryable status code and another wasn't sent as it - * used a duplicate key from the batch that was sent. - */ - assertEquals(2, batchingClient.getActions().size()); - - StepVerifier.create(batchingClient.flush()).verifyComplete(); - - /* - * One document should remain in the batch as it had the same key as another document in the batch. - */ - assertEquals(1, batchingClient.getActions().size()); - - StepVerifier.create(batchingClient.flush().then(batchingClient.close())).verifyComplete(); - - /* - * No documents should remain as no duplicate keys exists. - */ - assertEquals(0, batchingClient.getActions().size()); - } - - /** - * Tests that an operation will be dumped into a "dead letter" queue if it is retried too many times. - */ - @Test - public void batchRetriesUntilLimit() { - AtomicInteger addedCount = new AtomicInteger(); - AtomicInteger successCount = new AtomicInteger(); - AtomicInteger errorCount = new AtomicInteger(); - AtomicInteger sentCount = new AtomicInteger(); - - SearchIndexingBufferedSender> batchingClient - = getSearchClientBuilder() - .httpClient(wrapWithAsserting( - request -> Mono - .just(new MockHttpResponse(request, 207, new HttpHeaders(), createMockResponseData(0, 409))), - true)) - .bufferedSender(HOTEL_DOCUMENT_TYPE) - .documentKeyRetriever(HOTEL_ID_KEY_RETRIEVER) - .autoFlush(false) - .maxRetriesPerAction(10) - .onActionAdded(options -> addedCount.incrementAndGet()) - .onActionSucceeded(options -> successCount.incrementAndGet()) - .onActionError(options -> errorCount.incrementAndGet()) - .onActionSent(options -> sentCount.incrementAndGet()) - .buildSender(); - - batchingClient.addUploadActions(readJsonFileToList(HOTELS_DATA_JSON).subList(0, 1)); - - // Batch split until it was size of one and failed. - for (int i = 0; i < 10; i++) { - assertDoesNotThrow((Executable) batchingClient::flush); - - // Document should be added back into the batch as it is retryable. - assertEquals(1, batchingClient.getActions().size()); - } - - // Final call which will trigger the retry limit for the document but doesn't throw. - assertDoesNotThrow((Executable) batchingClient::flush); - - assertEquals(1, addedCount.get()); - // Document gets sent 10 times for the number of retries that happen. - assertEquals(11, sentCount.get()); - assertEquals(1, errorCount.get()); - assertEquals(0, successCount.get()); - - /* - * All documents failed, so we should expect zero documents are added back into the batch. - */ - assertEquals(0, batchingClient.getActions().size()); - } - - /** - * Tests that an operation will be dumped into a "dead letter" queue if it is retried too many times. - */ - @Test - public void batchRetriesUntilLimitAsync() { - AtomicInteger addedCount = new AtomicInteger(); - AtomicInteger successCount = new AtomicInteger(); - AtomicInteger errorCount = new AtomicInteger(); - AtomicInteger sentCount = new AtomicInteger(); - - SearchIndexingBufferedAsyncSender> batchingClient = getSearchClientBuilder() - .httpClient(wrapWithAsserting( - request -> Mono - .just(new MockHttpResponse(request, 207, new HttpHeaders(), createMockResponseData(0, 409))), - false)) - .bufferedSender(HOTEL_DOCUMENT_TYPE) - .documentKeyRetriever(HOTEL_ID_KEY_RETRIEVER) - .autoFlush(false) - .maxRetriesPerAction(10) - .onActionAdded(options -> addedCount.incrementAndGet()) - .onActionSucceeded(options -> successCount.incrementAndGet()) - .onActionError(options -> errorCount.incrementAndGet()) - .onActionSent(options -> sentCount.incrementAndGet()) - .buildAsyncSender(); - - StepVerifier.create(batchingClient.addUploadActions(readJsonFileToList(HOTELS_DATA_JSON).subList(0, 1))) - .verifyComplete(); - - // Batch split until it was size of one and failed. - for (int i = 0; i < 10; i++) { - StepVerifier.create(batchingClient.flush()).verifyComplete(); - - // Document should be added back into the batch as it is retryable. - assertEquals(1, batchingClient.getActions().size()); - } - - // Final call which will trigger the retry limit for the document but doesn't throw. - StepVerifier.create(batchingClient.flush()).verifyComplete(); - - assertEquals(1, addedCount.get()); - // Document gets sent 10 times for the number of retries that happen. - assertEquals(11, sentCount.get()); - assertEquals(1, errorCount.get()); - assertEquals(0, successCount.get()); - - /* - * All documents failed, so we should expect zero documents are added back into the batch. - */ - assertEquals(0, batchingClient.getActions().size()); - } - - /** - * Tests that a batch will split until it is a size of one if the service continues returning 413. When the service - * returns 413 on a batch size of one it will be deemed a final error state. - */ - @Test - public void batchSplitsUntilOneAndFails() { - AtomicInteger addedCount = new AtomicInteger(); - AtomicInteger successCount = new AtomicInteger(); - AtomicInteger errorCount = new AtomicInteger(); - AtomicInteger sentCount = new AtomicInteger(); - - SearchIndexingBufferedSender> batchingClient = getSearchClientBuilder() - .httpClient(wrapWithAsserting(request -> Mono.just(new MockHttpResponse(request, 413)), true)) - .bufferedSender(HOTEL_DOCUMENT_TYPE) - .documentKeyRetriever(HOTEL_ID_KEY_RETRIEVER) - .autoFlush(false) - .initialBatchActionCount(2) - .onActionAdded(options -> addedCount.incrementAndGet()) - .onActionSucceeded(options -> successCount.incrementAndGet()) - .onActionError(options -> errorCount.incrementAndGet()) - .onActionSent(options -> sentCount.incrementAndGet()) - .buildSender(); - - batchingClient.addUploadActions(readJsonFileToList(HOTELS_DATA_JSON).subList(0, 2)); - - // Batch split until it was size of one and fails but doesn't throw. - assertDoesNotThrow((Executable) batchingClient::flush); - - assertEquals(2, addedCount.get()); - assertEquals(2, errorCount.get()); - assertEquals(0, successCount.get()); - assertEquals(4, sentCount.get()); - - /* - * No documents failed, so we should expect zero documents are added back into the batch. - */ - assertEquals(0, batchingClient.getActions().size()); - } - - /** - * Tests that a batch will split until it is a size of one if the service continues returning 413. When the service - * returns 413 on a batch size of one it will be deemed a final error state. - */ - @Test - public void batchSplitsUntilOneAndFailsAsync() { - AtomicInteger addedCount = new AtomicInteger(); - AtomicInteger successCount = new AtomicInteger(); - AtomicInteger errorCount = new AtomicInteger(); - AtomicInteger sentCount = new AtomicInteger(); - - SearchIndexingBufferedAsyncSender> batchingClient = getSearchClientBuilder() - .httpClient(wrapWithAsserting(request -> Mono.just(new MockHttpResponse(request, 413)), false)) - .bufferedSender(HOTEL_DOCUMENT_TYPE) - .documentKeyRetriever(HOTEL_ID_KEY_RETRIEVER) - .autoFlush(false) - .initialBatchActionCount(2) - .onActionAdded(options -> addedCount.incrementAndGet()) - .onActionSucceeded(options -> successCount.incrementAndGet()) - .onActionError(options -> errorCount.incrementAndGet()) - .onActionSent(options -> sentCount.incrementAndGet()) - .buildAsyncSender(); - - StepVerifier.create(batchingClient.addUploadActions(readJsonFileToList(HOTELS_DATA_JSON).subList(0, 2))) - .verifyComplete(); - - // Batch split until it was size of one and fails but doesn't throw. - StepVerifier.create(batchingClient.flush()).verifyComplete(); - - assertEquals(2, addedCount.get()); - assertEquals(2, errorCount.get()); - assertEquals(0, successCount.get()); - assertEquals(4, sentCount.get()); - - /* - * No documents failed, so we should expect zero documents are added back into the batch. - */ - assertEquals(0, batchingClient.getActions().size()); - } - - /** - * Tests that a batch will split until all sub-batches are one document and some of the sub batches fail with 413 - * while others do not. - */ - @Test - public void batchSplitsUntilOneAndPartiallyFails() { - AtomicInteger callCount = new AtomicInteger(); - AtomicInteger addedCount = new AtomicInteger(); - AtomicInteger successCount = new AtomicInteger(); - AtomicInteger errorCount = new AtomicInteger(); - AtomicInteger sentCount = new AtomicInteger(); - - SearchIndexingBufferedSender> batchingClient = getSearchClientBuilder() - .httpClient(wrapWithAsserting(request -> (callCount.getAndIncrement() < 2) - ? Mono.just(new MockHttpResponse(request, 413)) - : createMockBatchSplittingResponse(request, 1, 1), true)) - .bufferedSender(HOTEL_DOCUMENT_TYPE) - .documentKeyRetriever(HOTEL_ID_KEY_RETRIEVER) - .autoFlush(false) - .initialBatchActionCount(2) - .onActionAdded(options -> addedCount.incrementAndGet()) - .onActionSucceeded(options -> successCount.incrementAndGet()) - .onActionError(options -> errorCount.incrementAndGet()) - .onActionSent(options -> sentCount.incrementAndGet()) - .buildSender(); - - batchingClient.addUploadActions(readJsonFileToList(HOTELS_DATA_JSON).subList(0, 2)); - - // Batch split until it was size of one and fails but doesn't throw. - assertDoesNotThrow((Executable) batchingClient::flush); - - assertEquals(2, addedCount.get()); - assertEquals(1, errorCount.get()); - assertEquals(1, successCount.get()); - assertEquals(4, sentCount.get()); - - /* - * No documents failed, so we should expect zero documents are added back into the batch. - */ - assertEquals(0, batchingClient.getActions().size()); - } - - /** - * Tests that a batch will split until all sub-batches are one document and some of the sub batches fail with 413 - * while others do not. - */ - @Test - public void batchSplitsUntilOneAndPartiallyFailsAsync() { - AtomicInteger callCount = new AtomicInteger(); - AtomicInteger addedCount = new AtomicInteger(); - AtomicInteger successCount = new AtomicInteger(); - AtomicInteger errorCount = new AtomicInteger(); - AtomicInteger sentCount = new AtomicInteger(); - - SearchIndexingBufferedAsyncSender> batchingClient = getSearchClientBuilder() - .httpClient(wrapWithAsserting(request -> (callCount.getAndIncrement() < 2) - ? Mono.just(new MockHttpResponse(request, 413)) - : createMockBatchSplittingResponse(request, 1, 1), false)) - .bufferedSender(HOTEL_DOCUMENT_TYPE) - .documentKeyRetriever(HOTEL_ID_KEY_RETRIEVER) - .autoFlush(false) - .initialBatchActionCount(2) - .onActionAdded(options -> addedCount.incrementAndGet()) - .onActionSucceeded(options -> successCount.incrementAndGet()) - .onActionError(options -> errorCount.incrementAndGet()) - .onActionSent(options -> sentCount.incrementAndGet()) - .buildAsyncSender(); - - StepVerifier.create(batchingClient.addUploadActions(readJsonFileToList(HOTELS_DATA_JSON).subList(0, 2))) - .verifyComplete(); - - // Batch split until it was size of one and fails but doesn't throw. - StepVerifier.create(batchingClient.flush()).verifyComplete(); - - assertEquals(2, addedCount.get()); - assertEquals(1, errorCount.get()); - assertEquals(1, successCount.get()); - assertEquals(4, sentCount.get()); - - /* - * No documents failed, so we should expect zero documents are added back into the batch. - */ - assertEquals(0, batchingClient.getActions().size()); - } - - @ParameterizedTest - @MethodSource("operationsThrowAfterClientIsClosedSupplier") - public void - operationsThrowAfterClientIsClosed(Consumer>> operation) { - SearchIndexingBufferedSender> batchingClient - = getSearchClientBuilder().httpClient(request -> Mono.just(new MockHttpResponse(request, 200))) - .bufferedSender(HOTEL_DOCUMENT_TYPE) - .documentKeyRetriever(HOTEL_ID_KEY_RETRIEVER) - .autoFlush(false) - .buildSender(); - - batchingClient.close(); - - assertThrows(IllegalStateException.class, () -> operation.accept(batchingClient)); - - } - - static Stream>>> - operationsThrowAfterClientIsClosedSupplier() { - List> simpleDocuments = Collections.singletonList(Collections.singletonMap("key", "value")); - List>> actions = simpleDocuments.stream() - .map(document -> new IndexAction>().setDocument(document) - .setActionType(IndexActionType.UPLOAD)) - .collect(Collectors.toList()); - - return Stream.of(client -> client.addActions(actions), - client -> client.addActions(actions, Duration.ofSeconds(60), Context.NONE), - - client -> client.addUploadActions(simpleDocuments), - client -> client.addUploadActions(simpleDocuments, Duration.ofSeconds(60), Context.NONE), - - client -> client.addMergeOrUploadActions(simpleDocuments), - client -> client.addMergeOrUploadActions(simpleDocuments, Duration.ofSeconds(60), Context.NONE), - - client -> client.addMergeActions(simpleDocuments), - client -> client.addMergeActions(simpleDocuments, Duration.ofSeconds(60), Context.NONE), - - client -> client.addDeleteActions(simpleDocuments), - client -> client.addDeleteActions(simpleDocuments, Duration.ofSeconds(60), Context.NONE), - - SearchIndexingBufferedSender::flush, client -> client.flush(Duration.ofSeconds(60), Context.NONE)); - } - - @ParameterizedTest - @MethodSource("operationsThrowAfterClientIsClosedAsyncSupplier") - public void operationsThrowAfterClientIsClosedAsync( - Function>, Mono> operation) { - SearchIndexingBufferedAsyncSender> batchingClient - = getSearchClientBuilder().httpClient(request -> Mono.just(new MockHttpResponse(request, 200))) - .bufferedSender(HOTEL_DOCUMENT_TYPE) - .documentKeyRetriever(HOTEL_ID_KEY_RETRIEVER) - .autoFlush(false) - .buildAsyncSender(); - - StepVerifier.create(batchingClient.close()).verifyComplete(); - - StepVerifier.create(operation.apply(batchingClient)).verifyError(IllegalStateException.class); - } - - static Stream>, Mono>> - operationsThrowAfterClientIsClosedAsyncSupplier() { - List> simpleDocuments = Collections.singletonList(Collections.singletonMap("key", "value")); - List>> actions = simpleDocuments.stream() - .map(document -> new IndexAction>().setDocument(document) - .setActionType(IndexActionType.UPLOAD)) - .collect(Collectors.toList()); - - return Stream.of(client -> client.addActions(actions), client -> client.addUploadActions(simpleDocuments), - client -> client.addMergeOrUploadActions(simpleDocuments), - client -> client.addMergeActions(simpleDocuments), client -> client.addDeleteActions(simpleDocuments), - SearchIndexingBufferedAsyncSender::flush); - } - - @Test - public void closingTwiceDoesNotThrow() { - SearchIndexingBufferedSender> batchingClient - = getSearchClientBuilder().httpClient(request -> Mono.just(new MockHttpResponse(request, 200))) - .bufferedSender(HOTEL_DOCUMENT_TYPE) - .documentKeyRetriever(HOTEL_ID_KEY_RETRIEVER) - .autoFlush(false) - .buildSender(); - - batchingClient.close(); - - assertDoesNotThrow((Executable) batchingClient::close); - } - - @Test - public void closingTwiceDoesNotThrowAsync() { - SearchIndexingBufferedAsyncSender> batchingClient - = getSearchClientBuilder().httpClient(request -> Mono.just(new MockHttpResponse(request, 200))) - .bufferedSender(HOTEL_DOCUMENT_TYPE) - .documentKeyRetriever(HOTEL_ID_KEY_RETRIEVER) - .autoFlush(false) - .buildAsyncSender(); - - StepVerifier.create(batchingClient.close()).verifyComplete(); - StepVerifier.create(batchingClient.close()).verifyComplete(); - } - - @Test - public void concurrentFlushesOnlyAllowsOneProcessor() throws InterruptedException { - AtomicInteger callCount = new AtomicInteger(); - - SearchIndexingBufferedSender> batchingClient - = getSearchClientBuilder().httpClient(wrapWithAsserting(request -> { - int count = callCount.getAndIncrement(); - if (count == 0) { - sleep(2000); - return createMockBatchSplittingResponse(request, 0, 5); - } else if (count == 1) { - return createMockBatchSplittingResponse(request, 5, 5); - } else { - return Mono.error(new IllegalStateException("Unexpected request.")); - } - }, true)) - .bufferedSender(HOTEL_DOCUMENT_TYPE) - .documentKeyRetriever(HOTEL_ID_KEY_RETRIEVER) - .autoFlush(false) - .initialBatchActionCount(5) - .buildSender(); - - CountDownLatch countDownLatch = new CountDownLatch(2); - batchingClient.addUploadActions(readJsonFileToList(HOTELS_DATA_JSON)); - - AtomicLong firstFlushCompletionTime = new AtomicLong(); - ForkJoinPool.commonPool().execute(() -> { - try { - batchingClient.flush(); - } finally { - firstFlushCompletionTime.set(System.nanoTime()); - countDownLatch.countDown(); - } - }); - - Thread.sleep(10); // Give the first operation a chance to start - - AtomicLong secondFlushCompletionTime = new AtomicLong(); - ForkJoinPool.commonPool().execute(() -> { - try { - batchingClient.flush(); - } finally { - secondFlushCompletionTime.set(System.nanoTime()); - countDownLatch.countDown(); - } - }); - - countDownLatch.await(); - assertTrue(firstFlushCompletionTime.get() > secondFlushCompletionTime.get(), - () -> "Expected first flush to complete before the second flush but was " + firstFlushCompletionTime.get() - + " and " + secondFlushCompletionTime.get() + "."); - } - - @Test - public void concurrentFlushesOnlyAllowsOneProcessorAsync() throws InterruptedException { - AtomicInteger callCount = new AtomicInteger(); - - SearchIndexingBufferedAsyncSender> batchingClient - = getSearchClientBuilder().httpClient(wrapWithAsserting(request -> { - int count = callCount.getAndIncrement(); - if (count == 0) { - return createMockBatchSplittingResponse(request, 0, 5).delayElement(Duration.ofSeconds(2)); - } else if (count == 1) { - return createMockBatchSplittingResponse(request, 5, 5); - } else { - return Mono.error(new IllegalStateException("Unexpected request.")); - } - }, false)) - .bufferedSender(HOTEL_DOCUMENT_TYPE) - .documentKeyRetriever(HOTEL_ID_KEY_RETRIEVER) - .autoFlush(false) - .initialBatchActionCount(5) - .buildAsyncSender(); - - CountDownLatch countDownLatch = new CountDownLatch(2); - batchingClient.addUploadActions(readJsonFileToList(HOTELS_DATA_JSON)).block(); - - AtomicLong firstFlushCompletionTime = new AtomicLong(); - Mono.using(() -> 1, ignored -> batchingClient.flush(), ignored -> { - firstFlushCompletionTime.set(System.nanoTime()); - countDownLatch.countDown(); - }).subscribe(); - - Thread.sleep(10); // Give the first operation a chance to start - - AtomicLong secondFlushCompletionTime = new AtomicLong(); - Mono.using(() -> 1, ignored -> batchingClient.flush(), ignored -> { - secondFlushCompletionTime.set(System.nanoTime()); - countDownLatch.countDown(); - }).subscribe(); - - countDownLatch.await(); - assertTrue(firstFlushCompletionTime.get() > secondFlushCompletionTime.get(), - () -> "Expected first flush to complete before the second flush but was " + firstFlushCompletionTime.get() - + " and " + secondFlushCompletionTime.get() + "."); - } - - //@RepeatedTest(1000) - @Test - public void closeWillWaitForAnyCurrentFlushesToCompleteBeforeRunning() throws InterruptedException { - AtomicInteger callCount = new AtomicInteger(); - - SearchIndexingBufferedSender> batchingClient - = getSearchClientBuilder().httpClient(wrapWithAsserting(request -> { - int count = callCount.getAndIncrement(); - if (count == 0) { - return createMockBatchSplittingResponse(request, 0, 5).delayElement(Duration.ofSeconds(2)); - } else if (count == 1) { - return createMockBatchSplittingResponse(request, 5, 5); - } else { - return Mono.error(new IllegalStateException("Unexpected request.")); - } - }, true)) - .bufferedSender(HOTEL_DOCUMENT_TYPE) - .documentKeyRetriever(HOTEL_ID_KEY_RETRIEVER) - .autoFlush(false) - .initialBatchActionCount(5) - .buildSender(); - - CountDownLatch countDownLatch = new CountDownLatch(2); - batchingClient.addUploadActions(readJsonFileToList(HOTELS_DATA_JSON)); - - AtomicLong firstFlushCompletionTime = new AtomicLong(); - ForkJoinPool.commonPool().execute(() -> { - try { - batchingClient.flush(); - } finally { - firstFlushCompletionTime.set(System.nanoTime()); - countDownLatch.countDown(); - } - }); - - Thread.sleep(10); // Give the first operation a chance to start. - - AtomicLong secondFlushCompletionTime = new AtomicLong(); - ForkJoinPool.commonPool().execute(() -> { - try { - batchingClient.close(); - } finally { - secondFlushCompletionTime.set(System.nanoTime()); - countDownLatch.countDown(); - } - }); - - countDownLatch.await(); - assertTrue(firstFlushCompletionTime.get() <= secondFlushCompletionTime.get()); - } - - @Test - public void closeWillWaitForAnyCurrentFlushesToCompleteBeforeRunningAsync() throws InterruptedException { - AtomicInteger callCount = new AtomicInteger(); - - SearchIndexingBufferedAsyncSender> batchingClient - = getSearchClientBuilder().httpClient(wrapWithAsserting(request -> { - int count = callCount.getAndIncrement(); - if (count == 0) { - sleep(2000); - return createMockBatchSplittingResponse(request, 0, 5); - } else if (count == 1) { - return createMockBatchSplittingResponse(request, 5, 5); - } else { - return Mono.error(new IllegalStateException("Unexpected request.")); - } - }, false)) - .bufferedSender(HOTEL_DOCUMENT_TYPE) - .documentKeyRetriever(HOTEL_ID_KEY_RETRIEVER) - .autoFlush(false) - .initialBatchActionCount(5) - .buildAsyncSender(); - - CountDownLatch countDownLatch = new CountDownLatch(2); - batchingClient.addUploadActions(readJsonFileToList(HOTELS_DATA_JSON)).block(); - - AtomicLong firstFlushCompletionTime = new AtomicLong(); - Mono.using(() -> 1, ignored -> batchingClient.flush(), ignored -> { - firstFlushCompletionTime.set(System.nanoTime()); - countDownLatch.countDown(); - }).subscribe(); - - AtomicLong secondFlushCompletionTime = new AtomicLong(); - Mono.using(() -> 1, ignored -> batchingClient.close(), ignored -> { - secondFlushCompletionTime.set(System.nanoTime()); - countDownLatch.countDown(); - }).subscribe(); - - countDownLatch.await(); - assertTrue(firstFlushCompletionTime.get() <= secondFlushCompletionTime.get(), - () -> "Expected first flush attempt to complete before second flush attempt. First flush finished at " - + firstFlushCompletionTime.get() + ", second flush finished at " + secondFlushCompletionTime.get()); - } - - @Test - public void serverBusyResponseRetries() { - AtomicInteger callCount = new AtomicInteger(); - AtomicInteger addedCount = new AtomicInteger(); - AtomicInteger successCount = new AtomicInteger(); - AtomicInteger errorCount = new AtomicInteger(); - AtomicInteger sentCount = new AtomicInteger(); - - SearchIndexingBufferedSender> batchingClient - = getSearchClientBuilder().retryPolicy(new RetryPolicy(new FixedDelay(0, Duration.ZERO))) - .httpClient(wrapWithAsserting(request -> { - int count = callCount.getAndIncrement(); - if (count < 1) { - return Mono.just(new MockHttpResponse(request, 503)); - } else { - return Mono.just(new MockHttpResponse(request, 200, new HttpHeaders(), - createMockResponseData(0, 201, 200, 201, 200, 200, 200, 201, 201, 200, 201))); - } - }, true)) - .bufferedSender(HOTEL_DOCUMENT_TYPE) - .documentKeyRetriever(HOTEL_ID_KEY_RETRIEVER) - .autoFlush(false) - .onActionAdded(options -> addedCount.incrementAndGet()) - .onActionSucceeded(options -> successCount.incrementAndGet()) - .onActionError(options -> errorCount.incrementAndGet()) - .onActionSent(options -> sentCount.incrementAndGet()) - .buildSender(); - - batchingClient.addUploadActions(readJsonFileToList(HOTELS_DATA_JSON)); - - // No exception is thrown as the batch splits and retries successfully. - assertDoesNotThrow((Executable) batchingClient::flush); - assertDoesNotThrow((Executable) batchingClient::flush); - - assertEquals(10, addedCount.get()); - assertEquals(10, successCount.get()); - assertEquals(0, errorCount.get()); - assertEquals(20, sentCount.get()); - - /* - * No documents failed, so we should expect zero documents are added back into the batch. - */ - assertEquals(0, batchingClient.getActions().size()); - } - - @Test - public void serverBusyResponseRetriesAsync() { - AtomicInteger callCount = new AtomicInteger(); - AtomicInteger addedCount = new AtomicInteger(); - AtomicInteger successCount = new AtomicInteger(); - AtomicInteger errorCount = new AtomicInteger(); - AtomicInteger sentCount = new AtomicInteger(); - - SearchIndexingBufferedAsyncSender> batchingClient - = getSearchClientBuilder().retryPolicy(new RetryPolicy(new FixedDelay(0, Duration.ZERO))) - .httpClient(wrapWithAsserting(request -> { - int count = callCount.getAndIncrement(); - if (count < 1) { - return Mono.just(new MockHttpResponse(request, 503)); - } else { - return Mono.just(new MockHttpResponse(request, 200, new HttpHeaders(), - createMockResponseData(0, 201, 200, 201, 200, 200, 200, 201, 201, 200, 201))); - } - }, false)) - .bufferedSender(HOTEL_DOCUMENT_TYPE) - .documentKeyRetriever(HOTEL_ID_KEY_RETRIEVER) - .autoFlush(false) - .onActionAdded(options -> addedCount.incrementAndGet()) - .onActionSucceeded(options -> successCount.incrementAndGet()) - .onActionError(options -> errorCount.incrementAndGet()) - .onActionSent(options -> sentCount.incrementAndGet()) - .buildAsyncSender(); - - StepVerifier.create(batchingClient.addUploadActions(readJsonFileToList(HOTELS_DATA_JSON))).verifyComplete(); - - // No exception is thrown as the batch splits and retries successfully. - StepVerifier.create(batchingClient.flush()).verifyComplete(); - StepVerifier.create(batchingClient.flush()).verifyComplete(); - - assertEquals(10, addedCount.get()); - assertEquals(10, successCount.get()); - assertEquals(0, errorCount.get()); - assertEquals(20, sentCount.get()); - - /* - * No documents failed, so we should expect zero documents are added back into the batch. - */ - assertEquals(0, batchingClient.getActions().size()); - } - - @Test - public void delayGrowsWith503Response() { - SearchIndexingBufferedSender> batchingClient - = getSearchClientBuilder().retryPolicy(new RetryPolicy(new FixedDelay(0, Duration.ZERO))) - .httpClient(wrapWithAsserting(request -> Mono.just(new MockHttpResponse(request, 503)), true)) - .bufferedSender(HOTEL_DOCUMENT_TYPE) - .documentKeyRetriever(HOTEL_ID_KEY_RETRIEVER) - .autoFlush(false) - .buildSender(); - - batchingClient.addUploadActions(readJsonFileToList(HOTELS_DATA_JSON)); - - assertDoesNotThrow((Executable) batchingClient::flush); - Duration retryDuration = batchingClient.publisher.getCurrentRetryDelay(); - assertTrue(retryDuration.compareTo(Duration.ZERO) > 0); - - assertDoesNotThrow((Executable) batchingClient::flush); - assertTrue(batchingClient.publisher.getCurrentRetryDelay().compareTo(retryDuration) > 0); - } - - @Test - public void delayGrowsWith503ResponseAsync() { - SearchIndexingBufferedAsyncSender> batchingClient - = getSearchClientBuilder().retryPolicy(new RetryPolicy(new FixedDelay(0, Duration.ZERO))) - .httpClient(wrapWithAsserting(request -> Mono.just(new MockHttpResponse(request, 503)), false)) - .bufferedSender(HOTEL_DOCUMENT_TYPE) - .documentKeyRetriever(HOTEL_ID_KEY_RETRIEVER) - .autoFlush(false) - .buildAsyncSender(); - - StepVerifier.create(batchingClient.addUploadActions(readJsonFileToList(HOTELS_DATA_JSON))).verifyComplete(); - - StepVerifier.create(batchingClient.flush()).verifyComplete(); - Duration retryDuration = batchingClient.publisher.getCurrentRetryDelay(); - assertTrue(retryDuration.compareTo(Duration.ZERO) > 0); - - StepVerifier.create(batchingClient.flush()).verifyComplete(); - assertTrue(batchingClient.publisher.getCurrentRetryDelay().compareTo(retryDuration) > 0); - } - - @Test - public void delayGrowsWith503BatchOperation() { - SearchIndexingBufferedSender> batchingClient - = getSearchClientBuilder().retryPolicy(new RetryPolicy(new FixedDelay(0, Duration.ZERO))) - .httpClient(wrapWithAsserting( - request -> Mono - .just(new MockHttpResponse(request, 207, new HttpHeaders(), createMockResponseData(0, 503))), - true)) - .bufferedSender(HOTEL_DOCUMENT_TYPE) - .documentKeyRetriever(HOTEL_ID_KEY_RETRIEVER) - .autoFlush(false) - .buildSender(); - - batchingClient.addUploadActions(readJsonFileToList(HOTELS_DATA_JSON).subList(0, 1)); - - assertDoesNotThrow((Executable) batchingClient::flush); - Duration retryDuration = batchingClient.publisher.getCurrentRetryDelay(); - assertTrue(retryDuration.compareTo(Duration.ZERO) > 0); - - assertDoesNotThrow((Executable) batchingClient::flush); - assertTrue(batchingClient.publisher.getCurrentRetryDelay().compareTo(retryDuration) > 0); - } - - @Test - public void delayGrowsWith503BatchOperationAsync() { - SearchIndexingBufferedAsyncSender> batchingClient - = getSearchClientBuilder().retryPolicy(new RetryPolicy(new FixedDelay(0, Duration.ZERO))) - .httpClient(wrapWithAsserting( - request -> Mono - .just(new MockHttpResponse(request, 207, new HttpHeaders(), createMockResponseData(0, 503))), - false)) - .bufferedSender(HOTEL_DOCUMENT_TYPE) - .documentKeyRetriever(HOTEL_ID_KEY_RETRIEVER) - .autoFlush(false) - .buildAsyncSender(); - - StepVerifier.create(batchingClient.addUploadActions(readJsonFileToList(HOTELS_DATA_JSON).subList(0, 1))) - .verifyComplete(); - - StepVerifier.create(batchingClient.flush()).verifyComplete(); - Duration retryDuration = batchingClient.publisher.getCurrentRetryDelay(); - assertTrue(retryDuration.compareTo(Duration.ZERO) > 0); - - StepVerifier.create(batchingClient.flush()).verifyComplete(); - assertTrue(batchingClient.publisher.getCurrentRetryDelay().compareTo(retryDuration) > 0); - } - - @Test - public void delayResetsAfterNo503s() { - AtomicInteger callCount = new AtomicInteger(); - SearchIndexingBufferedSender> batchingClient - = getSearchClientBuilder().retryPolicy(new RetryPolicy(new FixedDelay(0, Duration.ZERO))) - .httpClient(wrapWithAsserting(request -> { - int count = callCount.getAndIncrement(); - if (count == 0) { - return Mono.just(new MockHttpResponse(request, 503)); - } else { - return Mono.just( - new MockHttpResponse(request, 200, new HttpHeaders(), createMockResponseData(0, 200))); - } - }, true)) - .bufferedSender(HOTEL_DOCUMENT_TYPE) - .documentKeyRetriever(HOTEL_ID_KEY_RETRIEVER) - .autoFlush(false) - .buildSender(); - - batchingClient.addUploadActions(readJsonFileToList(HOTELS_DATA_JSON).subList(0, 1)); - - assertDoesNotThrow((Executable) batchingClient::flush); - Duration retryDuration = batchingClient.publisher.getCurrentRetryDelay(); - assertTrue(retryDuration.compareTo(Duration.ZERO) > 0); - - assertDoesNotThrow((Executable) batchingClient::flush); - assertEquals(Duration.ZERO, batchingClient.publisher.getCurrentRetryDelay()); - } - - @Test - public void delayResetsAfterNo503sAsync() { - AtomicInteger callCount = new AtomicInteger(); - SearchIndexingBufferedAsyncSender> batchingClient - = getSearchClientBuilder().retryPolicy(new RetryPolicy(new FixedDelay(0, Duration.ZERO))) - .httpClient(wrapWithAsserting(request -> { - int count = callCount.getAndIncrement(); - if (count == 0) { - return Mono.just(new MockHttpResponse(request, 503)); - } else { - return Mono.just( - new MockHttpResponse(request, 200, new HttpHeaders(), createMockResponseData(0, 200))); - } - }, false)) - .bufferedSender(HOTEL_DOCUMENT_TYPE) - .documentKeyRetriever(HOTEL_ID_KEY_RETRIEVER) - .autoFlush(false) - .buildAsyncSender(); - - StepVerifier.create(batchingClient.addUploadActions(readJsonFileToList(HOTELS_DATA_JSON).subList(0, 1))) - .verifyComplete(); - - StepVerifier.create(batchingClient.flush()).verifyComplete(); - Duration retryDuration = batchingClient.publisher.getCurrentRetryDelay(); - assertTrue(retryDuration.compareTo(Duration.ZERO) > 0); - - StepVerifier.create(batchingClient.flush()).verifyComplete(); - assertEquals(Duration.ZERO, batchingClient.publisher.getCurrentRetryDelay()); - } - - /** - * Tests that an empty batch doesn't attempt to index. - */ - @Test - public void emptyBatchIsNeverSent() { - AtomicInteger requestCount = new AtomicInteger(); - SearchIndexingBufferedSender> batchingClient - = getSearchClientBuilder().httpClient(request -> Mono.just(new MockHttpResponse(request, 200))) - .addPolicy((context, next) -> { - requestCount.incrementAndGet(); - return next.process(); - }) - .bufferedSender(HOTEL_DOCUMENT_TYPE) - .documentKeyRetriever(HOTEL_ID_KEY_RETRIEVER) - .buildSender(); - - batchingClient.flush(); - - // flushInternal should never be called if the batch doesn't have any documents. - assertEquals(0, requestCount.get()); - batchingClient.close(); - } - - /** - * Tests that an empty batch doesn't attempt to index. - */ - @Test - public void emptyBatchIsNeverSentAsync() { - AtomicInteger requestCount = new AtomicInteger(); - SearchIndexingBufferedAsyncSender> batchingClient - = getSearchClientBuilder().httpClient(request -> Mono.just(new MockHttpResponse(request, 200))) - .addPolicy((context, next) -> { - requestCount.incrementAndGet(); - return next.process(); - }) - .bufferedSender(HOTEL_DOCUMENT_TYPE) - .documentKeyRetriever(HOTEL_ID_KEY_RETRIEVER) - .buildAsyncSender(); - - StepVerifier.create(batchingClient.flush()).verifyComplete(); - - // flushInternal should never be called if the batch doesn't have any documents. - assertEquals(0, requestCount.get()); - - StepVerifier.create(batchingClient.close()).verifyComplete(); - } - - /* - * Helper method that creates mock results with the status codes given. This will create a mock indexing result - * and turn it into a byte[] so it can be put in a mock response. - */ - private static byte[] createMockResponseData(int keyIdOffset, int... statusCodes) { - ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); - try (JsonWriter writer = JsonProviders.createWriter(outputStream)) { - writer.writeStartObject(); - writer.writeStartArray("value"); - - for (int i = 0; i < statusCodes.length; i++) { - int statusCode = statusCodes[i]; - - writer.writeStartObject() - .writeStringField("key", String.valueOf(keyIdOffset + i + 1)) - .writeBooleanField("status", statusCode == 200 || statusCode == 201) - .writeIntField("statusCode", statusCode) - .writeEndObject(); - } - - writer.writeEndArray().writeEndObject().flush(); - - return outputStream.toByteArray(); - } catch (IOException ex) { - throw new UncheckedIOException(ex); - } - } - - private static Mono createMockBatchSplittingResponse(HttpRequest request, int keyIdOffset, - int expectedBatchSize) { - return FluxUtil.collectBytesInByteBufferStream(request.getBody()).flatMap(bodyBytes -> { - // Request documents are in a sub-node called value. - try (JsonReader reader = JsonProviders.createReader(bodyBytes)) { - IndexBatch indexBatch = IndexBatch.fromJson(reader); - - // Given the initial size was 10 and it was split we should expect 5 elements. - assertNotNull(indexBatch); - assertEquals(expectedBatchSize, indexBatch.getActions().size()); - - int[] statusCodes = new int[expectedBatchSize]; - Arrays.fill(statusCodes, 200); - - return Mono.just(new MockHttpResponse(request, 200, new HttpHeaders(), - createMockResponseData(keyIdOffset, statusCodes))); - } catch (IOException ex) { - return Mono.error(ex); - } - }); - } - - private static void sleep(long millis) { - try { - Thread.sleep(millis); - } catch (InterruptedException ex) { - throw new RuntimeException(ex); - } - } -} diff --git a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/SearchServiceSubClientTests.java b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/SearchServiceSubClientTests.java deleted file mode 100644 index 6363cdfeea33..000000000000 --- a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/SearchServiceSubClientTests.java +++ /dev/null @@ -1,112 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -package com.azure.search.documents; - -import com.azure.core.credential.AzureKeyCredential; -import com.azure.core.http.HttpPipeline; -import com.azure.core.http.policy.FixedDelay; -import com.azure.core.http.policy.RetryPolicy; -import com.azure.core.test.http.MockHttpResponse; -import com.azure.search.documents.indexes.IndexesTestHelpers; -import com.azure.search.documents.indexes.SearchIndexAsyncClient; -import com.azure.search.documents.indexes.SearchIndexClient; -import com.azure.search.documents.indexes.SearchIndexClientBuilder; -import org.junit.jupiter.api.Test; -import reactor.core.publisher.Mono; -import reactor.test.StepVerifier; - -import java.time.Duration; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertThrows; - -public class SearchServiceSubClientTests extends SearchTestBase { - - @Test - public void canGetIndexClientFromSearchClient() { - SearchIndexClient serviceClient = getSearchIndexClient(); - - SearchClient searchClient = serviceClient.getSearchClient("hotels"); - - // Validate the client was created - assertNotNull(searchClient); - - // Validate the client points to the same instance - assertEquals(serviceClient.getEndpoint(), searchClient.getEndpoint()); - - // Validate that the client uses the same HTTP pipeline for authentication, retries, etc - HttpPipeline servicePipeline = IndexesTestHelpers.getHttpPipeline(serviceClient); - HttpPipeline searchPipeline = TestHelpers.getHttpPipeline(searchClient); - - assertEquals(servicePipeline, searchPipeline); - - // Validate that the client uses the specified index - assertEquals("hotels", searchClient.getIndexName()); - } - - @Test - public void canGetIndexAsyncClientFromSearchClient() { - SearchIndexAsyncClient indexAsyncClient = getSearchIndexAsyncClient(); - - SearchAsyncClient searchAsyncClient = indexAsyncClient.getSearchAsyncClient("hotels"); - - // Validate the client was created - assertNotNull(searchAsyncClient); - - // Validate the client points to the same instance - assertEquals(indexAsyncClient.getEndpoint(), searchAsyncClient.getEndpoint()); - - // Validate that the client uses the same HTTP pipeline for authentication, retries, etc - HttpPipeline servicePipeline = IndexesTestHelpers.getHttpPipeline(indexAsyncClient); - HttpPipeline searchPipeline = TestHelpers.getHttpPipeline(searchAsyncClient); - - assertEquals(servicePipeline, searchPipeline); - - // Validate that the client uses the specified index - assertEquals("hotels", searchAsyncClient.getIndexName()); - } - - @Test - public void canGetIndexClientAfterUsingServiceClient() { - // This will fail and be retried as the index doesn't exist so use a short retry policy. - SearchIndexClient serviceClient - = getSearchIndexClient(new RetryPolicy(new FixedDelay(3, Duration.ofMillis(10)))); - - assertThrows(Exception.class, () -> serviceClient.deleteIndex("thisindexdoesnotexist")); - - // This should not fail - SearchClient indexClient = serviceClient.getSearchClient("hotels"); - assertEquals("hotels", indexClient.getIndexName()); - } - - @Test - public void canGetIndexAsyncClientAfterUsingServiceClient() { - SearchIndexAsyncClient serviceClient = getSearchIndexAsyncClient(); - - StepVerifier.create(serviceClient.deleteIndex("thisindexdoesnotexist")).verifyError(); - - // This should not fail - SearchAsyncClient indexClient = serviceClient.getSearchAsyncClient("hotels"); - assertEquals("hotels", indexClient.getIndexName()); - } - - private SearchIndexClient getSearchIndexClient() { - return getSearchIndexClient(null); - } - - private SearchIndexClient getSearchIndexClient(RetryPolicy retryPolicy) { - return new SearchIndexClientBuilder().httpClient(request -> Mono.just(new MockHttpResponse(request, 200))) - .endpoint("https://test1.search.windows.net") - .credential(new AzureKeyCredential("api-key")) - .retryPolicy(retryPolicy) - .buildClient(); - } - - private SearchIndexAsyncClient getSearchIndexAsyncClient() { - return new SearchIndexClientBuilder().httpClient(request -> Mono.just(new MockHttpResponse(request, 200))) - .endpoint("https://test1.search.windows.net") - .credential(new AzureKeyCredential("api-key")) - .buildAsyncClient(); - } -} diff --git a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/SearchTestBase.java b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/SearchTestBase.java deleted file mode 100644 index 21df278225c8..000000000000 --- a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/SearchTestBase.java +++ /dev/null @@ -1,476 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.search.documents; - -import com.azure.core.client.traits.HttpTrait; -import com.azure.core.credential.TokenCredential; -import com.azure.core.http.HttpClient; -import com.azure.core.http.policy.FixedDelay; -import com.azure.core.http.policy.HttpPipelinePolicy; -import com.azure.core.http.policy.RetryPolicy; -import com.azure.core.test.InterceptorManager; -import com.azure.core.test.TestMode; -import com.azure.core.test.TestProxyTestBase; -import com.azure.core.test.http.AssertingHttpClientBuilder; -import com.azure.core.test.utils.MockTokenCredential; -import com.azure.core.util.Configuration; -import com.azure.core.util.logging.ClientLogger; -import com.azure.identity.AzurePowerShellCredentialBuilder; -import com.azure.identity.DefaultAzureCredentialBuilder; -import com.azure.json.JsonProviders; -import com.azure.json.JsonReader; -import com.azure.search.documents.indexes.SearchIndexClientBuilder; -import com.azure.search.documents.indexes.SearchIndexerClientBuilder; -import com.azure.search.documents.indexes.SearchIndexerDataSources; -import com.azure.search.documents.indexes.models.CorsOptions; -import com.azure.search.documents.indexes.models.DataChangeDetectionPolicy; -import com.azure.search.documents.indexes.models.DataDeletionDetectionPolicy; -import com.azure.search.documents.indexes.models.DistanceScoringFunction; -import com.azure.search.documents.indexes.models.DistanceScoringParameters; -import com.azure.search.documents.indexes.models.FreshnessScoringFunction; -import com.azure.search.documents.indexes.models.FreshnessScoringParameters; -import com.azure.search.documents.indexes.models.LexicalAnalyzerName; -import com.azure.search.documents.indexes.models.MagnitudeScoringFunction; -import com.azure.search.documents.indexes.models.MagnitudeScoringParameters; -import com.azure.search.documents.indexes.models.ScoringFunctionAggregation; -import com.azure.search.documents.indexes.models.ScoringFunctionInterpolation; -import com.azure.search.documents.indexes.models.ScoringProfile; -import com.azure.search.documents.indexes.models.SearchField; -import com.azure.search.documents.indexes.models.SearchFieldDataType; -import com.azure.search.documents.indexes.models.SearchIndex; -import com.azure.search.documents.indexes.models.SearchIndexerDataSourceConnection; -import com.azure.search.documents.indexes.models.SearchSuggester; -import com.azure.search.documents.indexes.models.SoftDeleteColumnDeletionDetectionPolicy; -import com.azure.search.documents.indexes.models.TagScoringFunction; -import com.azure.search.documents.indexes.models.TagScoringParameters; -import com.azure.search.documents.indexes.models.TextWeights; - -import java.io.IOException; -import java.io.UncheckedIOException; -import java.text.DateFormat; -import java.text.ParseException; -import java.text.SimpleDateFormat; -import java.time.Duration; -import java.util.Arrays; -import java.util.Collections; -import java.util.Date; -import java.util.HashMap; -import java.util.Locale; -import java.util.Map; -import java.util.TimeZone; -import java.util.function.BiConsumer; - -import static com.azure.search.documents.TestHelpers.BLOB_DATASOURCE_NAME; -import static com.azure.search.documents.TestHelpers.HOTEL_INDEX_NAME; -import static com.azure.search.documents.TestHelpers.ISO8601_FORMAT; -import static com.azure.search.documents.TestHelpers.SQL_DATASOURCE_NAME; -import static com.azure.search.documents.indexes.DataSourceTests.FAKE_AZURE_SQL_CONNECTION_STRING; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; - -/** - * Abstract base class for all Search API tests - */ -public abstract class SearchTestBase extends TestProxyTestBase { - protected static final String HOTELS_TESTS_INDEX_DATA_JSON = "HotelsTestsIndexData.json"; - private boolean sanitizersRemoved = false; - - protected static final String ENDPOINT - = Configuration.getGlobalConfiguration().get("SEARCH_SERVICE_ENDPOINT", "https://playback.search.windows.net"); - - protected static final String STORAGE_CONNECTION_STRING - = Configuration.getGlobalConfiguration().get("SEARCH_STORAGE_CONNECTION_STRING", "connectionString"); - protected static final String BLOB_CONTAINER_NAME = "searchcontainer"; - - protected static final TestMode TEST_MODE = initializeTestMode(); - - private static final String FAKE_DESCRIPTION = "Some data source"; - - static final String HOTELS_DATA_JSON = "HotelsDataArray.json"; - - // This has to be used in all test modes as this is more retry counts than the standard policy. - // Change the delay based on the mode. - static final RetryPolicy SERVICE_THROTTLE_SAFE_RETRY_POLICY = new RetryPolicy( - new FixedDelay(4, TEST_MODE == TestMode.PLAYBACK ? Duration.ofMillis(1) : Duration.ofSeconds(30))); - - protected String createHotelIndex() { - return setupIndexFromJsonFile(HOTELS_TESTS_INDEX_DATA_JSON); - } - - protected InterceptorManager getInterceptorManager() { - return interceptorManager; - } - - protected String setupIndexFromJsonFile(String jsonFile) { - try (JsonReader jsonReader = JsonProviders.createReader(TestHelpers.loadResource(jsonFile))) { - SearchIndex baseIndex = SearchIndex.fromJson(jsonReader); - String testIndexName = testResourceNamer.randomName(baseIndex.getName(), 64); - - return setupIndex(TestHelpers.createTestIndex(testIndexName, baseIndex)); - } catch (IOException ex) { - throw new UncheckedIOException(ex); - } - } - - protected String setupIndex(SearchIndex index) { - getSearchIndexClientBuilder(true).buildClient().createOrUpdateIndex(index); - - return index.getName(); - } - - protected SearchIndexClientBuilder getSearchIndexClientBuilder(boolean isSync) { - SearchIndexClientBuilder builder = new SearchIndexClientBuilder().endpoint(ENDPOINT) - .credential(getTestTokenCredential(interceptorManager)) - .httpClient(getHttpClient(true, interceptorManager, isSync)) - .retryPolicy(SERVICE_THROTTLE_SAFE_RETRY_POLICY); - - // Disable `("$..token")` and `name` sanitizer - if (!interceptorManager.isLiveMode() && !sanitizersRemoved) { - interceptorManager.removeSanitizers("AZSDK3431", "AZSDK3493", "AZSDK3430"); - sanitizersRemoved = true; - } - - if (interceptorManager.isPlaybackMode()) { - addPolicies(builder); - return builder; - } - - if (interceptorManager.isRecordMode()) { - builder.addPolicy(interceptorManager.getRecordPolicy()); - } - - return builder; - - } - - protected SearchIndexerClientBuilder getSearchIndexerClientBuilder(boolean isSync, HttpPipelinePolicy... policies) { - SearchIndexerClientBuilder builder = new SearchIndexerClientBuilder().endpoint(ENDPOINT) - .credential(getTestTokenCredential(interceptorManager)) - .httpClient(getHttpClient(true, interceptorManager, isSync)) - .retryPolicy(SERVICE_THROTTLE_SAFE_RETRY_POLICY); - - addPolicies(builder, policies); - // Disable `("$..token")` and `name` sanitizer - if (!interceptorManager.isLiveMode() && !sanitizersRemoved) { - interceptorManager.removeSanitizers("AZSDK3431", "AZSDK3493", "AZSDK3430"); - sanitizersRemoved = true; - } - - if (interceptorManager.isPlaybackMode()) { - return builder; - } - - if (interceptorManager.isRecordMode()) { - builder.addPolicy(interceptorManager.getRecordPolicy()); - } - - return builder; - - } - - private static void addPolicies(HttpTrait builder, HttpPipelinePolicy... policies) { - if (policies == null) { - return; - } - - for (HttpPipelinePolicy policy : policies) { - builder.addPolicy(policy); - } - } - - protected SearchClientBuilder getSearchClientBuilder(String indexName, boolean isSync) { - return getSearchClientBuilderHelper(indexName, true, isSync); - - } - - protected SearchClientBuilder getSearchClientBuilderWithoutAssertingClient(String indexName, boolean isSync) { - return getSearchClientBuilderHelper(indexName, false, isSync); - } - - /** - * Retrieve the appropriate TokenCredential based on the test mode. - * - * @param interceptorManager the interceptor manager - * @return The appropriate token credential - */ - public static TokenCredential getTestTokenCredential(InterceptorManager interceptorManager) { - if (interceptorManager.isLiveMode()) { - return new AzurePowerShellCredentialBuilder().build(); - } else if (interceptorManager.isRecordMode()) { - return new DefaultAzureCredentialBuilder().build(); - } else { - return new MockTokenCredential(); - } - } - - private SearchClientBuilder getSearchClientBuilderHelper(String indexName, boolean wrapWithAssertingClient, - boolean isSync) { - SearchClientBuilder builder = new SearchClientBuilder().endpoint(ENDPOINT) - .indexName(indexName) - .credential(getTestTokenCredential(interceptorManager)) - .httpClient(getHttpClient(wrapWithAssertingClient, interceptorManager, isSync)) - .retryPolicy(SERVICE_THROTTLE_SAFE_RETRY_POLICY); - - // Disable `("$..token")` and `name` sanitizer - if (!interceptorManager.isLiveMode() && !sanitizersRemoved) { - interceptorManager.removeSanitizers("AZSDK3431", "AZSDK3493", "AZSDK3430"); - sanitizersRemoved = true; - } - - if (interceptorManager.isPlaybackMode()) { - return builder; - } - - if (interceptorManager.isRecordMode()) { - builder.addPolicy(interceptorManager.getRecordPolicy()); - } - - return builder; - } - - private static HttpClient getHttpClient(boolean wrapWithAssertingClient, InterceptorManager interceptorManager, - boolean isSync) { - HttpClient httpClient - = interceptorManager.isPlaybackMode() ? interceptorManager.getPlaybackClient() : HttpClient.createDefault(); - - if (wrapWithAssertingClient) { - if (!isSync) { - httpClient = new AssertingHttpClientBuilder(httpClient).assertAsync() - .skipRequest((ignored1, ignored2) -> false) - .build(); - } else { - httpClient = new AssertingHttpClientBuilder(httpClient).assertSync() - .skipRequest((ignored1, ignored2) -> false) - .build(); - } - } - return httpClient; - } - - protected SearchIndex createTestIndex(String indexName) { - Map weights = new HashMap<>(); - weights.put("Description", 1.5); - weights.put("Category", 2.0); - String searchIndexName = indexName == null ? randomIndexName(HOTEL_INDEX_NAME) : indexName; - return new SearchIndex(searchIndexName, - Arrays.asList( - new SearchField("HotelId", SearchFieldDataType.STRING).setKey(Boolean.TRUE) - .setFilterable(Boolean.TRUE) - .setSortable(Boolean.TRUE) - .setFacetable(Boolean.TRUE) - .setHidden(Boolean.FALSE), - new SearchField("HotelName", SearchFieldDataType.STRING).setSearchable(Boolean.TRUE) - .setFilterable(Boolean.TRUE) - .setSortable(Boolean.TRUE) - .setHidden(Boolean.FALSE), - new SearchField("Description", SearchFieldDataType.STRING).setSearchable(Boolean.TRUE) - .setAnalyzerName(LexicalAnalyzerName.EN_LUCENE) - .setHidden(Boolean.FALSE), - new SearchField("DescriptionFr", SearchFieldDataType.STRING).setSearchable(Boolean.TRUE) - .setAnalyzerName(LexicalAnalyzerName.FR_LUCENE) - .setHidden(Boolean.FALSE), - new SearchField("Description_Custom", SearchFieldDataType.STRING).setSearchable(Boolean.TRUE) - .setSearchAnalyzerName(LexicalAnalyzerName.STOP) - .setIndexAnalyzerName(LexicalAnalyzerName.STOP) - .setHidden(Boolean.FALSE), - new SearchField("Category", SearchFieldDataType.STRING).setSearchable(Boolean.TRUE) - .setFilterable(Boolean.TRUE) - .setSortable(Boolean.TRUE) - .setFacetable(Boolean.TRUE) - .setHidden(Boolean.FALSE), - new SearchField("Tags", SearchFieldDataType.collection(SearchFieldDataType.STRING)) - .setSearchable(Boolean.TRUE) - .setFilterable(Boolean.TRUE) - .setFacetable(Boolean.TRUE) - .setHidden(Boolean.FALSE), - new SearchField("ParkingIncluded", SearchFieldDataType.BOOLEAN).setFilterable(Boolean.TRUE) - .setSortable(Boolean.TRUE) - .setFacetable(Boolean.TRUE) - .setHidden(Boolean.FALSE), - new SearchField("SmokingAllowed", SearchFieldDataType.BOOLEAN).setFilterable(Boolean.TRUE) - .setSortable(Boolean.TRUE) - .setFacetable(Boolean.TRUE) - .setHidden(Boolean.FALSE), - new SearchField("LastRenovationDate", SearchFieldDataType.DATE_TIME_OFFSET).setFilterable(Boolean.TRUE) - .setSortable(Boolean.TRUE) - .setFacetable(Boolean.TRUE) - .setHidden(Boolean.FALSE), - new SearchField("Rating", SearchFieldDataType.INT32).setFilterable(Boolean.TRUE) - .setSortable(Boolean.TRUE) - .setFacetable(Boolean.TRUE) - .setHidden(Boolean.FALSE), - new SearchField("Address", SearchFieldDataType.COMPLEX).setFields( - new SearchField("StreetAddress", SearchFieldDataType.STRING).setSearchable(Boolean.TRUE) - .setHidden(Boolean.FALSE), - new SearchField("City", SearchFieldDataType.STRING).setSearchable(Boolean.TRUE) - .setFilterable(Boolean.TRUE) - .setSortable(Boolean.TRUE) - .setFacetable(Boolean.TRUE) - .setHidden(Boolean.FALSE), - new SearchField("StateProvince", SearchFieldDataType.STRING).setSearchable(Boolean.TRUE) - .setFilterable(Boolean.TRUE) - .setSortable(Boolean.TRUE) - .setFacetable(Boolean.TRUE) - .setHidden(Boolean.FALSE), - new SearchField("Country", SearchFieldDataType.STRING).setSearchable(Boolean.TRUE) - .setFilterable(Boolean.TRUE) - .setSortable(Boolean.TRUE) - .setFacetable(Boolean.TRUE) - .setHidden(Boolean.FALSE), - new SearchField("PostalCode", SearchFieldDataType.STRING).setSearchable(Boolean.TRUE) - .setFilterable(Boolean.TRUE) - .setSortable(Boolean.TRUE) - .setFacetable(Boolean.TRUE) - .setHidden(Boolean.FALSE)), - new SearchField("Location", SearchFieldDataType.GEOGRAPHY_POINT).setFilterable(Boolean.TRUE) - .setSortable(Boolean.TRUE) - .setHidden(Boolean.FALSE), - new SearchField("Rooms", SearchFieldDataType.collection(SearchFieldDataType.COMPLEX)).setFields( - new SearchField("Description", SearchFieldDataType.STRING).setSearchable(Boolean.TRUE) - .setAnalyzerName(LexicalAnalyzerName.EN_LUCENE), - new SearchField("DescriptionFr", SearchFieldDataType.STRING).setSearchable(Boolean.TRUE) - .setAnalyzerName(LexicalAnalyzerName.FR_LUCENE) - .setHidden(Boolean.FALSE), - new SearchField("Type", SearchFieldDataType.STRING).setSearchable(Boolean.TRUE) - .setFilterable(Boolean.TRUE) - .setFacetable(Boolean.TRUE) - .setHidden(Boolean.FALSE), - new SearchField("BaseRate", SearchFieldDataType.DOUBLE).setKey(Boolean.FALSE) - .setFilterable(Boolean.TRUE) - .setFacetable(Boolean.TRUE) - .setHidden(Boolean.FALSE), - new SearchField("BedOptions", SearchFieldDataType.STRING).setSearchable(Boolean.TRUE) - .setFilterable(Boolean.TRUE) - .setFacetable(Boolean.TRUE) - .setHidden(Boolean.FALSE), - new SearchField("SleepsCount", SearchFieldDataType.INT32).setFilterable(Boolean.TRUE) - .setFacetable(Boolean.TRUE) - .setHidden(Boolean.FALSE), - new SearchField("SmokingAllowed", SearchFieldDataType.BOOLEAN).setFilterable(Boolean.TRUE) - .setFacetable(Boolean.TRUE) - .setHidden(Boolean.FALSE), - new SearchField("Tags", SearchFieldDataType.collection(SearchFieldDataType.STRING)) - .setSearchable(Boolean.TRUE) - .setFilterable(Boolean.TRUE) - .setFacetable(Boolean.TRUE) - .setHidden(Boolean.FALSE)), - new SearchField("TotalGuests", SearchFieldDataType.INT64).setFilterable(Boolean.TRUE) - .setSortable(Boolean.TRUE) - .setFacetable(Boolean.TRUE), - new SearchField("ProfitMargin", SearchFieldDataType.DOUBLE))) - .setScoringProfiles( - new ScoringProfile("MyProfile").setFunctionAggregation(ScoringFunctionAggregation.AVERAGE) - .setFunctions(new MagnitudeScoringFunction("Rating", 2.0, - new MagnitudeScoringParameters(1, 4).setShouldBoostBeyondRangeByConstant(true)) - .setInterpolation(ScoringFunctionInterpolation.CONSTANT), - new DistanceScoringFunction("Location", 1.5, new DistanceScoringParameters("Loc", 5)) - .setInterpolation(ScoringFunctionInterpolation.LINEAR), - new FreshnessScoringFunction("LastRenovationDate", 1.1, - new FreshnessScoringParameters(Duration.ofDays(365))) - .setInterpolation(ScoringFunctionInterpolation.LOGARITHMIC)) - .setTextWeights(new TextWeights(weights)), - new ScoringProfile("ProfileTwo").setFunctionAggregation(ScoringFunctionAggregation.MAXIMUM) - .setFunctions(new TagScoringFunction("Tags", 1.5, new TagScoringParameters("MyTags")) - .setInterpolation(ScoringFunctionInterpolation.LINEAR)), - new ScoringProfile("ProfileThree").setFunctionAggregation(ScoringFunctionAggregation.MINIMUM) - .setFunctions(new MagnitudeScoringFunction("Rating", 3.0, - new MagnitudeScoringParameters(0, 10).setShouldBoostBeyondRangeByConstant(false)) - .setInterpolation(ScoringFunctionInterpolation.QUADRATIC)), - new ScoringProfile("ProfileFour") - .setFunctionAggregation(ScoringFunctionAggregation.FIRST_MATCHING) - .setFunctions(new MagnitudeScoringFunction("Rating", 3.25, - new MagnitudeScoringParameters(1, 5).setShouldBoostBeyondRangeByConstant(false)) - .setInterpolation(ScoringFunctionInterpolation.CONSTANT))) - .setDefaultScoringProfile("MyProfile") - .setCorsOptions(new CorsOptions(Arrays.asList("http://tempuri.org", "http://localhost:80")) - .setMaxAgeInSeconds(60L)) - .setSuggesters(new SearchSuggester("FancySuggester", Collections.singletonList("HotelName"))); - } - - protected SearchIndexerDataSourceConnection createTestSqlDataSourceObject() { - return createTestSqlDataSourceObject(null, null, null); - } - - protected SearchIndexerDataSourceConnection createTestSqlDataSourceObject( - DataDeletionDetectionPolicy dataDeletionDetectionPolicy, DataChangeDetectionPolicy dataChangeDetectionPolicy) { - return createTestSqlDataSourceObject(testResourceNamer.randomName(SQL_DATASOURCE_NAME, 32), - dataDeletionDetectionPolicy, dataChangeDetectionPolicy); - } - - protected SearchIndexerDataSourceConnection createTestSqlDataSourceObject(String name, - DataDeletionDetectionPolicy dataDeletionDetectionPolicy, DataChangeDetectionPolicy dataChangeDetectionPolicy) { - if (name == null) { - name = testResourceNamer.randomName(SQL_DATASOURCE_NAME, 32); - } - - return SearchIndexerDataSources.createFromAzureSql(name, FAKE_AZURE_SQL_CONNECTION_STRING, "GeoNamesRI", - FAKE_DESCRIPTION, dataChangeDetectionPolicy, dataDeletionDetectionPolicy); - } - - protected SearchIndexerDataSourceConnection createBlobDataSource() { - // create the new data source object for this storage account and container - return SearchIndexerDataSources.createFromAzureBlobStorage( - testResourceNamer.randomName(BLOB_DATASOURCE_NAME, 32), STORAGE_CONNECTION_STRING, BLOB_CONTAINER_NAME, "/", - "real live blob", new SoftDeleteColumnDeletionDetectionPolicy().setSoftDeleteColumnName("fieldName") - .setSoftDeleteMarkerValue("someValue")); - } - - protected String randomIndexName(String indexNameBase) { - return testResourceNamer.randomName(indexNameBase, 64); - } - - private static TestMode initializeTestMode() { - ClientLogger logger = new ClientLogger(SearchTestBase.class); - String azureTestMode = Configuration.getGlobalConfiguration().get("AZURE_TEST_MODE"); - if (azureTestMode != null) { - try { - return TestMode.valueOf(azureTestMode.toUpperCase(Locale.US)); - } catch (IllegalArgumentException var3) { - logger.error("Could not parse '{}' into TestEnum. Using 'Playback' mode.", azureTestMode); - return TestMode.PLAYBACK; - } - } else { - logger.info("Environment variable '{}' has not been set yet. Using 'Playback' mode.", "AZURE_TEST_MODE"); - return TestMode.PLAYBACK; - } - } - - protected void validateETagUpdate(String original, String updated) { - assertNotNull(original); - assertNotNull(updated); - assertNotEquals(original, updated); - } - - protected void compareMaps(Map expectedMap, Map actualMap, - BiConsumer comparisonFunction) { - compareMaps(expectedMap, actualMap, comparisonFunction, true); - } - - protected void compareMaps(Map expectedMap, Map actualMap, - BiConsumer comparisonFunction, boolean checkSize) { - if (checkSize) { - assertEquals(expectedMap.size(), actualMap.size()); - } - - actualMap.forEach((key, actual) -> { - T expected = expectedMap.get(key); - assertNotNull(expected, "Actual map contained an entry that doesn't exist in the expected map: " + key); - - comparisonFunction.accept(expected, actual); - }); - } - - @SuppressWarnings({ "UseOfObsoleteDateTimeApi" }) - protected static Date parseDate(String dateString) { - DateFormat dateFormat = new SimpleDateFormat(ISO8601_FORMAT); - dateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); - - try { - return dateFormat.parse(dateString); - } catch (ParseException ex) { - throw new RuntimeException(ex); - } - } -} diff --git a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/SearchTests.java b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/SearchTests.java deleted file mode 100644 index b8ac7e8ef2fd..000000000000 --- a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/SearchTests.java +++ /dev/null @@ -1,1519 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.search.documents; - -import com.azure.core.exception.HttpResponseException; -import com.azure.core.models.GeoPoint; -import com.azure.core.test.TestProxyTestBase; -import com.azure.core.test.TestMode; -import com.azure.core.test.annotation.LiveOnly; -import com.azure.core.util.Context; -import com.azure.search.documents.implementation.util.SearchPagedResponseAccessHelper; -import com.azure.search.documents.indexes.SearchIndexClient; -import com.azure.search.documents.indexes.models.SearchField; -import com.azure.search.documents.indexes.models.SearchFieldDataType; -import com.azure.search.documents.indexes.models.SearchIndex; -import com.azure.search.documents.indexes.models.SynonymMap; -import com.azure.search.documents.models.FacetResult; -import com.azure.search.documents.models.QueryType; -import com.azure.search.documents.models.RangeFacetResult; -import com.azure.search.documents.models.ScoringParameter; -import com.azure.search.documents.models.SearchMode; -import com.azure.search.documents.models.SearchOptions; -import com.azure.search.documents.models.SearchResult; -import com.azure.search.documents.models.ValueFacetResult; -import com.azure.search.documents.test.environment.models.Bucket; -import com.azure.search.documents.test.environment.models.Hotel; -import com.azure.search.documents.test.environment.models.NonNullableModel; -import com.azure.search.documents.util.SearchPagedFlux; -import com.azure.search.documents.util.SearchPagedIterable; -import com.azure.search.documents.util.SearchPagedResponse; -import org.junit.jupiter.api.AfterAll; -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.Test; -import reactor.core.publisher.Mono; -import reactor.test.StepVerifier; - -import java.net.HttpURLConnection; -import java.time.Instant; -import java.time.OffsetDateTime; -import java.time.format.DateTimeFormatter; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.Date; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.NoSuchElementException; -import java.util.Set; -import java.util.concurrent.atomic.AtomicInteger; -import java.util.function.Function; -import java.util.stream.Collectors; -import java.util.stream.Stream; - -import static com.azure.search.documents.TestHelpers.assertMapEquals; -import static com.azure.search.documents.TestHelpers.assertObjectEquals; -import static com.azure.search.documents.TestHelpers.convertMapToValue; -import static com.azure.search.documents.TestHelpers.readJsonFileToList; -import static com.azure.search.documents.TestHelpers.setupSharedIndex; -import static com.azure.search.documents.TestHelpers.uploadDocuments; -import static org.junit.jupiter.api.Assertions.assertArrayEquals; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertInstanceOf; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertNull; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.junit.jupiter.api.Assertions.assertTrue; - -public class SearchTests extends SearchTestBase { - private final List indexesToDelete = new ArrayList<>(); - - private static final String HOTEL_INDEX_NAME = "azsearch-search-shared-hotel-instance"; - private static final String LARGE_INDEX_NAME = "azsearch-search-shared-large-instance"; - private static final String SYNONYM_INDEX_NAME = "azsearch-search-shared-synonym-instance"; - private static final String SYNONYM_NAME = "azsearch-search-shared-synonym-instance"; - - private static SearchIndexClient searchIndexClient; - - @BeforeAll - public static void setupClass() { - TestProxyTestBase.setupClass(); - - if (TEST_MODE == TestMode.PLAYBACK) { - return; - } - - searchIndexClient = setupSharedIndex(HOTEL_INDEX_NAME, HOTELS_TESTS_INDEX_DATA_JSON, HOTELS_DATA_JSON); - setupSharedIndex(SYNONYM_INDEX_NAME, HOTELS_TESTS_INDEX_DATA_JSON, HOTELS_DATA_JSON); - setupSharedIndex(LARGE_INDEX_NAME, HOTELS_TESTS_INDEX_DATA_JSON, null); - - uploadDocuments(searchIndexClient.getSearchClient(LARGE_INDEX_NAME), createHotelsList()); - - searchIndexClient.createSynonymMap(new SynonymMap(SYNONYM_NAME).setSynonyms("luxury,fancy")); - - // Attach index field to SynonymMap - SearchIndex hotelsIndex = searchIndexClient.getIndex(SYNONYM_INDEX_NAME); - hotelsIndex.getFields() - .stream() - .filter(f -> "HotelName".equals(f.getName())) - .findFirst() - .orElseThrow(NoSuchElementException::new) - .setSynonymMapNames(SYNONYM_NAME); - searchIndexClient.createOrUpdateIndex(hotelsIndex); - } - - @Override - protected void afterTest() { - super.afterTest(); - - SearchIndexClient serviceClient = getSearchIndexClientBuilder(true).buildClient(); - for (String index : indexesToDelete) { - serviceClient.deleteIndex(index); - } - } - - @AfterAll - protected static void cleanupClass() { - if (TEST_MODE != TestMode.PLAYBACK) { - searchIndexClient.deleteIndex(HOTEL_INDEX_NAME); - searchIndexClient.deleteIndex(LARGE_INDEX_NAME); - searchIndexClient.deleteIndex(SYNONYM_INDEX_NAME); - searchIndexClient.deleteSynonymMap(SYNONYM_NAME); - - // Sleep to ensure the synonym map delete finishes. - try { - Thread.sleep(5000); - } catch (InterruptedException ex) { - throw new RuntimeException(ex); - } - } - } - - private SearchClient getClient(String indexName) { - return getSearchClientBuilder(indexName, true).buildClient(); - } - - private SearchAsyncClient getAsyncClient(String indexName) { - return getSearchClientBuilder(indexName, false).buildAsyncClient(); - } - - @Test - public void searchThrowsWhenRequestIsMalformedSync() { - badSearchSync("*", new SearchOptions().setFilter("This is not a valid filter.")); - } - - @Test - public void searchThrowsWhenRequestIsMalformedAsync() { - badSearchAsync("*", new SearchOptions().setFilter("This is not a valid filter.")); - } - - @Test - public void searchThrowsWhenSpecialCharInRegexIsUnescapedSync() { - badSearchSync("/.*/.*/", new SearchOptions().setQueryType(QueryType.FULL)); - } - - @Test - public void searchThrowsWhenSpecialCharInRegexIsUnescapedAsync() { - badSearchAsync("/.*/.*/", new SearchOptions().setQueryType(QueryType.FULL)); - } - - private void badSearchSync(String searchText, SearchOptions searchOptions) { - HttpResponseException ex = assertThrows(HttpResponseException.class, - () -> getSearchClientBuilder(HOTEL_INDEX_NAME, true).buildClient() - .search(searchText, searchOptions, Context.NONE) - .iterableByPage() - .iterator() - .next()); - - assertEquals(HttpURLConnection.HTTP_BAD_REQUEST, ex.getResponse().getStatusCode()); - } - - private void badSearchAsync(String searchText, SearchOptions searchOptions) { - StepVerifier.create(getSearchClientBuilder(HOTEL_INDEX_NAME, false).buildAsyncClient() - .search(searchText, searchOptions) - .byPage()).thenRequest(1).verifyErrorSatisfies(throwable -> { - HttpResponseException ex = assertInstanceOf(HttpResponseException.class, throwable); - assertEquals(HttpURLConnection.HTTP_BAD_REQUEST, ex.getResponse().getStatusCode()); - }); - } - - @Test - public void canSearchDynamicDocumentsSync() { - SearchClient client = getClient(HOTEL_INDEX_NAME); - - List> hotels = readJsonFileToList(HOTELS_DATA_JSON); - Map> expectedHotels - = hotels.stream().collect(Collectors.toMap(h -> h.get("HotelId").toString(), Function.identity())); - - for (SearchPagedResponse response : client.search("*").iterableByPage()) { - assertNull(SearchPagedResponseAccessHelper.getCount(response)); - assertNull(SearchPagedResponseAccessHelper.getCoverage(response)); - assertNull(SearchPagedResponseAccessHelper.getFacets(response)); - - response.getElements().forEach(item -> { - assertEquals(1, item.getScore(), 0); - assertNull(item.getHighlights()); - - SearchDocument actual = item.getDocument(SearchDocument.class); - Map expected = expectedHotels.remove(actual.get("HotelId").toString()); - - assertNotNull(expected); - assertMapEquals(expected, actual, true, "properties"); - }); - } - - assertEquals(0, expectedHotels.size()); - } - - @Test - public void canSearchDynamicDocumentsAsync() { - SearchAsyncClient asyncClient = getAsyncClient(HOTEL_INDEX_NAME); - - List> hotels = readJsonFileToList(HOTELS_DATA_JSON); - Map> expectedHotels - = hotels.stream().collect(Collectors.toMap(h -> h.get("HotelId").toString(), Function.identity())); - - StepVerifier.create(asyncClient.search("*").byPage()).thenConsumeWhile(response -> { - assertNull(SearchPagedResponseAccessHelper.getCount(response)); - assertNull(SearchPagedResponseAccessHelper.getCoverage(response)); - assertNull(SearchPagedResponseAccessHelper.getFacets(response)); - - response.getElements().forEach(item -> { - assertEquals(1, item.getScore(), 0); - assertNull(item.getHighlights()); - - SearchDocument actual = item.getDocument(SearchDocument.class); - Map expected = expectedHotels.remove(actual.get("HotelId").toString()); - - assertNotNull(expected); - assertMapEquals(expected, actual, true, "properties"); - }); - - return true; - }).verifyComplete(); - - assertEquals(0, expectedHotels.size()); - } - - @Test - public void canContinueSearchSync() { - SearchClient client = getClient(LARGE_INDEX_NAME); - - // upload large documents batch - List> hotels = createHotelsList(); - - SearchOptions searchOptions = new SearchOptions().setSelect("HotelId").setOrderBy("HotelId asc"); - - List expectedHotelIds - = hotels.stream().map(hotel -> (String) hotel.get("HotelId")).sorted().collect(Collectors.toList()); - - SearchPagedIterable results = client.search("*", searchOptions, Context.NONE); - - // By default, if top isn't specified in the SearchOptions each page will contain 50 results. - AtomicInteger total = new AtomicInteger(); - results.iterableByPage().forEach(page -> { - assertEquals(50, page.getValue().size()); - assertListEqualHotelIds(expectedHotelIds.subList(total.get(), total.addAndGet(50)), page.getValue()); - if (total.get() != 3000) { - assertNotNull(page.getContinuationToken()); - } else { - assertNull(page.getContinuationToken()); - } - }); - } - - @Test - public void canContinueSearchAsync() { - SearchAsyncClient asyncClient = getAsyncClient(LARGE_INDEX_NAME); - - // upload large documents batch - List> hotels = createHotelsList(); - - SearchOptions searchOptions = new SearchOptions().setSelect("HotelId").setOrderBy("HotelId asc"); - - List expectedHotelIds - = hotels.stream().map(hotel -> (String) hotel.get("HotelId")).sorted().collect(Collectors.toList()); - - // By default, if top isn't specified in the SearchOptions each page will contain 50 results. - StepVerifier.create(asyncClient.search("*", searchOptions).byPage().collectList()).assertNext(pages -> { - AtomicInteger total = new AtomicInteger(); - pages.forEach(page -> { - assertEquals(50, page.getValue().size()); - assertListEqualHotelIds(expectedHotelIds.subList(total.get(), total.addAndGet(50)), page.getValue()); - if (total.get() != 3000) { - assertNotNull(page.getContinuationToken()); - } else { - assertNull(page.getContinuationToken()); - } - }); - }).verifyComplete(); - } - - @Test - public void canContinueSearchWithTopSync() { - SearchClient client = getClient(LARGE_INDEX_NAME); - - // upload large documents batch - List> hotels = createHotelsList(); - - SearchOptions searchOptions = new SearchOptions().setTop(2000).setSelect("HotelId").setOrderBy("HotelId asc"); - - List expectedHotelIds - = hotels.stream().map(hotel -> (String) hotel.get("HotelId")).sorted().collect(Collectors.toList()); - - SearchPagedIterable results = client.search("*", searchOptions, Context.NONE); - - assertNotNull(results); - - Iterator iterator = results.iterableByPage().iterator(); - - try (SearchPagedResponse firstPage = iterator.next()) { - assertEquals(1000, firstPage.getValue().size()); - assertListEqualHotelIds(expectedHotelIds.subList(0, 1000), firstPage.getValue()); - assertNotNull(firstPage.getContinuationToken()); - } - - try (SearchPagedResponse secondPage = iterator.next()) { - assertEquals(1000, secondPage.getValue().size()); - assertListEqualHotelIds(expectedHotelIds.subList(1000, 2000), secondPage.getValue()); - assertNull(secondPage.getContinuationToken()); - } - } - - @Test - public void canContinueSearchWithTopAsync() { - SearchAsyncClient asyncClient = getAsyncClient(LARGE_INDEX_NAME); - - // upload large documents batch - List> hotels = createHotelsList(); - - SearchOptions searchOptions = new SearchOptions().setTop(2000).setSelect("HotelId").setOrderBy("HotelId asc"); - - List expectedHotelIds - = hotels.stream().map(hotel -> (String) hotel.get("HotelId")).sorted().collect(Collectors.toList()); - - StepVerifier.create(asyncClient.search("*", searchOptions).byPage()).assertNext(response -> { - assertEquals(1000, response.getValue().size()); - assertListEqualHotelIds(expectedHotelIds.subList(0, 1000), response.getValue()); - assertNotNull(response.getContinuationToken()); - }).assertNext(response -> { - assertEquals(1000, response.getValue().size()); - assertListEqualHotelIds(expectedHotelIds.subList(1000, 2000), response.getValue()); - assertNull(response.getContinuationToken()); - }).verifyComplete(); - } - - @Test - public void canSearchStaticallyTypedDocumentsSync() { - SearchClient client = getClient(HOTEL_INDEX_NAME); - - List> hotels = readJsonFileToList(HOTELS_DATA_JSON); - Map expectedHotels = hotels.stream() - .map(hotel -> convertMapToValue(hotel, Hotel.class)) - .collect(Collectors.toMap(Hotel::hotelId, Function.identity())); - - for (SearchPagedResponse response : client.search("*", new SearchOptions(), Context.NONE).iterableByPage()) { - assertNull(SearchPagedResponseAccessHelper.getCount(response)); - assertNull(SearchPagedResponseAccessHelper.getCoverage(response)); - assertNull(SearchPagedResponseAccessHelper.getFacets(response)); - - response.getElements().forEach(sr -> { - assertEquals(1, sr.getScore(), 0); - assertNull(sr.getHighlights()); - Hotel actual = sr.getDocument(Hotel.class); - - Hotel expected = expectedHotels.remove(actual.hotelId()); - assertNotNull(expected); - assertObjectEquals(expected, actual, true, "properties"); - }); - } - - assertEquals(0, expectedHotels.size()); - } - - @Test - public void canSearchStaticallyTypedDocumentsAsync() { - SearchAsyncClient asyncClient = getAsyncClient(HOTEL_INDEX_NAME); - - List> hotels = readJsonFileToList(HOTELS_DATA_JSON); - Map expectedHotels = hotels.stream() - .map(hotel -> convertMapToValue(hotel, Hotel.class)) - .collect(Collectors.toMap(Hotel::hotelId, Function.identity())); - - StepVerifier.create(asyncClient.search("*", new SearchOptions()).byPage()).thenConsumeWhile(response -> { - assertNull(SearchPagedResponseAccessHelper.getCount(response)); - assertNull(SearchPagedResponseAccessHelper.getCoverage(response)); - assertNull(SearchPagedResponseAccessHelper.getFacets(response)); - - response.getElements().forEach(sr -> { - assertEquals(1, sr.getScore(), 0); - assertNull(sr.getHighlights()); - Hotel actual = sr.getDocument(Hotel.class); - - Hotel expected = expectedHotels.remove(actual.hotelId()); - assertNotNull(expected); - assertObjectEquals(expected, actual, true, "properties"); - }); - - return true; - }).verifyComplete(); - - assertEquals(0, expectedHotels.size()); - } - - @SuppressWarnings("UseOfObsoleteDateTimeApi") - @Test - public void canRoundTripNonNullableValueTypesSyncAndAsync() { - String indexName = createIndexWithNonNullableTypes(); - indexesToDelete.add(indexName); - SearchClient client = getSearchClientBuilder(indexName, true).buildClient(); - - Date startEpoch = Date.from(Instant.ofEpochMilli(1275346800000L)); - NonNullableModel doc1 = new NonNullableModel().key("123") - .count(3) - .isEnabled(true) - .rating(5) - .ratio(3.25) - .startDate(new Date(startEpoch.getTime())) - .endDate(new Date(startEpoch.getTime())) - .topLevelBucket(new Bucket().bucketName("A").count(12)) - .buckets(new Bucket[] { new Bucket().bucketName("B").count(20), new Bucket().bucketName("C").count(7) }); - - NonNullableModel doc2 = new NonNullableModel().key("456").buckets(new Bucket[] { }); - - Map expectedDocs = new HashMap<>(); - expectedDocs.put(doc1.key(), doc1); - expectedDocs.put(doc2.key(), doc2); - - uploadDocuments(client, Arrays.asList(doc1, doc2)); - - SearchPagedIterable results = client.search("*", new SearchOptions(), Context.NONE); - Iterator iterator = results.iterableByPage().iterator(); - - SearchPagedResponse result = iterator.next(); - Map actualDocs = result.getValue() - .stream() - .map(sr -> sr.getDocument(NonNullableModel.class)) - .collect(Collectors.toMap(NonNullableModel::key, Function.identity())); - - compareMaps(expectedDocs, actualDocs, (expected, actual) -> assertObjectEquals(expected, actual, true)); - - SearchAsyncClient asyncClient = getSearchClientBuilder(indexName, false).buildAsyncClient(); - NonNullableModel doc1Async = new NonNullableModel().key("123async") - .count(3) - .isEnabled(true) - .rating(5) - .ratio(3.25) - .startDate(new Date(startEpoch.getTime())) - .endDate(new Date(startEpoch.getTime())) - .topLevelBucket(new Bucket().bucketName("A").count(12)) - .buckets(new Bucket[] { new Bucket().bucketName("B").count(20), new Bucket().bucketName("C").count(7) }); - - NonNullableModel doc2Async = new NonNullableModel().key("456async").buckets(new Bucket[] { }); - - Map expectedDocsAsync = new HashMap<>(); - expectedDocsAsync.put(doc1Async.key(), doc1Async); - expectedDocsAsync.put(doc2Async.key(), doc2Async); - - uploadDocuments(asyncClient, Arrays.asList(doc1Async, doc2Async)); - - StepVerifier.create(asyncClient.search("*", new SearchOptions()).byPage()).assertNext(response -> { - Map actualDocsAsync = response.getValue() - .stream() - .map(sr -> sr.getDocument(NonNullableModel.class)) - .filter(model -> model.key().endsWith("async")) - .collect(Collectors.toMap(NonNullableModel::key, Function.identity())); - - compareMaps(expectedDocsAsync, actualDocsAsync, - (expected, actual) -> assertObjectEquals(expected, actual, true)); - }).verifyComplete(); - } - - @SuppressWarnings("UseOfObsoleteDateTimeApi") - @Test - public void canSearchWithDateInStaticModelSync() { - SearchClient client = getClient(HOTEL_INDEX_NAME); - - OffsetDateTime expected = OffsetDateTime.parse("2010-06-27T00:00:00Z"); - - SearchPagedIterable results = client.search("Fancy", new SearchOptions(), Context.NONE); - Iterator iterator = results.iterableByPage().iterator(); - - try (SearchPagedResponse result = iterator.next()) { - assertEquals(1, result.getValue().size()); - Date actual = result.getValue().get(0).getDocument(Hotel.class).lastRenovationDate(); - long epochMilli = expected.toInstant().toEpochMilli(); - assertEquals(new Date(epochMilli), actual); - } - } - - @SuppressWarnings("UseOfObsoleteDateTimeApi") - @Test - public void canSearchWithDateInStaticModelAsync() { - SearchAsyncClient asyncClient = getAsyncClient(HOTEL_INDEX_NAME); - - OffsetDateTime expected = OffsetDateTime.parse("2010-06-27T00:00:00Z"); - - StepVerifier.create(asyncClient.search("Fancy", new SearchOptions()).byPage()).assertNext(response -> { - assertEquals(1, response.getValue().size()); - Date actual = response.getValue().get(0).getDocument(Hotel.class).lastRenovationDate(); - long epochMilli = expected.toInstant().toEpochMilli(); - assertEquals(new Date(epochMilli), actual); - }).verifyComplete(); - } - - @Test - public void canSearchWithSelectedFieldsSync() { - SearchClient client = getClient(HOTEL_INDEX_NAME); - - // Ask JUST for the following two fields - SearchOptions sp = new SearchOptions(); - sp.setSearchFields("HotelName", "Category"); - sp.setSelect("HotelName", "Rating", "Address/City", "Rooms/Type"); - - SearchPagedIterable results = client.search("fancy luxury secret", sp, Context.NONE); - - HashMap expectedHotel1 = new HashMap<>(); - expectedHotel1.put("HotelName", "Fancy Stay"); - expectedHotel1.put("Rating", 5); - expectedHotel1.put("Address", null); - expectedHotel1.put("Rooms", Collections.emptyList()); - - // This is the expected document when querying the document later (notice that only two fields are expected) - HashMap expectedHotel2 = new HashMap<>(); - expectedHotel2.put("HotelName", "Secret Point Motel"); - expectedHotel2.put("Rating", 4); - HashMap address = new HashMap<>(); - address.put("City", "New York"); - expectedHotel2.put("Address", address); - HashMap rooms = new HashMap<>(); - rooms.put("Type", "Budget Room"); - HashMap rooms2 = new HashMap<>(); - rooms2.put("Type", "Budget Room"); - expectedHotel2.put("Rooms", Arrays.asList(rooms, rooms2)); - - Iterator iterator = results.iterableByPage().iterator(); - try (SearchPagedResponse result = iterator.next()) { - assertEquals(2, result.getValue().size()); - - // From the result object, extract the two hotels, clean up (irrelevant fields) and change data structure - // as a preparation to check equality - Map hotel1 = extractAndTransformSingleResult(result.getValue().get(0)); - Map hotel2 = extractAndTransformSingleResult(result.getValue().get(1)); - - assertMapEquals(expectedHotel1, hotel1, true); - assertMapEquals(expectedHotel2, hotel2, true); - } - } - - @Test - public void canSearchWithSelectedFieldsAsync() { - SearchAsyncClient asyncClient = getAsyncClient(HOTEL_INDEX_NAME); - - // Ask JUST for the following two fields - SearchOptions sp = new SearchOptions(); - sp.setSearchFields("HotelName", "Category"); - sp.setSelect("HotelName", "Rating", "Address/City", "Rooms/Type"); - - HashMap expectedHotel1 = new HashMap<>(); - expectedHotel1.put("HotelName", "Fancy Stay"); - expectedHotel1.put("Rating", 5); - expectedHotel1.put("Address", null); - expectedHotel1.put("Rooms", Collections.emptyList()); - - // This is the expected document when querying the document later (notice that only two fields are expected) - HashMap expectedHotel2 = new HashMap<>(); - expectedHotel2.put("HotelName", "Secret Point Motel"); - expectedHotel2.put("Rating", 4); - HashMap address = new HashMap<>(); - address.put("City", "New York"); - expectedHotel2.put("Address", address); - HashMap rooms = new HashMap<>(); - rooms.put("Type", "Budget Room"); - HashMap rooms2 = new HashMap<>(); - rooms2.put("Type", "Budget Room"); - expectedHotel2.put("Rooms", Arrays.asList(rooms, rooms2)); - - StepVerifier.create(asyncClient.search("fancy luxury secret", sp).byPage()).assertNext(response -> { - assertEquals(2, response.getValue().size()); - - // From the result object, extract the two hotels, clean up (irrelevant fields) and change data structure - // as a preparation to check equality - Map hotel1 = extractAndTransformSingleResult(response.getValue().get(0)); - Map hotel2 = extractAndTransformSingleResult(response.getValue().get(1)); - - assertMapEquals(expectedHotel1, hotel1, true); - assertMapEquals(expectedHotel2, hotel2, true); - }).verifyComplete(); - } - - @Test - public void canUseTopAndSkipForClientSidePagingSync() { - SearchClient client = getClient(HOTEL_INDEX_NAME); - - SearchOptions parameters = new SearchOptions().setTop(3).setSkip(0).setOrderBy("HotelId"); - - SearchPagedIterable results = client.search("*", parameters, Context.NONE); - assertKeySequenceEqual(results, Arrays.asList("1", "10", "2")); - - parameters.setSkip(3); - results = client.search("*", parameters, Context.NONE); - assertKeySequenceEqual(results, Arrays.asList("3", "4", "5")); - } - - @Test - public void canUseTopAndSkipForClientSidePagingAsync() { - SearchAsyncClient asyncClient = getAsyncClient(HOTEL_INDEX_NAME); - - SearchOptions parameters = new SearchOptions().setTop(3).setSkip(0).setOrderBy("HotelId"); - - StepVerifier - .create(getSearchResultsAsync(asyncClient.search("*", parameters, Context.NONE)) - .map(docs -> docs.stream().map(sd -> sd.get("HotelId").toString()).collect(Collectors.toList()))) - .assertNext(actualKeys -> assertEquals(Arrays.asList("1", "10", "2"), actualKeys)) - .verifyComplete(); - - parameters.setSkip(3); - - StepVerifier - .create(getSearchResultsAsync(asyncClient.search("*", parameters, Context.NONE)) - .map(docs -> docs.stream().map(sd -> sd.get("HotelId").toString()).collect(Collectors.toList()))) - .assertNext(actualKeys -> assertEquals(Arrays.asList("3", "4", "5"), actualKeys)) - .verifyComplete(); - } - - @Test - public void searchWithoutOrderBySortsByScoreSync() { - SearchClient client = getClient(HOTEL_INDEX_NAME); - - Iterator results - = client.search("*", new SearchOptions().setFilter("Rating lt 4"), Context.NONE).iterator(); - SearchResult firstResult = results.next(); - SearchResult secondResult = results.next(); - assertTrue(firstResult.getScore() <= secondResult.getScore()); - } - - @Test - public void searchWithoutOrderBySortsByScoreAsync() { - SearchAsyncClient asyncClient = getAsyncClient(HOTEL_INDEX_NAME); - - StepVerifier.create(asyncClient.search("*", new SearchOptions().setFilter("Rating lt 4")).take(2).collectList()) - .assertNext(results -> assertTrue(results.get(0).getScore() <= results.get(1).getScore())) - .verifyComplete(); - } - - @Test - public void orderByProgressivelyBreaksTiesSync() { - SearchClient client = getClient(HOTEL_INDEX_NAME); - - String[] expectedResults = new String[] { "1", "9", "3", "4", "5", "10", "2", "6", "7", "8" }; - - Stream results - = client - .search("*", new SearchOptions().setOrderBy("Rating desc", "LastRenovationDate asc", "HotelId"), - Context.NONE) - .stream() - .map(SearchTests::getSearchResultId); - - assertArrayEquals(results.toArray(), expectedResults); - } - - @Test - public void orderByProgressivelyBreaksTiesAsync() { - SearchAsyncClient asyncClient = getAsyncClient(HOTEL_INDEX_NAME); - - String[] expectedResults = new String[] { "1", "9", "3", "4", "5", "10", "2", "6", "7", "8" }; - - StepVerifier - .create(asyncClient - .search("*", new SearchOptions().setOrderBy("Rating desc", "LastRenovationDate asc", "HotelId")) - .map(SearchTests::getSearchResultId) - .collectList()) - .assertNext(results -> assertArrayEquals(results.toArray(), expectedResults)) - .verifyComplete(); - } - - @Test - public void canFilterSync() { - SearchClient client = getClient(HOTEL_INDEX_NAME); - - SearchOptions searchOptions - = new SearchOptions().setFilter("Rating gt 3 and LastRenovationDate gt 2000-01-01T00:00:00Z") - .setOrderBy("HotelId asc"); - - SearchPagedIterable results = client.search("*", searchOptions, Context.NONE); - assertNotNull(results); - - List searchResultsList = getSearchResultsSync(results); - assertEquals(2, searchResultsList.size()); - assertEquals("1", searchResultsList.get(0).get("HotelId").toString()); - assertEquals("5", searchResultsList.get(1).get("HotelId").toString()); - } - - @Test - public void canFilterAsync() { - SearchAsyncClient asyncClient = getAsyncClient(HOTEL_INDEX_NAME); - - SearchOptions searchOptions - = new SearchOptions().setFilter("Rating gt 3 and LastRenovationDate gt 2000-01-01T00:00:00Z") - .setOrderBy("HotelId asc"); - - StepVerifier.create(getSearchResultsAsync(asyncClient.search("*", searchOptions))) - .assertNext(searchResultsList -> { - assertEquals(2, searchResultsList.size()); - assertEquals("1", searchResultsList.get(0).get("HotelId").toString()); - assertEquals("5", searchResultsList.get(1).get("HotelId").toString()); - }) - .verifyComplete(); - } - - @Test - @LiveOnly - public void canSearchWithRangeFacetsSync() { - // Disable sanitizer `$.to` for this test - // interceptorManager.removeSanitizers("AZSDK3424")); - SearchClient client = getClient(HOTEL_INDEX_NAME); - - List> hotels = readJsonFileToList(HOTELS_DATA_JSON); - - for (SearchPagedResponse response : client.search("*", getSearchOptionsForRangeFacets(), Context.NONE) - .iterableByPage()) { - Map> facets = SearchPagedResponseAccessHelper.getFacets(response); - assertNotNull(facets); - - List> baseRateFacets = getRangeFacetsForField(facets, "Rooms/BaseRate", 4); - List> lastRenovationDateFacets - = getRangeFacetsForField(facets, "LastRenovationDate", 2); - assertRangeFacets(baseRateFacets, lastRenovationDateFacets); - - assertContainHotelIds(hotels, response.getValue()); - } - } - - @Test - @LiveOnly - public void canSearchWithRangeFacetsAsync() { - // Disable sanitizer `$.to` for this test - // interceptorManager.removeSanitizers("AZSDK3424"); - SearchAsyncClient asyncClient = getAsyncClient(HOTEL_INDEX_NAME); - - List> hotels = readJsonFileToList(HOTELS_DATA_JSON); - - StepVerifier.create(asyncClient.search("*", getSearchOptionsForRangeFacets()).byPage()) - .thenConsumeWhile(response -> { - Map> facets = SearchPagedResponseAccessHelper.getFacets(response); - assertNotNull(facets); - - List> baseRateFacets = getRangeFacetsForField(facets, "Rooms/BaseRate", 4); - List> lastRenovationDateFacets - = getRangeFacetsForField(facets, "LastRenovationDate", 2); - assertRangeFacets(baseRateFacets, lastRenovationDateFacets); - - assertContainHotelIds(hotels, response.getValue()); - - return true; - }) - .verifyComplete(); - } - - @Test - public void canSearchWithValueFacetsSync() { - SearchClient client = getClient(HOTEL_INDEX_NAME); - - List> hotels = readJsonFileToList(HOTELS_DATA_JSON); - - for (SearchPagedResponse response : client.search("*", getSearchOptionsForValueFacets(), Context.NONE) - .iterableByPage()) { - Map> facets = SearchPagedResponseAccessHelper.getFacets(response); - assertNotNull(facets); - - canSearchWithValueFacetsValidateResponse(response, hotels, facets); - } - } - - @Test - public void canSearchWithValueFacetsAsync() { - SearchAsyncClient asyncClient = getAsyncClient(HOTEL_INDEX_NAME); - - List> hotels = readJsonFileToList(HOTELS_DATA_JSON); - - StepVerifier.create(asyncClient.search("*", getSearchOptionsForValueFacets()).byPage()) - .thenConsumeWhile(response -> { - Map> facets = SearchPagedResponseAccessHelper.getFacets(response); - assertNotNull(facets); - - canSearchWithValueFacetsValidateResponse(response, hotels, facets); - - return true; - }) - .verifyComplete(); - } - - @Test - public void canSearchWithLuceneSyntaxSync() { - SearchClient client = getClient(HOTEL_INDEX_NAME); - - Map expectedResult = new HashMap<>(); - expectedResult.put("HotelName", "Roach Motel"); - expectedResult.put("Rating", 1); - - SearchOptions searchOptions = new SearchOptions().setQueryType(QueryType.FULL).setSelect("HotelName", "Rating"); - - List searchResultsList - = getSearchResultsSync(client.search("HotelName:roch~", searchOptions, Context.NONE)); - assertEquals(1, searchResultsList.size()); - assertEquals(expectedResult, searchResultsList.get(0)); - } - - @Test - public void canSearchWithLuceneSyntaxAsync() { - SearchAsyncClient asyncClient = getAsyncClient(HOTEL_INDEX_NAME); - - Map expectedResult = new HashMap<>(); - expectedResult.put("HotelName", "Roach Motel"); - expectedResult.put("Rating", 1); - - SearchOptions searchOptions = new SearchOptions().setQueryType(QueryType.FULL).setSelect("HotelName", "Rating"); - - StepVerifier.create(getSearchResultsAsync(asyncClient.search("HotelName:roch~", searchOptions))) - .assertNext(searchResultsList -> { - assertEquals(1, searchResultsList.size()); - assertEquals(expectedResult, searchResultsList.get(0)); - }) - .verifyComplete(); - } - - @Test - public void canFilterNonNullableTypeSyncAndAsync() { - SearchOptions searchOptions - = new SearchOptions().setFilter("IntValue eq 0 or (Bucket/BucketName eq 'B' and Bucket/Count lt 10)"); - - String indexName = createIndexWithValueTypes(); - indexesToDelete.add(indexName); - SearchClient client = getSearchClientBuilder(indexName, true).buildClient(); - - List docsList = createDocsListWithValueTypes(""); - uploadDocuments(client, docsList); - - Map expectedDocs = docsList.stream() - .filter(d -> !d.get("Key").equals("789")) - .collect(Collectors.toMap(sd -> sd.get("Key").toString(), Function.identity())); - - SearchPagedIterable results = client.search("*", searchOptions, Context.NONE); - assertNotNull(results); - - Map actualDocs = results.stream() - .map(sr -> sr.getDocument(SearchDocument.class)) - .collect(Collectors.toMap(sd -> sd.get("Key").toString(), Function.identity())); - - compareMaps(expectedDocs, actualDocs, (expected, actual) -> assertObjectEquals(expected, actual, true)); - - SearchAsyncClient asyncClient = getSearchClientBuilder(indexName, false).buildAsyncClient(); - List docsListAsync = createDocsListWithValueTypes("async"); - uploadDocuments(asyncClient, docsListAsync); - - Map expectedDocsAsync = docsListAsync.stream() - .filter(d -> !d.get("Key").equals("789async")) - .collect(Collectors.toMap(sd -> sd.get("Key").toString(), Function.identity())); - - StepVerifier - .create(asyncClient.search("*", searchOptions) - .map(sr -> sr.getDocument(SearchDocument.class)) - .filter(doc -> doc.get("Key").toString().endsWith("async")) - .collectMap(sd -> sd.get("Key").toString())) - .assertNext(resultsAsync -> compareMaps(expectedDocsAsync, resultsAsync, - (expected, actual) -> assertObjectEquals(expected, actual, true))) - .verifyComplete(); - } - - @Test - public void canSearchWithSearchModeAllSync() { - SearchClient client = getClient(HOTEL_INDEX_NAME); - - List response = getSearchResultsSync(client.search("Cheapest hotel", - new SearchOptions().setQueryType(QueryType.SIMPLE).setSearchMode(SearchMode.ALL), Context.NONE)); - - assertEquals(1, response.size()); - assertEquals("2", response.get(0).get("HotelId")); - } - - @Test - public void canSearchWithSearchModeAllAsync() { - SearchAsyncClient asyncClient = getAsyncClient(HOTEL_INDEX_NAME); - - StepVerifier - .create(getSearchResultsAsync(asyncClient.search("Cheapest hotel", - new SearchOptions().setQueryType(QueryType.SIMPLE).setSearchMode(SearchMode.ALL)))) - .assertNext(response -> { - assertEquals(1, response.size()); - assertEquals("2", response.get(0).get("HotelId")); - }) - .verifyComplete(); - } - - @Test - public void defaultSearchModeIsAnySync() { - SearchClient client = getClient(HOTEL_INDEX_NAME); - - List response = getSearchResultsSync( - client.search("Cheapest hotel", new SearchOptions().setOrderBy("HotelId"), Context.NONE)); - assertEquals(7, response.size()); - assertEquals(Arrays.asList("1", "10", "2", "3", "4", "5", "9"), - response.stream().map(res -> res.get("HotelId").toString()).collect(Collectors.toList())); - } - - @Test - public void defaultSearchModeIsAnyAsync() { - SearchAsyncClient asyncClient = getAsyncClient(HOTEL_INDEX_NAME); - - StepVerifier - .create( - getSearchResultsAsync(asyncClient.search("Cheapest hotel", new SearchOptions().setOrderBy("HotelId")))) - .assertNext(response -> { - assertEquals(7, response.size()); - assertEquals(Arrays.asList("1", "10", "2", "3", "4", "5", "9"), - response.stream().map(res -> res.get("HotelId").toString()).collect(Collectors.toList())); - }) - .verifyComplete(); - } - - @Test - public void canGetResultCountInSearchSync() { - SearchClient client = getClient(HOTEL_INDEX_NAME); - List> hotels = readJsonFileToList(HOTELS_DATA_JSON); - - SearchPagedIterable results = client.search("*", new SearchOptions().setIncludeTotalCount(true), Context.NONE); - assertNotNull(results); - assertEquals(hotels.size(), results.getTotalCount().intValue()); - - Iterator iterator = results.iterableByPage().iterator(); - - assertNotNull(iterator.next()); - assertFalse(iterator.hasNext()); - } - - @Test - public void canGetResultCountInSearchAsync() { - SearchAsyncClient asyncClient = getAsyncClient(HOTEL_INDEX_NAME); - List> hotels = readJsonFileToList(HOTELS_DATA_JSON); - - StepVerifier.create(asyncClient.search("*", new SearchOptions().setIncludeTotalCount(true)).byPage()) - .assertNext(response -> assertEquals(hotels.size(), SearchPagedResponseAccessHelper.getCount(response))) - .verifyComplete(); - } - - @Test - public void canSearchWithRegexSync() { - SearchClient client = getClient(HOTEL_INDEX_NAME); - - SearchOptions searchOptions = new SearchOptions().setQueryType(QueryType.FULL).setSelect("HotelName", "Rating"); - - SearchPagedIterable results = client.search("HotelName:/.*oach.*\\/?/", searchOptions, Context.NONE); - assertNotNull(results); - - List resultsList = getSearchResultsSync(results); - - SearchDocument expectedHotel = new SearchDocument(); - expectedHotel.put("HotelName", "Roach Motel"); - expectedHotel.put("Rating", 1); - - assertEquals(1, resultsList.size()); - assertEquals(resultsList.get(0), expectedHotel); - } - - @Test - public void canSearchWithRegexAsync() { - SearchAsyncClient asyncClient = getAsyncClient(HOTEL_INDEX_NAME); - - SearchOptions searchOptions = new SearchOptions().setQueryType(QueryType.FULL).setSelect("HotelName", "Rating"); - - StepVerifier.create(getSearchResultsAsync(asyncClient.search("HotelName:/.*oach.*\\/?/", searchOptions))) - .assertNext(resultsList -> { - Map expectedHotel = new HashMap<>(); - expectedHotel.put("HotelName", "Roach Motel"); - expectedHotel.put("Rating", 1); - - assertEquals(1, resultsList.size()); - assertEquals(resultsList.get(0), expectedHotel); - }) - .verifyComplete(); - } - - @Test - public void canSearchWithEscapedSpecialCharsInRegexSync() { - SearchClient client = getClient(HOTEL_INDEX_NAME); - - SearchOptions searchOptions = new SearchOptions().setQueryType(QueryType.FULL); - - SearchPagedIterable results - = client.search("\\+\\-\\&\\|\\!\\(\\)\\{\\}\\[\\]\\^\\~\\*\\?\\:", searchOptions, Context.NONE); - assertNotNull(results); - - List resultsList = getSearchResultsSync(results); - assertEquals(0, resultsList.size()); - } - - @Test - public void canSearchWithEscapedSpecialCharsInRegexAsync() { - SearchAsyncClient asyncClient = getAsyncClient(HOTEL_INDEX_NAME); - - SearchOptions searchOptions = new SearchOptions().setQueryType(QueryType.FULL); - - StepVerifier - .create(getSearchResultsAsync( - asyncClient.search("\\+\\-\\&\\|\\!\\(\\)\\{\\}\\[\\]\\^\\~\\*\\?\\:", searchOptions))) - .assertNext(response -> assertEquals(0, response.size())) - .verifyComplete(); - } - - @Test - public void searchWithScoringProfileBoostsScoreSync() { - SearchClient client = getClient(HOTEL_INDEX_NAME); - - SearchOptions searchOptions = new SearchOptions().setScoringProfile("nearest") - .setScoringParameters(new ScoringParameter("myloc", new GeoPoint(-122.0, 49.0))) - .setFilter("Rating eq 5 or Rating eq 1") - .setOrderBy("HotelId desc"); - - List response = getSearchResultsSync(client.search("hotel", searchOptions, Context.NONE)); - assertEquals(2, response.size()); - assertEquals("2", response.get(0).get("HotelId").toString()); - assertEquals("1", response.get(1).get("HotelId").toString()); - } - - @Test - public void searchWithScoringProfileBoostsScoreAsync() { - SearchAsyncClient asyncClient = getAsyncClient(HOTEL_INDEX_NAME); - - SearchOptions searchOptions = new SearchOptions().setScoringProfile("nearest") - .setScoringParameters(new ScoringParameter("myloc", new GeoPoint(-122.0, 49.0))) - .setFilter("Rating eq 5 or Rating eq 1") - .setOrderBy("HotelId desc"); - - StepVerifier.create(getSearchResultsAsync(asyncClient.search("hotel", searchOptions))).assertNext(response -> { - assertEquals(2, response.size()); - assertEquals("2", response.get(0).get("HotelId").toString()); - assertEquals("1", response.get(1).get("HotelId").toString()); - }).verifyComplete(); - } - - @Test - public void searchWithScoringProfileEscaperSync() { - SearchClient client = getClient(HOTEL_INDEX_NAME); - - SearchOptions searchOptions = new SearchOptions().setScoringProfile("text") - .setScoringParameters(new ScoringParameter("mytag", Arrays.asList("concierge", "Hello, O''Brien"))) - .setFilter("Rating eq 5 or Rating eq 1"); - - List response = getSearchResultsSync(client.search("hotel", searchOptions, Context.NONE)); - assertEquals(2, response.size()); - assertEquals(Arrays.asList("1", "2"), - response.stream().map(res -> res.get("HotelId").toString()).collect(Collectors.toList())); - } - - @Test - public void searchWithScoringProfileEscaperAsync() { - SearchAsyncClient asyncClient = getAsyncClient(HOTEL_INDEX_NAME); - - SearchOptions searchOptions = new SearchOptions().setScoringProfile("text") - .setScoringParameters(new ScoringParameter("mytag", Arrays.asList("concierge", "Hello, O''Brien"))) - .setFilter("Rating eq 5 or Rating eq 1"); - - StepVerifier.create(getSearchResultsAsync(asyncClient.search("hotel", searchOptions))).assertNext(response -> { - assertEquals(2, response.size()); - assertEquals(Arrays.asList("1", "2"), - response.stream().map(res -> res.get("HotelId").toString()).collect(Collectors.toList())); - }).verifyComplete(); - } - - @Test - public void searchWithScoringParametersEmptySync() { - SearchClient client = getClient(HOTEL_INDEX_NAME); - - SearchOptions searchOptions = new SearchOptions().setScoringProfile("text") - .setScoringParameters(new ScoringParameter("mytag", Arrays.asList("", "concierge"))) - .setFilter("Rating eq 5 or Rating eq 1"); - - List response = getSearchResultsSync(client.search("hotel", searchOptions, Context.NONE)); - assertEquals(2, response.size()); - assertEquals(Arrays.asList("1", "2"), - response.stream().map(res -> res.get("HotelId").toString()).collect(Collectors.toList())); - } - - @Test - public void searchWithScoringParametersEmptyAsync() { - SearchAsyncClient asyncClient = getAsyncClient(HOTEL_INDEX_NAME); - - SearchOptions searchOptions = new SearchOptions().setScoringProfile("text") - .setScoringParameters(new ScoringParameter("mytag", Arrays.asList("", "concierge"))) - .setFilter("Rating eq 5 or Rating eq 1"); - - StepVerifier.create(getSearchResultsAsync(asyncClient.search("hotel", searchOptions))).assertNext(response -> { - assertEquals(2, response.size()); - assertEquals(Arrays.asList("1", "2"), - response.stream().map(res -> res.get("HotelId").toString()).collect(Collectors.toList())); - }).verifyComplete(); - } - - @Test - public void canSearchWithMinimumCoverageSync() { - SearchClient client = getClient(HOTEL_INDEX_NAME); - - SearchPagedResponse response = client.search("*", new SearchOptions().setMinimumCoverage(50.0), Context.NONE) - .iterableByPage() - .iterator() - .next(); - - assertEquals(100.0, SearchPagedResponseAccessHelper.getCoverage(response), 0); - } - - @Test - public void canSearchWithMinimumCoverageAsync() { - SearchAsyncClient asyncClient = getAsyncClient(HOTEL_INDEX_NAME); - - StepVerifier.create(asyncClient.search("*", new SearchOptions().setMinimumCoverage(50.0)).byPage()) - .assertNext(response -> assertEquals(100.0, SearchPagedResponseAccessHelper.getCoverage(response))) - .verifyComplete(); - } - - @Test - public void canUseHitHighlightingSync() { - SearchClient client = getClient(HOTEL_INDEX_NAME); - - //arrange - String description = "Description"; - String category = "Category"; - - SearchOptions sp = new SearchOptions(); - sp.setFilter("Rating eq 5"); - sp.setHighlightPreTag(""); - sp.setHighlightPostTag(""); - sp.setHighlightFields(category, description); - - //act - try (SearchPagedResponse result - = client.search("luxury hotel", sp, Context.NONE).iterableByPage().iterator().next()) { - - List documents = result.getValue(); - assertEquals(1, documents.size()); - - Map> highlights = documents.get(0).getHighlights(); - assertEquals(2, highlights.keySet().size()); - assertTrue(highlights.containsKey(description)); - assertTrue(highlights.containsKey(category)); - - //asserts - assertEquals("Luxury", highlights.get(category).get(0)); - - List expectedDescriptionHighlights - = Arrays.asList("Best hotel in town if you like luxury hotels.", - "We highly recommend this hotel."); - - assertEquals(expectedDescriptionHighlights, highlights.get(description)); - } - } - - @Test - public void canUseHitHighlightingAsync() { - SearchAsyncClient asyncClient = getAsyncClient(HOTEL_INDEX_NAME); - - //arrange - String description = "Description"; - String category = "Category"; - - SearchOptions sp = new SearchOptions(); - sp.setFilter("Rating eq 5"); - sp.setHighlightPreTag(""); - sp.setHighlightPostTag(""); - sp.setHighlightFields(category, description); - - StepVerifier.create(asyncClient.search("luxury hotel", sp).byPage()).assertNext(result -> { - List documents = result.getValue(); - - assertEquals(1, documents.size()); - Map> highlights = documents.get(0).getHighlights(); - assertEquals(2, highlights.keySet().size()); - assertTrue(highlights.containsKey(description)); - assertTrue(highlights.containsKey(category)); - - assertEquals("Luxury", highlights.get(category).get(0)); - - List expectedDescriptionHighlights - = Arrays.asList("Best hotel in town if you like luxury hotels.", - "We highly recommend this hotel."); - - assertEquals(expectedDescriptionHighlights, highlights.get(description)); - }).verifyComplete(); - } - - @Test - public void canSearchWithSynonymsSync() { - SearchClient client = getClient(SYNONYM_INDEX_NAME); - - SearchOptions searchOptions = new SearchOptions().setQueryType(QueryType.FULL) - .setSearchFields("HotelName") - .setSelect("HotelName", "Rating"); - - SearchPagedIterable results = client.search("luxury", searchOptions, Context.NONE); - assertNotNull(results); - - List response = getSearchResultsSync(results); - assertEquals(1, response.size()); - assertEquals("Fancy Stay", response.get(0).get("HotelName")); - assertEquals(5, response.get(0).get("Rating")); - } - - @Test - public void canSearchWithSynonymsAsync() { - SearchAsyncClient asyncClient = getAsyncClient(SYNONYM_INDEX_NAME); - - SearchOptions searchOptions = new SearchOptions().setQueryType(QueryType.FULL) - .setSearchFields("HotelName") - .setSelect("HotelName", "Rating"); - - StepVerifier.create(getSearchResultsAsync(asyncClient.search("luxury", searchOptions))).assertNext(results -> { - assertEquals(1, results.size()); - assertEquals("Fancy Stay", results.get(0).get("HotelName")); - assertEquals(5, results.get(0).get("Rating")); - }).verifyComplete(); - } - - private static List getSearchResultsSync(SearchPagedIterable results) { - return results.stream().map(sr -> sr.getDocument(SearchDocument.class)).collect(Collectors.toList()); - } - - private static Mono> getSearchResultsAsync(SearchPagedFlux results) { - return results.map(sr -> sr.getDocument(SearchDocument.class)).collectList(); - } - - private static Map extractAndTransformSingleResult(SearchResult result) { - return convertHashMapToMap((result.getDocument(SearchDocument.class))); - } - - /** - * Convert a HashMap object to Map object - * - * @param mapObject object to convert - * @return {@link Map}{@code <}{@link String}{@code ,}{@link Object}{@code >} - */ - @SuppressWarnings("unchecked") - private static Map convertHashMapToMap(Object mapObject) { - // This SuppressWarnings is for the checkstyle it is used because api return type can - // be anything and therefore is an Object in our case we know and we use it only when - // the return type is LinkedHashMap. The object is converted into HashMap (which LinkedHashMap - // extends) - HashMap map = (HashMap) mapObject; - - Set> entries = map.entrySet(); - - Map convertedMap = new HashMap<>(); - - for (Map.Entry entry : entries) { - Object value = entry.getValue(); - - if (value instanceof HashMap) { - value = convertHashMapToMap(entry.getValue()); - } - if (value instanceof ArrayList) { - value = convertArray((ArrayList) value); - - } - - convertedMap.put(entry.getKey(), value); - } - - return convertedMap; - } - - /** - * Convert Array Object elements - * - * @param array which elements will be converted - * @return {@link ArrayList}{@code <}{@link Object}{@code >} - */ - private static ArrayList convertArray(ArrayList array) { - ArrayList convertedArray = new ArrayList<>(); - for (Object arrayValue : array) { - if (arrayValue instanceof HashMap) { - convertedArray.add(convertHashMapToMap(arrayValue)); - } else { - convertedArray.add(arrayValue); - } - } - return convertedArray; - } - - private static void assertKeySequenceEqual(SearchPagedIterable results, List expectedKeys) { - assertNotNull(results); - - List actualKeys = results.stream() - .map(doc -> doc.getDocument(SearchDocument.class)) - .filter(sd -> sd.containsKey("HotelId")) - .map(sd -> sd.get("HotelId").toString()) - .collect(Collectors.toList()); - - assertEquals(expectedKeys, actualKeys); - } - - static List> createHotelsList() { - List> documents = new ArrayList<>(); - for (int i = 1; i <= 3000; i++) { - Map doc = new HashMap<>(); - - doc.put("HotelId", Integer.toString(i)); - doc.put("HotelName", "Hotel" + i); - doc.put("Description", "Desc" + i); - doc.put("Description_fr", "Desc_fr" + i); - doc.put("Category", "Catg" + i); - doc.put("Tags", Collections.singletonList("tag" + i)); - doc.put("ParkingIncluded", false); - doc.put("SmokingAllowed", false); - doc.put("LastRenovationDate", OffsetDateTime.parse("2010-06-27T00:00:00Z")); - doc.put("Rating", i); - - documents.add(doc); - } - return documents; - } - - static void assertRangeFacets(List> baseRateFacets, - List> lastRenovationDateFacets) { - assertNull(baseRateFacets.get(0).getFrom()); - assertEquals(5.0, baseRateFacets.get(0).getTo()); - assertEquals(5.0, baseRateFacets.get(1).getFrom()); - assertEquals(8.0, baseRateFacets.get(1).getTo()); - assertEquals(8.0, baseRateFacets.get(2).getFrom()); - assertEquals(10.0, baseRateFacets.get(2).getTo()); - assertEquals(10.0, baseRateFacets.get(3).getFrom()); - assertNull(baseRateFacets.get(3).getTo()); - - assertEquals(1, baseRateFacets.get(0).getCount().intValue()); - assertEquals(1, baseRateFacets.get(1).getCount().intValue()); - assertEquals(1, baseRateFacets.get(2).getCount().intValue()); - assertEquals(0, baseRateFacets.get(3).getCount().intValue()); - - assertNull(lastRenovationDateFacets.get(0).getFrom()); - assertEquals("2000-01-01T00:00:00.000+0000", lastRenovationDateFacets.get(0).getTo()); - assertEquals("2000-01-01T00:00:00.000+0000", lastRenovationDateFacets.get(1).getFrom()); - assertNull(lastRenovationDateFacets.get(1).getTo()); - - assertEquals(5, lastRenovationDateFacets.get(0).getCount().intValue()); - assertEquals(2, lastRenovationDateFacets.get(1).getCount().intValue()); - } - - static List> getRangeFacetsForField(Map> facets, - String expectedField, int expectedCount) { - List facetCollection = getFacetsForField(facets, expectedField, expectedCount); - return facetCollection.stream().map(RangeFacetResult::new).collect(Collectors.toList()); - } - - static List> getValueFacetsForField(Map> facets, - String expectedField, int expectedCount) { - List facetCollection = getFacetsForField(facets, expectedField, expectedCount); - return facetCollection.stream().map(ValueFacetResult::new).collect(Collectors.toList()); - } - - private static List getFacetsForField(Map> facets, String expectedField, - int expectedCount) { - assertTrue(facets.containsKey(expectedField)); - List results = facets.get(expectedField); - assertEquals(expectedCount, results.size()); - return results; - } - - static void assertContainHotelIds(List> expected, List actual) { - assertNotNull(actual); - Set actualKeys = actual.stream() - .filter(item -> item.getDocument(SearchDocument.class).containsKey("HotelId")) - .map(item -> (String) item.getDocument(SearchDocument.class).get("HotelId")) - .collect(Collectors.toSet()); - Set expectedKeys = expected.stream() - .filter(item -> item.containsKey("HotelId")) - .map(item -> (String) item.get("HotelId")) - .collect(Collectors.toSet()); - assertEquals(expectedKeys, actualKeys); - } - - static void assertValueFacetsEqual(List> actualFacets, - ArrayList> expectedFacets) { - assertEquals(expectedFacets.size(), actualFacets.size()); - for (int i = 0; i < actualFacets.size(); i++) { - assertEquals(expectedFacets.get(i).getCount(), actualFacets.get(i).getCount()); - assertEquals(expectedFacets.get(i).getValue(), actualFacets.get(i).getValue()); - } - } - - static String getSearchResultId(SearchResult searchResult) { - return searchResult.getDocument(SearchDocument.class).get("HotelId").toString(); - } - - static SearchOptions getSearchOptionsForRangeFacets() { - return new SearchOptions().setFacets("Rooms/BaseRate,values:5|8|10", - "LastRenovationDate,values:2000-01-01T00:00:00Z"); - } - - static SearchOptions getSearchOptionsForValueFacets() { - return new SearchOptions().setFacets("Rating,count:2,sort:-value", "SmokingAllowed,sort:count", "Category", - "LastRenovationDate,interval:year", "Rooms/BaseRate,sort:value", "Tags,sort:value"); - } - - static void assertListEqualHotelIds(List expected, List actual) { - assertNotNull(actual); - List actualKeys = actual.stream() - .filter(item -> item.getDocument(SearchDocument.class).containsKey("HotelId")) - .map(item -> (String) item.getDocument(SearchDocument.class).get("HotelId")) - .collect(Collectors.toList()); - assertEquals(expected, actualKeys); - } - - String createIndexWithNonNullableTypes() { - SearchIndex index = new SearchIndex(testResourceNamer.randomName("non-nullable-index", 64)) - .setFields(Arrays.asList(new SearchField("Key", SearchFieldDataType.STRING).setHidden(false).setKey(true), - new SearchField("Rating", SearchFieldDataType.INT32).setHidden(false), - new SearchField("Count", SearchFieldDataType.INT64).setHidden(false), - new SearchField("IsEnabled", SearchFieldDataType.BOOLEAN).setHidden(false), - new SearchField("Ratio", SearchFieldDataType.DOUBLE).setHidden(false), - new SearchField("StartDate", SearchFieldDataType.DATE_TIME_OFFSET).setHidden(false), - new SearchField("EndDate", SearchFieldDataType.DATE_TIME_OFFSET).setHidden(false), - new SearchField("TopLevelBucket", SearchFieldDataType.COMPLEX).setFields( - Arrays.asList(new SearchField("BucketName", SearchFieldDataType.STRING).setFilterable(true), - new SearchField("Count", SearchFieldDataType.INT32).setFilterable(true))), - new SearchField("Buckets", SearchFieldDataType.collection(SearchFieldDataType.COMPLEX)).setFields( - Arrays.asList(new SearchField("BucketName", SearchFieldDataType.STRING).setFilterable(true), - new SearchField("Count", SearchFieldDataType.INT32).setFilterable(true))))); - - setupIndex(index); - - return index.getName(); - } - - String createIndexWithValueTypes() { - SearchIndex index = new SearchIndex(testResourceNamer.randomName("testindex", 64)).setFields( - Arrays.asList(new SearchField("Key", SearchFieldDataType.STRING).setKey(true).setSearchable(true), - new SearchField("IntValue", SearchFieldDataType.INT32).setFilterable(true), - new SearchField("Bucket", SearchFieldDataType.COMPLEX).setFields( - Arrays.asList(new SearchField("BucketName", SearchFieldDataType.STRING).setFilterable(true), - new SearchField("Count", SearchFieldDataType.INT32).setFilterable(true))))); - - setupIndex(index); - - return index.getName(); - } - - static List createDocsListWithValueTypes(String keySuffix) { - SearchDocument element1 = new SearchDocument(); - element1.put("Key", "123" + keySuffix); - element1.put("IntValue", 0); - - Map subElement1 = new HashMap<>(); - subElement1.put("BucketName", "A"); - subElement1.put("Count", 3); - element1.put("Bucket", subElement1); - - SearchDocument element2 = new SearchDocument(); - element2.put("Key", "456" + keySuffix); - element2.put("IntValue", 7); - - Map subElement2 = new HashMap<>(); - subElement2.put("BucketName", "B"); - subElement2.put("Count", 5); - element2.put("Bucket", subElement2); - - SearchDocument element3 = new SearchDocument(); - element3.put("Key", "789" + keySuffix); - element3.put("IntValue", 1); - - Map subElement3 = new HashMap<>(); - subElement3.put("BucketName", "B"); - subElement3.put("Count", 99); - element3.put("Bucket", subElement3); - - return Arrays.asList(element1, element2, element3); - } - - private static void canSearchWithValueFacetsValidateResponse(SearchPagedResponse result, - List> expectedHotels, Map> facets) { - assertContainHotelIds(expectedHotels, result.getValue()); - - assertValueFacetsEqual(getValueFacetsForField(facets, "Rating", 2), - new ArrayList<>(Arrays.asList(new ValueFacetResult<>(1L, 5), new ValueFacetResult<>(4L, 4)))); - - assertValueFacetsEqual(getValueFacetsForField(facets, "SmokingAllowed", 2), - new ArrayList<>(Arrays.asList(new ValueFacetResult<>(4L, false), new ValueFacetResult<>(2L, true)))); - - assertValueFacetsEqual(getValueFacetsForField(facets, "Category", 3), - new ArrayList<>(Arrays.asList(new ValueFacetResult<>(5L, "Budget"), new ValueFacetResult<>(1L, "Boutique"), - new ValueFacetResult<>(1L, "Luxury")))); - - assertValueFacetsEqual(getValueFacetsForField(facets, "LastRenovationDate", 6), - new ArrayList<>(Arrays.asList( - new ValueFacetResult<>(1L, - OffsetDateTime.parse("1970-01-01T00:00:00Z").format(DateTimeFormatter.ISO_OFFSET_DATE_TIME)), - new ValueFacetResult<>(1L, - OffsetDateTime.parse("1982-01-01T00:00:00Z").format(DateTimeFormatter.ISO_OFFSET_DATE_TIME)), - new ValueFacetResult<>(2L, - OffsetDateTime.parse("1995-01-01T00:00:00Z").format(DateTimeFormatter.ISO_OFFSET_DATE_TIME)), - new ValueFacetResult<>(1L, - OffsetDateTime.parse("1999-01-01T00:00:00Z").format(DateTimeFormatter.ISO_OFFSET_DATE_TIME)), - new ValueFacetResult<>(1L, - OffsetDateTime.parse("2010-01-01T00:00:00Z").format(DateTimeFormatter.ISO_OFFSET_DATE_TIME)), - new ValueFacetResult<>(1L, - OffsetDateTime.parse("2012-01-01T00:00:00Z").format(DateTimeFormatter.ISO_OFFSET_DATE_TIME))))); - - assertValueFacetsEqual(getValueFacetsForField(facets, "Rooms/BaseRate", 4), - new ArrayList<>(Arrays.asList(new ValueFacetResult<>(1L, 2.44), new ValueFacetResult<>(1L, 7.69), - new ValueFacetResult<>(1L, 8.09), new ValueFacetResult<>(1L, 9.69)))); - - assertValueFacetsEqual(getValueFacetsForField(facets, "Tags", 10), - new ArrayList<>(Arrays.asList(new ValueFacetResult<>(1L, "24-hour front desk service"), - new ValueFacetResult<>(1L, "air conditioning"), new ValueFacetResult<>(4L, "budget"), - new ValueFacetResult<>(1L, "coffee in lobby"), new ValueFacetResult<>(2L, "concierge"), - new ValueFacetResult<>(1L, "motel"), new ValueFacetResult<>(2L, "pool"), - new ValueFacetResult<>(1L, "restaurant"), new ValueFacetResult<>(1L, "view"), - new ValueFacetResult<>(4L, "wifi")))); - } -} diff --git a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/SuggestOptionsHandlerTests.java b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/SuggestOptionsHandlerTests.java deleted file mode 100644 index 0be95abb858a..000000000000 --- a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/SuggestOptionsHandlerTests.java +++ /dev/null @@ -1,69 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.search.documents; - -import com.azure.search.documents.implementation.util.Utility; -import com.azure.search.documents.models.SuggestOptions; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.parallel.Execution; -import org.junit.jupiter.api.parallel.ExecutionMode; - -import java.util.Collections; -import java.util.List; - -import static org.junit.jupiter.api.Assertions.assertEquals; - -@Execution(ExecutionMode.CONCURRENT) -public class SuggestOptionsHandlerTests { - - private static final List SELECT_STAR = Collections.singletonList("*"); - - @Test - public void ensureSelectConvertsEmptyToSelectStar() { - List emptySelect = Collections.emptyList(); - - SuggestOptions suggestOptions = createTestOptions(); - assertEquals(suggestOptions.getSelect(), emptySelect); - - SuggestOptions ensuredSuggestOptions = Utility.ensureSuggestOptions(suggestOptions); - assertEquals(ensuredSuggestOptions.getSelect(), SELECT_STAR); - } - - @Test - public void ensureSelectLeavesOtherPropertiesUnchanged() { - - SuggestOptions suggestOptions = createTestOptions(); - SuggestOptions ensuredSuggestOptions = Utility.ensureSuggestOptions(suggestOptions); - - assertEquals(suggestOptions.getFilter(), ensuredSuggestOptions.getFilter()); - assertEquals(suggestOptions.getHighlightPostTag(), ensuredSuggestOptions.getHighlightPostTag()); - assertEquals(suggestOptions.getHighlightPreTag(), ensuredSuggestOptions.getHighlightPreTag()); - assertEquals(suggestOptions.getMinimumCoverage(), ensuredSuggestOptions.getMinimumCoverage()); - assertEquals(suggestOptions.getOrderBy(), ensuredSuggestOptions.getOrderBy()); - assertEquals(suggestOptions.getSearchFields(), ensuredSuggestOptions.getSearchFields()); - assertEquals(suggestOptions.getTop(), ensuredSuggestOptions.getTop()); - assertEquals(suggestOptions.useFuzzyMatching(), ensuredSuggestOptions.useFuzzyMatching()); - - } - - @Test - public void ensureSelectReturnsSelfWhenSelectIsPopulated() { - SuggestOptions suggestOptions = createTestOptions(); - SuggestOptions ensuredSuggestOptions = Utility.ensureSuggestOptions(suggestOptions); - - assertEquals(suggestOptions, ensuredSuggestOptions); - } - - private static SuggestOptions createTestOptions() { - return new SuggestOptions().setFilter("x eq y") - .setHighlightPreTag("") - .setHighlightPostTag("") - .setMinimumCoverage(33.3) - .setOrderBy("a", "b desc") - .setSearchFields("a", "b", "c") - .setSelect() - .setTop(5) - .setUseFuzzyMatching(true); - } -} diff --git a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/SuggestTests.java b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/SuggestTests.java deleted file mode 100644 index 3f132fc6d413..000000000000 --- a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/SuggestTests.java +++ /dev/null @@ -1,566 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -package com.azure.search.documents; - -import com.azure.core.exception.HttpResponseException; -import com.azure.core.http.rest.PagedIterableBase; -import com.azure.core.http.rest.PagedResponse; -import com.azure.core.test.TestProxyTestBase; -import com.azure.core.test.TestMode; -import com.azure.core.util.Context; -import com.azure.search.documents.indexes.SearchIndexClient; -import com.azure.search.documents.models.SuggestOptions; -import com.azure.search.documents.models.SuggestResult; -import com.azure.search.documents.test.environment.models.Author; -import com.azure.search.documents.test.environment.models.Book; -import com.azure.search.documents.test.environment.models.Hotel; -import com.azure.search.documents.util.SuggestPagedIterable; -import com.azure.search.documents.util.SuggestPagedResponse; -import org.junit.jupiter.api.AfterAll; -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.parallel.Execution; -import org.junit.jupiter.api.parallel.ExecutionMode; -import reactor.test.StepVerifier; - -import java.net.HttpURLConnection; -import java.time.OffsetDateTime; -import java.util.Arrays; -import java.util.Comparator; -import java.util.Iterator; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import java.util.stream.Collectors; - -import static com.azure.search.documents.TestHelpers.readJsonFileToList; -import static com.azure.search.documents.TestHelpers.setupSharedIndex; -import static com.azure.search.documents.TestHelpers.waitForIndexing; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertInstanceOf; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.junit.jupiter.api.Assertions.assertTrue; - -@Execution(ExecutionMode.CONCURRENT) -public class SuggestTests extends SearchTestBase { - private static final String BOOKS_INDEX_JSON = "BooksIndexData.json"; - private static final String HOTEL_INDEX_NAME = "azsearch-suggest-shared-hotel-instance"; - private static final String BOOKS_INDEX_NAME = "azsearch-suggest-shared-books-instance"; - - private static SearchIndexClient searchIndexClient; - - @BeforeAll - public static void setupClass() { - TestProxyTestBase.setupClass(); - - if (TEST_MODE == TestMode.PLAYBACK) { - return; - } - - searchIndexClient = setupSharedIndex(HOTEL_INDEX_NAME, HOTELS_TESTS_INDEX_DATA_JSON, HOTELS_DATA_JSON); - setupSharedIndex(BOOKS_INDEX_NAME, BOOKS_INDEX_JSON, null); - - Author tolkien = new Author(); - tolkien.firstName("J.R.R."); - tolkien.lastName("Tolkien"); - Book doc1 = new Book(); - doc1.ISBN("123"); - doc1.title("Lord of the Rings"); - doc1.author(tolkien); - - Book doc2 = new Book(); - doc2.ISBN("456"); - doc2.title("War and Peace"); - doc2.publishDate(OffsetDateTime.parse("2015-08-18T00:00:00Z")); - - searchIndexClient.getSearchClient(BOOKS_INDEX_NAME).uploadDocuments(Arrays.asList(doc1, doc2)); - waitForIndexing(); - } - - @AfterAll - protected static void cleanupClass() { - if (TEST_MODE != TestMode.PLAYBACK) { - searchIndexClient.deleteIndex(HOTEL_INDEX_NAME); - searchIndexClient.deleteIndex(BOOKS_INDEX_NAME); - } - } - - private SearchClient getClient(String indexName) { - return getSearchClientBuilder(indexName, true).buildClient(); - } - - private SearchAsyncClient getAsyncClient(String indexName) { - return getSearchClientBuilder(indexName, false).buildAsyncClient(); - } - - @Test - public void canSuggestDynamicDocumentsSync() { - SearchClient client = getClient(HOTEL_INDEX_NAME); - - SuggestOptions suggestOptions = new SuggestOptions().setOrderBy("HotelId"); - - Iterator suggestResultIterator - = client.suggest("more", "sg", suggestOptions, Context.NONE).iterableByPage().iterator(); - - verifyDynamicDocumentSuggest(suggestResultIterator.next()); - assertFalse(suggestResultIterator.hasNext()); - } - - @Test - public void canSuggestDynamicDocumentsAsync() { - SearchAsyncClient asyncClient = getAsyncClient(HOTEL_INDEX_NAME); - - SuggestOptions suggestOptions = new SuggestOptions().setOrderBy("HotelId"); - - StepVerifier.create(asyncClient.suggest("more", "sg", suggestOptions).byPage()) - .assertNext(SuggestTests::verifyDynamicDocumentSuggest) - .verifyComplete(); - } - - @Test - public void searchFieldsExcludesFieldsFromSuggestSync() { - SearchClient client = getClient(HOTEL_INDEX_NAME); - - SuggestOptions suggestOptions = new SuggestOptions().setSearchFields("HotelName"); - - Iterator suggestResultIterator - = client.suggest("luxury", "sg", suggestOptions, Context.NONE).iterableByPage().iterator(); - - verifySuggestionCount(suggestResultIterator.next(), 0); - assertFalse(suggestResultIterator.hasNext()); - } - - @Test - public void searchFieldsExcludesFieldsFromSuggestAsync() { - SearchAsyncClient asyncClient = getAsyncClient(HOTEL_INDEX_NAME); - - SuggestOptions suggestOptions = new SuggestOptions().setSearchFields("HotelName"); - - StepVerifier.create(asyncClient.suggest("luxury", "sg", suggestOptions).byPage()) - .assertNext(response -> verifySuggestionCount(response, 0)) - .verifyComplete(); - } - - @Test - public void canUseSuggestHitHighlightingSync() { - SearchClient client = getClient(HOTEL_INDEX_NAME); - - SuggestOptions suggestOptions = new SuggestOptions().setHighlightPreTag("") - .setHighlightPostTag("") - .setFilter("Category eq 'Luxury'") - .setTop(1); - - Iterator suggestResultIterator - = client.suggest("hotel", "sg", suggestOptions, Context.NONE).iterableByPage().iterator(); - - verifyHitHighlightingSuggest(suggestResultIterator.next()); - assertFalse(suggestResultIterator.hasNext()); - } - - @Test - public void canUseSuggestHitHighlightingAsync() { - SearchAsyncClient asyncClient = getAsyncClient(HOTEL_INDEX_NAME); - - SuggestOptions suggestOptions = new SuggestOptions().setHighlightPreTag("") - .setHighlightPostTag("") - .setFilter("Category eq 'Luxury'") - .setTop(1); - - StepVerifier.create(asyncClient.suggest("hotel", "sg", suggestOptions).byPage()) - .assertNext(SuggestTests::verifyHitHighlightingSuggest) - .verifyComplete(); - } - - @Test - public void canGetFuzzySuggestionsSync() { - SearchClient client = getClient(HOTEL_INDEX_NAME); - - SuggestOptions suggestOptions = new SuggestOptions().setUseFuzzyMatching(true); - - Iterator suggestResultIterator - = client.suggest("hitel", "sg", suggestOptions, Context.NONE).iterableByPage().iterator(); - - verifySuggestionCount(suggestResultIterator.next(), 5); - assertFalse(suggestResultIterator.hasNext()); - } - - @Test - public void canGetFuzzySuggestionsAsync() { - SearchAsyncClient asyncClient = getAsyncClient(HOTEL_INDEX_NAME); - - SuggestOptions suggestOptions = new SuggestOptions().setUseFuzzyMatching(true); - - StepVerifier.create(asyncClient.suggest("hitel", "sg", suggestOptions).byPage()) - .assertNext(response -> verifySuggestionCount(response, 5)) - .verifyComplete(); - } - - @Test - public void canSuggestStaticallyTypedDocumentsSync() { - SearchClient client = getClient(HOTEL_INDEX_NAME); - - List> hotels = readJsonFileToList(HOTELS_DATA_JSON); - //arrange - SuggestOptions suggestOptions = new SuggestOptions().setOrderBy("HotelId"); - - //act - Iterator suggestResultIterator - = client.suggest("more", "sg", suggestOptions, Context.NONE).iterableByPage().iterator(); - - //assert - verifyCanSuggestStaticallyTypedDocuments(suggestResultIterator.next(), hotels); - } - - @Test - public void canSuggestStaticallyTypedDocumentsAsync() { - SearchAsyncClient asyncClient = getAsyncClient(HOTEL_INDEX_NAME); - - List> hotels = readJsonFileToList(HOTELS_DATA_JSON); - //arrange - SuggestOptions suggestOptions = new SuggestOptions().setOrderBy("HotelId"); - - //act - StepVerifier.create(asyncClient.suggest("more", "sg", suggestOptions).byPage()) - .assertNext(response -> verifyCanSuggestStaticallyTypedDocuments(response, hotels)) - .verifyComplete(); - } - - @Test - public void canSuggestWithDateTimeInStaticModelSync() { - SearchClient client = getClient(BOOKS_INDEX_NAME); - - SuggestOptions suggestOptions = new SuggestOptions(); - suggestOptions.setSelect("ISBN", "Title", "PublishDate"); - Iterator suggestResultIterator - = client.suggest("War", "sg", suggestOptions, Context.NONE).iterableByPage().iterator(); - - //assert - verifyCanSuggestWithDateTimeInStaticModel(suggestResultIterator.next()); - } - - @Test - public void canSuggestWithDateTimeInStaticModelAsync() { - SearchAsyncClient asyncClient = getAsyncClient(BOOKS_INDEX_NAME); - - SuggestOptions suggestOptions = new SuggestOptions(); - suggestOptions.setSelect("ISBN", "Title", "PublishDate"); - - StepVerifier.create(asyncClient.suggest("War", "sg", suggestOptions).byPage()) - .assertNext(SuggestTests::verifyCanSuggestWithDateTimeInStaticModel) - .verifyComplete(); - } - - @Test - public void fuzzyIsOffByDefaultSync() { - SearchClient client = getClient(HOTEL_INDEX_NAME); - - Iterator suggestResultIterator - = client.suggest("hitel", "sg", null, Context.NONE).iterableByPage().iterator(); - - verifySuggestionCount(suggestResultIterator.next(), 0); - - Iterator suggestResultWithoutSuggestOptions - = client.suggest("hitel", "sg").iterableByPage().iterator(); - - verifySuggestionCount(suggestResultWithoutSuggestOptions.next(), 0); - } - - @Test - public void fuzzyIsOffByDefaultAsync() { - SearchAsyncClient asyncClient = getAsyncClient(HOTEL_INDEX_NAME); - - StepVerifier.create(asyncClient.suggest("hitel", "sg", null).byPage()) - .assertNext(response -> verifySuggestionCount(response, 0)) - .verifyComplete(); - - StepVerifier.create(asyncClient.suggest("hitel", "sg").byPage()) - .assertNext(response -> verifySuggestionCount(response, 0)) - .verifyComplete(); - } - - @Test - public void suggestThrowsWhenGivenBadSuggesterNameSync() { - SearchClient client = getClient(HOTEL_INDEX_NAME); - - SuggestPagedIterable suggestResultIterator - = client.suggest("Hotel", "Suggester does not exist", new SuggestOptions(), Context.NONE); - - HttpResponseException ex - = assertThrows(HttpResponseException.class, () -> suggestResultIterator.iterableByPage().iterator().next()); - assertEquals(HttpURLConnection.HTTP_BAD_REQUEST, ex.getResponse().getStatusCode()); - } - - @Test - public void suggestThrowsWhenGivenBadSuggesterNameAsync() { - SearchAsyncClient asyncClient = getAsyncClient(HOTEL_INDEX_NAME); - - StepVerifier.create(asyncClient.suggest("Hotel", "Suggester does not exist", new SuggestOptions()).byPage()) - .thenRequest(1) - .verifyErrorSatisfies(throwable -> { - HttpResponseException ex = assertInstanceOf(HttpResponseException.class, throwable); - assertEquals(HttpURLConnection.HTTP_BAD_REQUEST, ex.getResponse().getStatusCode()); - }); - } - - @Test - public void suggestThrowsWhenRequestIsMalformedSync() { - SearchClient client = getClient(HOTEL_INDEX_NAME); - - SuggestOptions suggestOptions = new SuggestOptions().setOrderBy("This is not a valid orderby."); - - SuggestPagedIterable suggestResultIterator = client.suggest("hotel", "sg", suggestOptions, Context.NONE); - - HttpResponseException ex - = assertThrows(HttpResponseException.class, () -> suggestResultIterator.iterableByPage().iterator().next()); - assertEquals(HttpURLConnection.HTTP_BAD_REQUEST, ex.getResponse().getStatusCode()); - } - - @Test - public void suggestThrowsWhenRequestIsMalformedAsync() { - SearchAsyncClient asyncClient = getAsyncClient(HOTEL_INDEX_NAME); - - SuggestOptions suggestOptions = new SuggestOptions().setOrderBy("This is not a valid orderby."); - - StepVerifier.create(asyncClient.suggest("hotel", "sg", suggestOptions)) - .thenRequest(1) - .verifyErrorSatisfies(throwable -> { - HttpResponseException ex = assertInstanceOf(HttpResponseException.class, throwable); - assertEquals(HttpURLConnection.HTTP_BAD_REQUEST, ex.getResponse().getStatusCode()); - }); - } - - @Test - public void testCanSuggestWithMinimumCoverageSync() { - SearchClient client = getClient(HOTEL_INDEX_NAME); - - //arrange - SuggestOptions suggestOptions = new SuggestOptions().setOrderBy("HotelId").setMinimumCoverage(50.0); - - //act - SuggestPagedResponse suggestPagedResponse - = client.suggest("luxury", "sg", suggestOptions, Context.NONE).iterableByPage().iterator().next(); - - verifyMinimumCoverage(suggestPagedResponse); - } - - @Test - public void testCanSuggestWithMinimumCoverageAsync() { - SearchAsyncClient asyncClient = getAsyncClient(HOTEL_INDEX_NAME); - - //arrange - SuggestOptions suggestOptions = new SuggestOptions().setOrderBy("HotelId").setMinimumCoverage(50.0); - - //act - StepVerifier.create(asyncClient.suggest("luxury", "sg", suggestOptions).byPage()) - .assertNext(SuggestTests::verifyMinimumCoverage) - .verifyComplete(); - } - - @Test - public void testTopTrimsResultsSync() { - SearchClient client = getClient(HOTEL_INDEX_NAME); - - //arrange - SuggestOptions suggestOptions = new SuggestOptions().setOrderBy("HotelId").setTop(3); - - //act - SuggestPagedResponse suggestResultIterator - = client.suggest("hotel", "sg", suggestOptions, Context.NONE).iterableByPage().iterator().next(); - - //assert - verifyTopDocumentSuggest(suggestResultIterator); - } - - @Test - public void testTopTrimsResultsAsync() { - SearchAsyncClient asyncClient = getAsyncClient(HOTEL_INDEX_NAME); - - //arrange - SuggestOptions suggestOptions = new SuggestOptions().setOrderBy("HotelId").setTop(3); - - //act - StepVerifier.create(asyncClient.suggest("hotel", "sg", suggestOptions).byPage()) - .assertNext(SuggestTests::verifyTopDocumentSuggest) - .verifyComplete(); - } - - @Test - public void testCanFilterSync() { - SearchClient client = getClient(HOTEL_INDEX_NAME); - - SuggestOptions suggestOptions - = new SuggestOptions().setFilter("Rating gt 3 and LastRenovationDate gt 2000-01-01T00:00:00Z") - .setOrderBy("HotelId"); - - SuggestPagedResponse suggestPagedResponse - = client.suggest("hotel", "sg", suggestOptions, Context.NONE).iterableByPage().iterator().next(); - - assertNotNull(suggestPagedResponse); - List actualIds = suggestPagedResponse.getValue() - .stream() - .map(s -> (String) s.getDocument(SearchDocument.class).get("HotelId")) - .collect(Collectors.toList()); - List expectedIds = Arrays.asList("1", "5"); - assertEquals(expectedIds, actualIds); - } - - @Test - public void testCanFilterAsync() { - SearchAsyncClient asyncClient = getAsyncClient(HOTEL_INDEX_NAME); - - SuggestOptions suggestOptions - = new SuggestOptions().setFilter("Rating gt 3 and LastRenovationDate gt 2000-01-01T00:00:00Z") - .setOrderBy("HotelId"); - - StepVerifier.create(asyncClient.suggest("hotel", "sg", suggestOptions).byPage()).assertNext(response -> { - List expectedIds = Arrays.asList("1", "5"); - List actualIds = response.getValue() - .stream() - .map(sr -> sr.getDocument(SearchDocument.class).get("HotelId").toString()) - .collect(Collectors.toList()); - - assertEquals(expectedIds, actualIds); - }).verifyComplete(); - } - - @Test - public void testOrderByProgressivelyBreaksTiesSync() { - SearchClient client = getClient(HOTEL_INDEX_NAME); - - SuggestOptions suggestOptions = new SuggestOptions().setOrderBy("Rating desc", "LastRenovationDate asc", - "geo.distance(Location, geography'POINT(-122.0 49.0)')"); - - SuggestPagedResponse suggestPagedResponse - = client.suggest("hotel", "sg", suggestOptions, Context.NONE).iterableByPage().iterator().next(); - - assertNotNull(suggestPagedResponse); - List actualIds = suggestPagedResponse.getValue() - .stream() - .map(s -> (String) s.getDocument(SearchDocument.class).get("HotelId")) - .collect(Collectors.toList()); - List expectedIds = Arrays.asList("1", "9", "4", "3", "5"); - assertEquals(expectedIds, actualIds); - } - - @Test - public void testOrderByProgressivelyBreaksTiesAsync() { - SearchAsyncClient asyncClient = getAsyncClient(HOTEL_INDEX_NAME); - - SuggestOptions suggestOptions = new SuggestOptions().setOrderBy("Rating desc", "LastRenovationDate asc", - "geo.distance(Location, geography'POINT(-122.0 49.0)')"); - - StepVerifier.create(asyncClient.suggest("hotel", "sg", suggestOptions).byPage()).assertNext(response -> { - List expectedIds = Arrays.asList("1", "9", "4", "3", "5"); - List actualIds = response.getValue() - .stream() - .map(sr -> sr.getDocument(SearchDocument.class).get("HotelId").toString()) - .collect(Collectors.toList()); - - assertEquals(expectedIds, actualIds); - }).verifyComplete(); - } - - @Test - public void testCanSuggestWithSelectedFieldsSync() { - SearchClient client = getClient(HOTEL_INDEX_NAME); - - SuggestOptions suggestOptions - = new SuggestOptions().setSelect("HotelName", "Rating", "Address/City", "Rooms/Type"); - PagedIterableBase suggestResult - = client.suggest("secret", "sg", suggestOptions, Context.NONE); - - verifySuggestWithSelectedFields(suggestResult.iterableByPage().iterator().next()); - } - - @Test - public void testCanSuggestWithSelectedFieldsAsync() { - SearchAsyncClient asyncClient = getAsyncClient(HOTEL_INDEX_NAME); - - SuggestOptions suggestOptions - = new SuggestOptions().setSelect("HotelName", "Rating", "Address/City", "Rooms/Type"); - - StepVerifier.create(asyncClient.suggest("secret", "sg", suggestOptions).byPage()) - .assertNext(SuggestTests::verifySuggestWithSelectedFields) - .verifyComplete(); - } - - static void verifySuggestionCount(SuggestPagedResponse response, int count) { - assertNotNull(response); - assertEquals(count, response.getValue().size()); - } - - static void verifyHitHighlightingSuggest(SuggestPagedResponse suggestResultPagedResponse) { - assertNotNull(suggestResultPagedResponse); - assertEquals(1, suggestResultPagedResponse.getValue().size()); - assertTrue(suggestResultPagedResponse.getValue().get(0).getText().startsWith("Best hotel in town")); - } - - static void verifyDynamicDocumentSuggest(SuggestPagedResponse suggestResultPagedResponse) { - assertNotNull(suggestResultPagedResponse); - assertEquals(2, suggestResultPagedResponse.getValue().size()); - Hotel hotel = suggestResultPagedResponse.getValue().get(0).getDocument(Hotel.class); - assertEquals("10", hotel.hotelId()); - } - - static void verifyCanSuggestStaticallyTypedDocuments(SuggestPagedResponse suggestResultPagedResponse, - List> expectedHotels) { - //sanity - assertNotNull(suggestResultPagedResponse); - List docs = suggestResultPagedResponse.getValue() - .stream() - .map(suggestResult -> suggestResult.getDocument(SearchDocument.class)) - .collect(Collectors.toList()); - List hotelsList = suggestResultPagedResponse.getValue(); - - List expectedHotelsList = expectedHotels.stream() - .map(SearchDocument::new) - .filter(h -> h.get("HotelId").equals("10") || h.get("HotelId").equals("8")) - .sorted(Comparator.comparing(h -> h.get("HotelId").toString())) - .collect(Collectors.toList()); - - //assert - //verify fields - assertEquals(2, docs.size()); - assertEquals(hotelsList.stream().map(SuggestResult::getText).collect(Collectors.toList()), - expectedHotelsList.stream().map(hotel -> hotel.get("Description")).collect(Collectors.toList())); - } - - static void verifyMinimumCoverage(SuggestPagedResponse suggestResultPagedResponse) { - assertNotNull(suggestResultPagedResponse); - assertEquals(Double.valueOf(100.0), suggestResultPagedResponse.getCoverage()); - } - - static void verifyTopDocumentSuggest(SuggestPagedResponse suggestResultPagedResponse) { - assertNotNull(suggestResultPagedResponse); - assertEquals(3, suggestResultPagedResponse.getValue().size()); - List resultIds = suggestResultPagedResponse.getValue() - .stream() - .map(hotel -> hotel.getDocument(Hotel.class).hotelId()) - .collect(Collectors.toList()); - - assertEquals(Arrays.asList("1", "10", "2"), resultIds); - } - - static void verifyCanSuggestWithDateTimeInStaticModel(SuggestPagedResponse suggestResultPagedResponse) { - List books = suggestResultPagedResponse.getValue(); - - assertEquals(1, books.size()); - assertEquals("War and Peace", books.get(0).getText()); - } - - @SuppressWarnings("unchecked") - static void verifySuggestWithSelectedFields(PagedResponse suggestResultPagedResponse) { - assertEquals(1, suggestResultPagedResponse.getValue().size()); - SearchDocument result = suggestResultPagedResponse.getValue().get(0).getDocument(SearchDocument.class); - - assertEquals("Secret Point Motel", result.get("HotelName")); - assertEquals(4, ((Number) result.get("Rating")).intValue()); - assertEquals("New York", ((LinkedHashMap) result.get("Address")).get("City")); - assertEquals(Arrays.asList("Budget Room", "Budget Room"), - ((List>) result.get("Rooms")).stream() - .map(room -> room.get("Type")) - .collect(Collectors.toList())); - } -} diff --git a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/TestHelpers.java b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/TestHelpers.java deleted file mode 100644 index 4c59d04464b4..000000000000 --- a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/TestHelpers.java +++ /dev/null @@ -1,481 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.search.documents; - -import com.azure.core.credential.TokenCredential; -import com.azure.core.exception.HttpResponseException; -import com.azure.core.http.HttpClient; -import com.azure.core.http.HttpPipeline; -import com.azure.core.http.policy.HttpLogDetailLevel; -import com.azure.core.http.policy.HttpLogOptions; -import com.azure.core.test.TestMode; -import com.azure.core.test.http.AssertingHttpClientBuilder; -import com.azure.core.test.utils.MockTokenCredential; -import com.azure.core.util.Configuration; -import com.azure.core.util.ExpandableStringEnum; -import com.azure.core.util.serializer.JsonSerializer; -import com.azure.core.util.serializer.JsonSerializerProviders; -import com.azure.core.util.serializer.TypeReference; -import com.azure.identity.*; -import com.azure.json.JsonProviders; -import com.azure.json.JsonReader; -import com.azure.json.JsonSerializable; -import com.azure.json.JsonWriter; -import com.azure.search.documents.indexes.SearchIndexClient; -import com.azure.search.documents.indexes.SearchIndexClientBuilder; -import com.azure.search.documents.indexes.models.SearchIndex; -import com.azure.search.documents.test.environment.models.NonNullableModel; - -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.UncheckedIOException; -import java.lang.reflect.Array; -import java.net.URI; -import java.nio.file.Files; -import java.nio.file.Paths; -import java.time.OffsetDateTime; -import java.time.ZoneOffset; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.Date; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.concurrent.ConcurrentHashMap; -import java.util.function.Function; - -import static com.azure.search.documents.SearchTestBase.ENDPOINT; -import static com.azure.search.documents.SearchTestBase.SERVICE_THROTTLE_SAFE_RETRY_POLICY; -import static org.junit.jupiter.api.Assertions.assertArrayEquals; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNull; -import static org.junit.jupiter.api.Assertions.assertTrue; -import static org.junit.jupiter.api.Assertions.fail; - -/** - * This class contains helper methods for running Azure AI Search tests. - */ -public final class TestHelpers { - private static TestMode testMode = setupTestMode(); - - private static final JsonSerializer SERIALIZER = JsonSerializerProviders.createInstance(true); - - public static final String HOTEL_INDEX_NAME = "hotels"; - - public static final String BLOB_DATASOURCE_NAME = "azs-java-live-blob"; - public static final String BLOB_DATASOURCE_TEST_NAME = "azs-java-test-blob"; - public static final String SQL_DATASOURCE_NAME = "azs-java-test-sql"; - public static final String ISO8601_FORMAT = "yyyy-MM-dd'T'HH:mm:ss'Z'"; - - private static final Map LOADED_FILE_DATA = new ConcurrentHashMap<>(); - - /** - * Assert whether two objects are equal. - * - * @param expected The expected object. - * @param actual The actual object. - */ - public static void assertObjectEquals(Object expected, Object actual) { - assertArrayEquals(SERIALIZER.serializeToBytes(expected), SERIALIZER.serializeToBytes(actual)); - } - - /** - * Assert whether two objects are equal. - * - * @param expected The expected object. - * @param actual The actual object. - * @param ignoreDefaults Set to true if it needs to ignore default value of expected object. - * @param ignoredFields Varargs of ignored fields. - */ - public static void assertObjectEquals(Object expected, Object actual, boolean ignoreDefaults, - String... ignoredFields) { - Set ignored - = (ignoredFields == null) ? Collections.emptySet() : new HashSet<>(Arrays.asList(ignoredFields)); - - assertObjectEqualsInternal(expected, actual, ignoreDefaults, ignored); - } - - @SuppressWarnings({ "unchecked", "rawtypes", "UseOfObsoleteDateTimeApi" }) - private static void assertObjectEqualsInternal(Object expected, Object actual, boolean ignoredDefaults, - Set ignoredFields) { - if (expected == null) { - assertNull(actual); - } else if (isComparableType(expected.getClass())) { - if (expected instanceof Number) { - assertEquals(((Number) expected).doubleValue(), ((Number) actual).doubleValue()); - } else { - assertEquals(expected, actual); - } - } else if (expected instanceof OffsetDateTime) { - assertEquals(0, ((OffsetDateTime) expected).compareTo(OffsetDateTime.parse(actual.toString()))); - } else if (expected instanceof Date) { - assertDateEquals((Date) expected, (Date) actual); - } else if (expected instanceof Map) { - assertMapEqualsInternal((Map) expected, (Map) actual, ignoredDefaults, ignoredFields); - } else { - byte[] expectedJson; - byte[] actualJson; - if (expected instanceof JsonSerializable) { - expectedJson = serializeJsonSerializable((JsonSerializable) expected); - actualJson = (actual instanceof JsonSerializable) - ? serializeJsonSerializable((JsonSerializable) actual) - : SERIALIZER.serializeToBytes(actual); - } else { - expectedJson = SERIALIZER.serializeToBytes(expected); - actualJson = SERIALIZER.serializeToBytes(actual); - } - - try (JsonReader expectedReader = JsonProviders.createReader(expectedJson); - JsonReader actualReader = JsonProviders.createReader(actualJson)) { - - assertMapEqualsInternal(expectedReader.readMap(JsonReader::readUntyped), - actualReader.readMap(JsonReader::readUntyped), ignoredDefaults, ignoredFields); - } catch (IOException ex) { - throw new UncheckedIOException(ex); - } - } - } - - private static byte[] serializeJsonSerializable(JsonSerializable jsonSerializable) { - if (jsonSerializable == null) { - return new byte[0]; - } - - ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); - - try (JsonWriter writer = JsonProviders.createWriter(outputStream)) { - jsonSerializable.toJson(writer).flush(); - return outputStream.toByteArray(); - } catch (IOException ex) { - throw new UncheckedIOException(ex); - } - } - - /** - * Determines if two lists of documents are equal by comparing their keys. - * - * @param group1 The first list of documents. - * @param group2 The second list documents. - * @return True of false if the documents are equal or not equal, respectively. - */ - public static boolean equalDocumentSets(List group1, List group2) { - List group1Keys = produceKeyList(group1, TestHelpers::extractKeyFromDocument); - List group2Keys = produceKeyList(group2, TestHelpers::extractKeyFromDocument); - return group1Keys.containsAll(group2Keys); - } - - private static List produceKeyList(List objList, Function extractKeyFunc) { - List keyList = new ArrayList<>(); - for (T obj : objList) { - keyList.add(extractKeyFunc.apply(obj)); - } - return keyList; - } - - private static String extractKeyFromDocument(NonNullableModel document) { - return document.key(); - } - - /** - * Assert whether two maps are equal, map key must be String. - * - * @param expectedMap The expected map. - * @param actualMap The actual map. - */ - public static void assertMapEquals(Map expectedMap, Map actualMap, - boolean ignoreDefaults, String... ignoredFields) { - Set ignored - = (ignoredFields == null) ? Collections.emptySet() : new HashSet<>(Arrays.asList(ignoredFields)); - - assertMapEqualsInternal(expectedMap, actualMap, ignoreDefaults, ignored); - } - - @SuppressWarnings({ "unchecked", "rawtypes" }) - private static void assertMapEqualsInternal(Map expectedMap, Map actualMap, - boolean ignoreDefaults, Set ignoredFields) { - for (Map.Entry entry : expectedMap.entrySet()) { - String expectedKey = entry.getKey(); - Object expectedValue = entry.getValue(); - - if (shouldSkipField(expectedKey, expectedValue, ignoreDefaults, ignoredFields)) { - continue; - } - - assertTrue(actualMap.containsKey(expectedKey)); - Object actualValue = actualMap.get(expectedKey); - if (expectedValue == null) { - assertNull(actualValue); - } else { - if (isComparableType(expectedValue.getClass())) { - if (expectedValue instanceof Number) { - assertEquals(((Number) entry.getValue()).doubleValue(), ((Number) actualValue).doubleValue()); - } else { - assertEquals(entry.getValue(), actualValue); - } - } else if (expectedValue instanceof List) { - assertListEquals((List) expectedValue, (List) actualValue, ignoreDefaults, ignoredFields); - } else { - assertObjectEqualsInternal(expectedValue, actualValue, ignoreDefaults, ignoredFields); - } - } - } - } - - @SuppressWarnings("UseOfObsoleteDateTimeApi") - private static void assertDateEquals(Date expect, Date actual) { - assertEquals(0, - expect.toInstant().atOffset(ZoneOffset.UTC).compareTo(actual.toInstant().atOffset(ZoneOffset.UTC))); - } - - private static void assertListEquals(List expected, List actual, boolean ignoreDefaults, - Set ignoredFields) { - for (int i = 0; i < expected.size(); i++) { - assertObjectEqualsInternal(expected.get(i), actual.get(i), ignoreDefaults, ignoredFields); - } - } - - private static boolean isComparableType(Class clazz) { - return clazz.isPrimitive() // Primitive types are always comparable. - || clazz.isEnum() // Enums are comparable - || ExpandableStringEnum.class.isAssignableFrom(clazz) // And so are ExpandableStringEnums - || Byte.class.isAssignableFrom(clazz) // Boxed primitives are also comparable - || Boolean.class.isAssignableFrom(clazz) - || Character.class.isAssignableFrom(clazz) - || Short.class.isAssignableFrom(clazz) - || Integer.class.isAssignableFrom(clazz) - || Long.class.isAssignableFrom(clazz) - || Float.class.isAssignableFrom(clazz) - || Double.class.isAssignableFrom(clazz) - || String.class.isAssignableFrom(clazz) // And so are Strings - || (clazz.isArray() && isComparableType(Array.newInstance(clazz, 0).getClass())); // Array of comparable - } - - private static boolean shouldSkipField(String fieldName, Object value, boolean ignoreDefaults, - Set ignoredFields) { - if (ignoredFields != null && ignoredFields.contains(fieldName)) { - return true; - } - - if (ignoreDefaults) { - if (value == null) { - return true; - } - if (value instanceof Boolean && !((boolean) value)) { - return true; - } - - return value instanceof Number && ((Number) value).doubleValue() == 0.0D; - } - - return false; - } - - public static void assertHttpResponseException(Runnable exceptionThrower, int statusCode, String expectedMessage) { - try { - exceptionThrower.run(); - fail(); - } catch (Throwable ex) { - verifyHttpResponseError(ex, statusCode, expectedMessage); - } - } - - public static void verifyHttpResponseError(Throwable ex, int statusCode, String expectedMessage) { - if (ex instanceof HttpResponseException) { - assertEquals(statusCode, ((HttpResponseException) ex).getResponse().getStatusCode()); - - if (expectedMessage != null) { - assertTrue(ex.getMessage().contains(expectedMessage)); - } - } else { - fail("Expected exception to be instanceof HttpResponseException", ex); - } - } - - public static void waitForIndexing() { - // Wait 2 seconds to allow index request to finish. - sleepIfRunningAgainstService(2000); - } - - public static void sleepIfRunningAgainstService(long millis) { - testMode = setupTestMode(); - if (testMode == TestMode.PLAYBACK) { - return; - } - - try { - Thread.sleep(millis); - } catch (InterruptedException ex) { - throw new IllegalStateException(ex); - } - } - - static TestMode setupTestMode() { - try { - return TestMode.valueOf(Configuration.getGlobalConfiguration().get("AZURE_TEST_MODE", "PLAYBACK")); - } catch (RuntimeException ex) { - return TestMode.PLAYBACK; - } - } - - public static void uploadDocuments(SearchClient client, List uploadDoc) { - client.uploadDocuments(uploadDoc); - waitForIndexing(); - } - - public static void uploadDocuments(SearchAsyncClient client, List uploadDoc) { - client.uploadDocuments(uploadDoc).block(); - waitForIndexing(); - } - - public static void uploadDocument(SearchClient client, T uploadDoc) { - client.uploadDocuments(Collections.singletonList(uploadDoc)); - waitForIndexing(); - } - - public static void uploadDocument(SearchAsyncClient client, T uploadDoc) { - client.uploadDocuments(Collections.singletonList(uploadDoc)).block(); - waitForIndexing(); - } - - public static List> uploadDocumentsJson(SearchClient client, String dataJson) { - List> documents = readJsonFileToList(dataJson); - uploadDocuments(client, documents); - - return documents; - } - - public static List> uploadDocumentsJson(SearchAsyncClient client, String dataJson) { - List> documents = readJsonFileToList(dataJson); - uploadDocuments(client, documents); - - return documents; - } - - public static HttpPipeline getHttpPipeline(SearchClient searchClient) { - return searchClient.getHttpPipeline(); - } - - public static HttpPipeline getHttpPipeline(SearchAsyncClient searchAsyncClient) { - return searchAsyncClient.getHttpPipeline(); - } - - public static List> readJsonFileToList(String filename) { - try (JsonReader jsonReader = JsonProviders.createReader(loadResource(filename))) { - return jsonReader.readArray(reader -> reader.readMap(JsonReader::readUntyped)); - } catch (IOException ex) { - throw new UncheckedIOException(ex); - } - } - - public static Map convertStreamToMap(byte[] source) { - try (JsonReader jsonReader = JsonProviders.createReader(source)) { - return jsonReader.readMap(JsonReader::readUntyped); - } catch (IOException ex) { - throw new UncheckedIOException(ex); - } - } - - public static T convertMapToValue(Map value, Class clazz) { - return SERIALIZER.deserializeFromBytes(SERIALIZER.serializeToBytes(value), TypeReference.createInstance(clazz)); - } - - public static SearchIndexClient setupSharedIndex(String indexName, String indexDefinition, String indexData) { - try (JsonReader jsonReader = JsonProviders.createReader(loadResource(indexDefinition))) { - SearchIndex baseIndex = SearchIndex.fromJson(jsonReader); - - SearchIndexClient searchIndexClient = new SearchIndexClientBuilder().endpoint(ENDPOINT) - .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS)) - .credential(TestHelpers.getTestTokenCredential()) - .retryPolicy(SERVICE_THROTTLE_SAFE_RETRY_POLICY) - .buildClient(); - - searchIndexClient.createOrUpdateIndex(createTestIndex(indexName, baseIndex)); - - if (indexData != null) { - uploadDocumentsJson(searchIndexClient.getSearchClient(indexName), indexData); - } - - return searchIndexClient; - } catch (IOException ex) { - throw new UncheckedIOException(ex); - } - } - - /** - * Retrieve the appropriate TokenCredential based on the test mode. - * - * @return The appropriate token credential - */ - public static TokenCredential getTestTokenCredential() { - if (testMode == TestMode.PLAYBACK) { - return new MockTokenCredential(); - } else if (testMode == TestMode.RECORD) { - return new DefaultAzureCredentialBuilder().build(); - } else { - return new AzurePowerShellCredentialBuilder().build(); - } - } - - static SearchIndex createTestIndex(String testIndexName, SearchIndex baseIndex) { - return new SearchIndex(testIndexName).setFields(baseIndex.getFields()) - .setScoringProfiles(baseIndex.getScoringProfiles()) - .setDefaultScoringProfile(baseIndex.getDefaultScoringProfile()) - .setCorsOptions(baseIndex.getCorsOptions()) - .setSuggesters(baseIndex.getSuggesters()) - .setAnalyzers(baseIndex.getAnalyzers()) - .setTokenizers(baseIndex.getTokenizers()) - .setTokenFilters(baseIndex.getTokenFilters()) - .setCharFilters(baseIndex.getCharFilters()) - .setEncryptionKey(baseIndex.getEncryptionKey()) - .setSimilarity(baseIndex.getSimilarity()) - .setSemanticSearch(baseIndex.getSemanticSearch()) - .setETag(baseIndex.getETag()); - } - - public static HttpClient buildSyncAssertingClient(HttpClient httpClient) { - return new AssertingHttpClientBuilder(httpClient).skipRequest((httpRequest, context) -> false) - .assertSync() - .build(); - } - - public static SearchIndexClient createSharedSearchIndexClient() { - return new SearchIndexClientBuilder().endpoint(ENDPOINT) - .credential(getTestTokenCredential()) - .retryPolicy(SERVICE_THROTTLE_SAFE_RETRY_POLICY) - .httpClient(buildSyncAssertingClient(HttpClient.createDefault())) - .buildClient(); - } - - public static String createGeographyPolygon(String... coordinates) { - if (coordinates.length % 2 != 0) { - throw new RuntimeException("'coordinates' must contain pairs of two."); - } - - StringBuilder builder = new StringBuilder("geography'POLYGON(("); - - for (int i = 0; i < coordinates.length; i += 2) { - if (i != 0) { - builder.append(','); - } - - builder.append(coordinates[i]).append(' ').append(coordinates[i + 1]); - } - - return builder.append("))'").toString(); - } - - static byte[] loadResource(String fileName) { - return LOADED_FILE_DATA.computeIfAbsent(fileName, fName -> { - try { - URI fileUri = AutocompleteTests.class.getClassLoader().getResource(fileName).toURI(); - - return Files.readAllBytes(Paths.get(fileUri)); - } catch (Exception ex) { - throw new RuntimeException(ex); - } - }); - } -} diff --git a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/UtilityMethodTests.java b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/UtilityMethodTests.java deleted file mode 100644 index a2e4f5ef657b..000000000000 --- a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/UtilityMethodTests.java +++ /dev/null @@ -1,110 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.search.documents; - -import com.azure.search.documents.models.QueryAnswer; -import com.azure.search.documents.models.QueryAnswerType; -import com.azure.search.documents.models.QueryCaption; -import com.azure.search.documents.models.QueryCaptionType; -import com.azure.search.documents.models.QueryRewrites; -import com.azure.search.documents.models.QueryRewritesType; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.parallel.Execution; -import org.junit.jupiter.api.parallel.ExecutionMode; -import org.junit.jupiter.params.ParameterizedTest; -import org.junit.jupiter.params.provider.Arguments; -import org.junit.jupiter.params.provider.MethodSource; - -import java.util.stream.Stream; - -import static org.junit.jupiter.api.Assertions.assertEquals; - -/** - * Test general utility methods. - */ -@Execution(ExecutionMode.CONCURRENT) -public class UtilityMethodTests { - @ParameterizedTest - @MethodSource("createSearchRequestAnswersTestsSupplier") - public void createSearchRequestAnswersTests(QueryAnswer queryAnswer, String expected) { - assertEquals(expected, SearchAsyncClient.createSearchRequestAnswers(queryAnswer)); - } - - static Stream createSearchRequestAnswersTestsSupplier() { - return Stream.of( - // No QueryAnswer provided returns null. - Arguments.of(null, null), - - // None returns none - Arguments.of(new QueryAnswer(QueryAnswerType.NONE), QueryAnswerType.NONE.toString()), - - // Only QueryAnswer provided returns the string value of QueryAnswer. - Arguments.of(new QueryAnswer(QueryAnswerType.EXTRACTIVE), QueryAnswerType.EXTRACTIVE.toString()), - - // Both QueryAnswer and count provided returns the concatenated string mentioned in docs. - Arguments.of(new QueryAnswer(QueryAnswerType.EXTRACTIVE).setCount(5), - QueryAnswerType.EXTRACTIVE + "|count-5"), - - Arguments.of(new QueryAnswer(QueryAnswerType.EXTRACTIVE).setThreshold(0.7), - QueryAnswerType.EXTRACTIVE + "|threshold-0.7"), - - Arguments.of(new QueryAnswer(QueryAnswerType.EXTRACTIVE).setCount(5).setThreshold(0.7), - QueryAnswerType.EXTRACTIVE + "|count-5,threshold-0.7")); - } - - @ParameterizedTest - @MethodSource("createSearchRequestCaptionsTestsSupplier") - public void createSearchRequestCaptionsTests(QueryCaption queryCaption, String expected) { - assertEquals(expected, SearchAsyncClient.createSearchRequestCaptions(queryCaption)); - } - - static Stream createSearchRequestCaptionsTestsSupplier() { - return Stream.of( - // No QueryCaption provided returns null. - Arguments.of(null, null), - - // None returns none - Arguments.of(new QueryCaption(QueryCaptionType.NONE), QueryCaptionType.NONE.toString()), - - // Only QueryCaption provided returns the string value of QueryCaption. - Arguments.of(new QueryCaption(QueryCaptionType.EXTRACTIVE), QueryAnswerType.EXTRACTIVE.toString()), - - // Both QueryCaption and highlight provided returns the concatenated string mentioned in docs. - Arguments.of(new QueryCaption(QueryCaptionType.EXTRACTIVE).setHighlightEnabled(true), - QueryAnswerType.EXTRACTIVE + "|highlight-true"), - Arguments.of(new QueryCaption(QueryCaptionType.EXTRACTIVE).setHighlightEnabled(false), - QueryAnswerType.EXTRACTIVE + "|highlight-false")); - } - - @ParameterizedTest - @MethodSource("createSearchRequestQueryRewriteTestsSupplier") - public void createSearchRequestQueryRewriteTests(QueryRewrites queryRewrites, String expected) { - assertEquals(expected, SearchAsyncClient.createQueryRewrites(queryRewrites)); - } - - static Stream createSearchRequestQueryRewriteTestsSupplier() { - return Stream.of( - // No QueryCaption provided returns null. - Arguments.of(null, null), - - // None returns none - Arguments.of(new QueryRewrites(QueryRewritesType.NONE), QueryRewritesType.NONE.toString()), - - // Only QueryRewrites provided returns the string value of QueryRewrites. - Arguments.of(new QueryRewrites(QueryRewritesType.GENERATIVE), QueryRewritesType.GENERATIVE.toString()), - - // Both QueryRewrites and count provided returns the concatenated string mentioned in docs. - Arguments.of(new QueryRewrites(QueryRewritesType.GENERATIVE).setCount(5), - QueryRewritesType.GENERATIVE + "|count-5")); - } - - @Test - public void queryRewritesFromString() { - assertEquals(new QueryRewrites(QueryRewritesType.NONE), QueryRewrites.fromString("none")); - assertEquals(new QueryRewrites(QueryRewritesType.GENERATIVE), QueryRewrites.fromString("generative")); - assertEquals(new QueryRewrites(QueryRewritesType.GENERATIVE).setCount(5), - QueryRewrites.fromString("generative|count-5")); - } - -} diff --git a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/VectorSearchEmbeddings.java b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/VectorSearchEmbeddings.java deleted file mode 100644 index ba0df2d1425d..000000000000 --- a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/VectorSearchEmbeddings.java +++ /dev/null @@ -1,52 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.search.documents; - -import com.azure.json.JsonProviders; -import com.azure.json.JsonReader; - -import java.io.IOException; -import java.io.InputStream; -import java.io.UncheckedIOException; -import java.util.List; -import java.util.Map; - -public class VectorSearchEmbeddings { - public static final List HOTEL1_VECTORIZE_DESCRIPTION; - public static final List HOTEL2_VECTORIZE_DESCRIPTION; - public static final List HOTEL3_VECTORIZE_DESCRIPTION; - public static final List HOTEL4_VECTORIZE_DESCRIPTION; - public static final List HOTEL5_VECTORIZE_DESCRIPTION; - public static final List HOTEL6_VECTORIZE_DESCRIPTION; - public static final List HOTEL7_VECTORIZE_DESCRIPTION; - public static final List HOTEL8_VECTORIZE_DESCRIPTION; - public static final List HOTEL9_VECTORIZE_DESCRIPTION; - public static final List HOTEL10_VECTORIZE_DESCRIPTION; - public static final List SEARCH_VECTORIZE_DESCRIPTION; - public static final List DEFAULT_VECTORIZE_DESCRIPTION; - - static { - InputStream stream - = VectorSearchEmbeddings.class.getClassLoader().getResourceAsStream("VectorSearchEmbeddings.json"); - - try (JsonReader jsonReader = JsonProviders.createReader(stream)) { - Map> embeddings = jsonReader.readMap(reader -> reader.readArray(JsonReader::getFloat)); - - HOTEL1_VECTORIZE_DESCRIPTION = embeddings.get("HOTEL1_VECTORIZE_DESCRIPTION"); - HOTEL2_VECTORIZE_DESCRIPTION = embeddings.get("HOTEL2_VECTORIZE_DESCRIPTION"); - HOTEL3_VECTORIZE_DESCRIPTION = embeddings.get("HOTEL3_VECTORIZE_DESCRIPTION"); - HOTEL4_VECTORIZE_DESCRIPTION = embeddings.get("HOTEL4_VECTORIZE_DESCRIPTION"); - HOTEL5_VECTORIZE_DESCRIPTION = embeddings.get("HOTEL5_VECTORIZE_DESCRIPTION"); - HOTEL6_VECTORIZE_DESCRIPTION = embeddings.get("HOTEL6_VECTORIZE_DESCRIPTION"); - HOTEL7_VECTORIZE_DESCRIPTION = embeddings.get("HOTEL7_VECTORIZE_DESCRIPTION"); - HOTEL8_VECTORIZE_DESCRIPTION = embeddings.get("HOTEL8_VECTORIZE_DESCRIPTION"); - HOTEL9_VECTORIZE_DESCRIPTION = embeddings.get("HOTEL9_VECTORIZE_DESCRIPTION"); - HOTEL10_VECTORIZE_DESCRIPTION = embeddings.get("HOTEL10_VECTORIZE_DESCRIPTION"); - SEARCH_VECTORIZE_DESCRIPTION = embeddings.get("SEARCH_VECTORIZE_DESCRIPTION"); - DEFAULT_VECTORIZE_DESCRIPTION = embeddings.get("DEFAULT_VECTORIZE_DESCRIPTION"); - } catch (IOException e) { - throw new UncheckedIOException(e); - } - } -} diff --git a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/VectorSearchTests.java b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/VectorSearchTests.java deleted file mode 100644 index b4b2cdfc7823..000000000000 --- a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/VectorSearchTests.java +++ /dev/null @@ -1,905 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.search.documents; - -import com.azure.core.models.GeoPoint; -import com.azure.core.test.TestMode; -import com.azure.core.test.TestProxyTestBase; -import com.azure.core.util.Context; -import com.azure.search.documents.implementation.util.SearchPagedResponseAccessHelper; -import com.azure.search.documents.indexes.SearchIndexAsyncClient; -import com.azure.search.documents.indexes.SearchIndexClient; -import com.azure.search.documents.indexes.SearchIndexClientBuilder; -import com.azure.search.documents.indexes.models.BinaryQuantizationCompression; -import com.azure.search.documents.indexes.models.DistanceScoringFunction; -import com.azure.search.documents.indexes.models.DistanceScoringParameters; -import com.azure.search.documents.indexes.models.HnswAlgorithmConfiguration; -import com.azure.search.documents.indexes.models.LexicalAnalyzerName; -import com.azure.search.documents.indexes.models.ScalarQuantizationCompression; -import com.azure.search.documents.indexes.models.ScoringFunctionAggregation; -import com.azure.search.documents.indexes.models.ScoringProfile; -import com.azure.search.documents.indexes.models.SearchField; -import com.azure.search.documents.indexes.models.SearchFieldDataType; -import com.azure.search.documents.indexes.models.SearchIndex; -import com.azure.search.documents.indexes.models.SearchSuggester; -import com.azure.search.documents.indexes.models.SemanticConfiguration; -import com.azure.search.documents.indexes.models.SemanticField; -import com.azure.search.documents.indexes.models.SemanticPrioritizedFields; -import com.azure.search.documents.indexes.models.SemanticSearch; -import com.azure.search.documents.indexes.models.VectorSearch; -import com.azure.search.documents.indexes.models.VectorSearchProfile; -import com.azure.search.documents.models.QueryAnswer; -import com.azure.search.documents.models.QueryAnswerType; -import com.azure.search.documents.models.QueryCaption; -import com.azure.search.documents.models.QueryCaptionType; -import com.azure.search.documents.models.QueryType; -import com.azure.search.documents.models.SearchOptions; -import com.azure.search.documents.models.SearchResult; -import com.azure.search.documents.models.SemanticSearchOptions; -import com.azure.search.documents.models.VectorSearchOptions; -import com.azure.search.documents.models.VectorizedQuery; -import com.azure.search.documents.test.environment.models.HotelAddress; -import com.azure.search.documents.test.environment.models.HotelRoom; -import com.azure.search.documents.test.environment.models.VectorHotel; -import com.azure.search.documents.util.SearchPagedResponse; -import org.junit.jupiter.api.AfterAll; -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.Disabled; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.parallel.Execution; -import org.junit.jupiter.api.parallel.ExecutionMode; -import reactor.core.publisher.Mono; -import reactor.test.StepVerifier; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.List; -import java.util.function.Function; -import java.util.stream.Collectors; - -import static com.azure.search.documents.TestHelpers.waitForIndexing; -import static org.junit.jupiter.api.Assertions.assertArrayEquals; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertNull; - -/** - * Tests Vector search functionality. - */ - -@Execution(ExecutionMode.SAME_THREAD) -public class VectorSearchTests extends SearchTestBase { - private static void assertKeysEqual(List results, Function keyAccessor, - String[] expectedKeys) { - assertArrayEquals(expectedKeys, results.stream().map(keyAccessor).toArray()); - } - - private static final String HOTEL_INDEX_NAME = "azsearch-vector-shared-hotel-instance"; - private static SearchIndexClient searchIndexClient; - - @BeforeAll - public static void setupClass() { - TestProxyTestBase.setupClass(); - - if (TEST_MODE == TestMode.PLAYBACK) { - return; - } - - searchIndexClient = new SearchIndexClientBuilder().endpoint(ENDPOINT) - .credential(TestHelpers.getTestTokenCredential()) - .retryPolicy(SERVICE_THROTTLE_SAFE_RETRY_POLICY) - .buildClient(); - - searchIndexClient.createIndex(getVectorIndex()); - - searchIndexClient.getSearchClient(HOTEL_INDEX_NAME).uploadDocuments(VECTORIZED_HOTELS); - - waitForIndexing(); - } - - @AfterAll - protected static void cleanupClass() { - if (TEST_MODE != TestMode.PLAYBACK) { - searchIndexClient.deleteIndex(HOTEL_INDEX_NAME); - - try { - Thread.sleep(5000); - } catch (InterruptedException ex) { - throw new RuntimeException(ex); - } - } - } - - private final List indexesToDelete = new ArrayList<>(); - - @AfterEach - public void deleteIndexes() { - if (TEST_MODE != TestMode.PLAYBACK) { - for (String index : indexesToDelete) { - searchIndexClient.deleteIndex(index); - } - } - } - - @Test - public void singleVectorSearchAsync() { - SearchAsyncClient searchClient = getSearchClientBuilder(HOTEL_INDEX_NAME, false).buildAsyncClient(); - waitForIndexing(); - SearchOptions searchOptions = new SearchOptions().setVectorSearchOptions(new VectorSearchOptions().setQueries( - new VectorizedQuery(VectorSearchEmbeddings.SEARCH_VECTORIZE_DESCRIPTION).setKNearestNeighborsCount(3) - .setFields("DescriptionVector"))) - .setSelect("HotelId", "HotelName"); - - StepVerifier.create(searchClient.search(null, searchOptions).collectList()) - .assertNext(results -> assertKeysEqual(results, - r -> (String) r.getDocument(SearchDocument.class).get("HotelId"), new String[] { "3", "5", "1" })) - .verifyComplete(); - } - - @Test - public void singleVectorSearchSync() { - SearchClient searchClient = getSearchClientBuilder(HOTEL_INDEX_NAME, true).buildClient(); - waitForIndexing(); - SearchOptions searchOptions = new SearchOptions().setVectorSearchOptions(new VectorSearchOptions().setQueries( - new VectorizedQuery(VectorSearchEmbeddings.SEARCH_VECTORIZE_DESCRIPTION).setKNearestNeighborsCount(3) - .setFields("DescriptionVector"))) - .setSelect("HotelId", "HotelName"); - - List results - = searchClient.search(null, searchOptions, Context.NONE).stream().collect(Collectors.toList()); - - assertKeysEqual(results, r -> (String) r.getDocument(SearchDocument.class).get("HotelId"), - new String[] { "3", "5", "1" }); - } - - @Test - public void singleVectorSearchWithFilterAsync() { - SearchAsyncClient searchClient = getSearchClientBuilder(HOTEL_INDEX_NAME, false).buildAsyncClient(); - waitForIndexing(); - SearchOptions searchOptions = new SearchOptions() - .setVectorSearchOptions(new VectorSearchOptions().setQueries( - new VectorizedQuery(VectorSearchEmbeddings.SEARCH_VECTORIZE_DESCRIPTION).setKNearestNeighborsCount(3) - .setFields("DescriptionVector"))) - .setSelect("HotelId", "HotelName", "Category") - .setFilter("Category eq 'Budget'"); - - StepVerifier.create(searchClient.search(null, searchOptions).collectList()) - .assertNext(results -> assertKeysEqual(results, - r -> (String) r.getDocument(SearchDocument.class).get("HotelId"), new String[] { "3", "5", "4" })) - .verifyComplete(); - } - - @Test - public void singleVectorSearchWithFilterSync() { - SearchClient searchClient = getSearchClientBuilder(HOTEL_INDEX_NAME, true).buildClient(); - waitForIndexing(); - SearchOptions searchOptions = new SearchOptions() - .setVectorSearchOptions(new VectorSearchOptions().setQueries( - new VectorizedQuery(VectorSearchEmbeddings.SEARCH_VECTORIZE_DESCRIPTION).setKNearestNeighborsCount(3) - .setFields("DescriptionVector"))) - .setSelect("HotelId", "HotelName", "Category") - .setFilter("Category eq 'Budget'"); - - List results - = searchClient.search(null, searchOptions, Context.NONE).stream().collect(Collectors.toList()); - - assertKeysEqual(results, r -> (String) r.getDocument(SearchDocument.class).get("HotelId"), - new String[] { "3", "5", "4" }); - } - - @Test - public void simpleHybridSearchAsync() { - SearchAsyncClient searchClient = getSearchClientBuilder(HOTEL_INDEX_NAME, false).buildAsyncClient(); - waitForIndexing(); - SearchOptions searchOptions = new SearchOptions().setVectorSearchOptions(new VectorSearchOptions().setQueries( - new VectorizedQuery(VectorSearchEmbeddings.SEARCH_VECTORIZE_DESCRIPTION).setKNearestNeighborsCount(3) - .setFields("DescriptionVector"))) - .setSelect("HotelId", "HotelName"); - - StepVerifier.create(searchClient.search("Top hotels in town", searchOptions).collectList()) - .assertNext( - results -> assertKeysEqual(results, r -> (String) r.getDocument(SearchDocument.class).get("HotelId"), - new String[] { "3", "1", "5", "2", "10", "4", "9" })) - .verifyComplete(); - } - - @Test - public void simpleHybridSearchSync() { - SearchClient searchClient = getSearchClientBuilder(HOTEL_INDEX_NAME, true).buildClient(); - waitForIndexing(); - SearchOptions searchOptions = new SearchOptions().setVectorSearchOptions(new VectorSearchOptions().setQueries( - new VectorizedQuery(VectorSearchEmbeddings.SEARCH_VECTORIZE_DESCRIPTION).setKNearestNeighborsCount(3) - .setFields("DescriptionVector"))) - .setSelect("HotelId", "HotelName"); - - List results = searchClient.search("Top hotels in town", searchOptions, Context.NONE) - .stream() - .collect(Collectors.toList()); - - assertKeysEqual(results, r -> (String) r.getDocument(SearchDocument.class).get("HotelId"), - new String[] { "3", "1", "5", "2", "10", "4", "9" }); - } - - @Test - @Disabled("Need to get manual recordings as this doesn't work with all SKUs or regions.") - public void semanticHybridSearchAsync() { - SearchAsyncClient searchClient = getSearchClientBuilder(HOTEL_INDEX_NAME, false).buildAsyncClient(); - - SearchOptions searchOptions = new SearchOptions() - .setVectorSearchOptions(new VectorSearchOptions().setQueries( - new VectorizedQuery(VectorSearchEmbeddings.SEARCH_VECTORIZE_DESCRIPTION).setKNearestNeighborsCount(3) - .setFields("DescriptionVector"))) - .setSelect("HotelId", "HotelName", "Description", "Category") - .setQueryType(QueryType.SEMANTIC) - .setSemanticSearchOptions(new SemanticSearchOptions().setSemanticConfigurationName("my-semantic-config") - .setQueryCaption(new QueryCaption(QueryCaptionType.EXTRACTIVE)) - .setQueryAnswer(new QueryAnswer(QueryAnswerType.EXTRACTIVE))); - - StepVerifier.create(searchClient - .search("Is there any hotel located on the main commercial artery of the city in the heart of New York?", - searchOptions) - .byPage() - .collectList()).assertNext(pages -> { - SearchPagedResponse page1 = pages.get(0); - assertNotNull(SearchPagedResponseAccessHelper.getQueryAnswers(page1)); - assertEquals(1, SearchPagedResponseAccessHelper.getQueryAnswers(page1).size()); - assertEquals("9", SearchPagedResponseAccessHelper.getQueryAnswers(page1).get(0).getKey()); - assertNotNull(SearchPagedResponseAccessHelper.getQueryAnswers(page1).get(0).getHighlights()); - assertNotNull(SearchPagedResponseAccessHelper.getQueryAnswers(page1).get(0).getText()); - - List results = new ArrayList<>(); - for (SearchPagedResponse page : pages) { - for (SearchResult result : page.getValue()) { - results.add(result); - - assertNotNull(result.getSemanticSearch().getQueryCaptions()); - assertNotNull(result.getSemanticSearch().getQueryCaptions().get(0).getHighlights()); - assertNotNull(result.getSemanticSearch().getQueryCaptions().get(0).getText()); - } - } - - assertKeysEqual(results, r -> (String) r.getDocument(SearchDocument.class).get("HotelId"), - new String[] { "9", "3", "2", "5", "10", "1", "4" }); - }).verifyComplete(); - } - - @Test - @Disabled("Need to get manual recordings as this doesn't work with all SKUs or regions.") - public void semanticHybridSearchSync() { - SearchClient searchClient = getSearchClientBuilder(HOTEL_INDEX_NAME, true).buildClient(); - waitForIndexing(); - SearchOptions searchOptions = new SearchOptions() - .setVectorSearchOptions(new VectorSearchOptions().setQueries( - new VectorizedQuery(VectorSearchEmbeddings.SEARCH_VECTORIZE_DESCRIPTION).setKNearestNeighborsCount(3) - .setFields("DescriptionVector"))) - .setSelect("HotelId", "HotelName", "Description", "Category") - .setQueryType(QueryType.SEMANTIC) - .setSemanticSearchOptions(new SemanticSearchOptions().setSemanticConfigurationName("my-semantic-config") - .setQueryCaption(new QueryCaption(QueryCaptionType.EXTRACTIVE)) - .setQueryAnswer(new QueryAnswer(QueryAnswerType.EXTRACTIVE))); - - List pages = searchClient - .search("Is there any hotel located on the main commercial artery of the city in the heart of New York?", - searchOptions, Context.NONE) - .streamByPage() - .collect(Collectors.toList()); - - SearchPagedResponse page1 = pages.get(0); - assertNotNull(SearchPagedResponseAccessHelper.getQueryAnswers(page1)); - assertEquals(1, SearchPagedResponseAccessHelper.getQueryAnswers(page1).size()); - assertEquals("9", SearchPagedResponseAccessHelper.getQueryAnswers(page1).get(0).getKey()); - assertNotNull(SearchPagedResponseAccessHelper.getQueryAnswers(page1).get(0).getHighlights()); - assertNotNull(SearchPagedResponseAccessHelper.getQueryAnswers(page1).get(0).getText()); - - List results = new ArrayList<>(); - for (SearchPagedResponse page : pages) { - for (SearchResult result : page.getValue()) { - results.add(result); - - assertNotNull(result.getSemanticSearch().getQueryCaptions()); - assertNotNull(result.getSemanticSearch().getQueryCaptions().get(0).getHighlights()); - assertNotNull(result.getSemanticSearch().getQueryCaptions().get(0).getText()); - } - } - - assertKeysEqual(results, r -> (String) r.getDocument(SearchDocument.class).get("HotelId"), - new String[] { "9", "3", "2", "5", "10", "1", "4" }); - } - - @SuppressWarnings("unchecked") - @Test - public void updateExistingIndexToAddVectorFieldsAsync() { - String indexName = randomIndexName("addvectorasync"); - SearchIndex searchIndex - = new SearchIndex(indexName).setFields(new SearchField("Id", SearchFieldDataType.STRING).setKey(true), - new SearchField("Name", SearchFieldDataType.STRING).setSearchable(true).setFilterable(true)); - - SearchIndexAsyncClient searchIndexClient = getSearchIndexClientBuilder(false).buildAsyncClient(); - searchIndexClient.createIndex(searchIndex).block(); - indexesToDelete.add(indexName); - - // Upload data - SearchDocument document = new SearchDocument(); - document.put("Id", "1"); - document.put("Name", "Countryside Hotel"); - - SearchAsyncClient searchClient = searchIndexClient.getSearchAsyncClient(indexName); - searchClient.uploadDocuments(Collections.singletonList(document)).block(); - - waitForIndexing(); - - // Get the document - StepVerifier.create(searchClient.getDocument("1", SearchDocument.class)).assertNext(response -> { - assertEquals(document.get("Id"), response.get("Id")); - assertEquals(document.get("Name"), response.get("Name")); - }).verifyComplete(); - - // Update created index to add vector field - - // Get created index - Mono getAndUpdateIndex = searchIndexClient.getIndex(indexName).flatMap(createdIndex -> { - // Add vector - SearchField vectorField - = new SearchField("DescriptionVector", SearchFieldDataType.collection(SearchFieldDataType.SINGLE)) - .setSearchable(true) - .setHidden(false) - .setVectorSearchDimensions(1536) - .setVectorSearchProfileName("my-vector-profile"); - - createdIndex.getFields().add(vectorField); - - createdIndex.setVectorSearch(new VectorSearch() - .setProfiles( - Collections.singletonList(new VectorSearchProfile("my-vector-profile", "my-vector-config"))) - .setAlgorithms(Collections.singletonList(new HnswAlgorithmConfiguration("my-vector-config")))); - - return searchIndexClient.createOrUpdateIndex(createdIndex); - }); - - // Update index - StepVerifier.create(getAndUpdateIndex).assertNext(response -> { - assertEquals(indexName, response.getName()); - assertEquals(3, response.getFields().size()); - }).verifyComplete(); - - // Update document to add vector field's data - - // Get the document - Mono getAndUpdateDocument - = searchClient.getDocument("1", SearchDocument.class).flatMap(resultDoc -> { - // Update document to add vector field data - resultDoc.put("DescriptionVector", VectorSearchEmbeddings.DEFAULT_VECTORIZE_DESCRIPTION); - return searchClient.mergeDocuments(Collections.singletonList(resultDoc)); - - }).flatMap(ignored -> { - // Equivalent of 'waitForIndexing()' where in PLAYBACK getting the document is called right away, - // but for LIVE and RECORD it waits two seconds for the document to be available. - if (TEST_MODE == TestMode.PLAYBACK) { - return searchClient.getDocument("1", SearchDocument.class); - } else { - waitForIndexing(); - return searchClient.getDocument("1", SearchDocument.class); - } - }); - - // Get the document - StepVerifier.create(getAndUpdateDocument).assertNext(response -> { - assertEquals(document.get("Id"), response.get("Id")); - assertEquals(document.get("Name"), response.get("Name")); - assertNotNull(response.get("DescriptionVector")); - compareFloatListToDeserializedFloatList(VectorSearchEmbeddings.DEFAULT_VECTORIZE_DESCRIPTION, - (List) response.get("DescriptionVector")); - }).verifyComplete(); - } - - @SuppressWarnings("unchecked") - @Test - public void updateExistingIndexToAddVectorFieldsSync() { - String indexName = randomIndexName("addvectorsync"); - SearchIndex searchIndex - = new SearchIndex(indexName).setFields(new SearchField("Id", SearchFieldDataType.STRING).setKey(true), - new SearchField("Name", SearchFieldDataType.STRING).setSearchable(true).setFilterable(true)); - - SearchIndexClient searchIndexClient = getSearchIndexClientBuilder(true).buildClient(); - searchIndexClient.createIndex(searchIndex); - indexesToDelete.add(indexName); - // Upload data - SearchDocument document = new SearchDocument(); - document.put("Id", "1"); - document.put("Name", "Countryside Hotel"); - - SearchClient searchClient = searchIndexClient.getSearchClient(indexName); - searchClient.uploadDocuments(Collections.singletonList(document)); - - waitForIndexing(); - - // Get the document - SearchDocument responseDocument = searchClient.getDocument("1", SearchDocument.class); - - assertEquals(document.get("Id"), responseDocument.get("Id")); - assertEquals(document.get("Name"), responseDocument.get("Name")); - - // Update created index to add vector field - - // Get created index - SearchIndex createdIndex = searchIndexClient.getIndex(indexName); - - // Add vector - SearchField vectorField - = new SearchField("DescriptionVector", SearchFieldDataType.collection(SearchFieldDataType.SINGLE)) - .setSearchable(true) - .setHidden(false) - .setVectorSearchDimensions(1536) - .setVectorSearchProfileName("my-vector-profile"); - - createdIndex.getFields().add(vectorField); - - createdIndex.setVectorSearch(new VectorSearch() - .setProfiles(Collections.singletonList(new VectorSearchProfile("my-vector-profile", "my-vector-config"))) - .setAlgorithms(Collections.singletonList(new HnswAlgorithmConfiguration("my-vector-config")))); - - // Update index - SearchIndex responseIndex = searchIndexClient.createOrUpdateIndex(createdIndex); - - assertEquals(indexName, responseIndex.getName()); - assertEquals(3, responseIndex.getFields().size()); - - // Update document to add vector field's data - - // Get the document - SearchDocument resultDoc = searchClient.getDocument("1", SearchDocument.class); - - // Update document to add vector field data - resultDoc.put("DescriptionVector", VectorSearchEmbeddings.DEFAULT_VECTORIZE_DESCRIPTION); - - searchClient.mergeDocuments(Collections.singletonList(resultDoc)); - waitForIndexing(); - - // Get the document - responseDocument = searchClient.getDocument("1", SearchDocument.class); - - assertEquals(document.get("Id"), responseDocument.get("Id")); - assertEquals(document.get("Name"), responseDocument.get("Name")); - compareFloatListToDeserializedFloatList(VectorSearchEmbeddings.DEFAULT_VECTORIZE_DESCRIPTION, - (List) responseDocument.get("DescriptionVector")); - } - - // create a test that synchronously tests the ability to use VectorSearchCompression.truncationDimension to reduce the dimensionality of the vector - @SuppressWarnings("unchecked") - @Test - public void testVectorSearchCompressionTruncationDimensionSync() { - // create a new index with a vector field - String indexName = randomIndexName("compressiontruncationdimension"); - String compressionName = "vector-compression-100"; - - SearchIndex searchIndex = new SearchIndex(indexName) - .setFields(new SearchField("Id", SearchFieldDataType.STRING).setKey(true), - new SearchField("Name", SearchFieldDataType.STRING).setSearchable(true).setFilterable(true), - new SearchField("DescriptionVector", SearchFieldDataType.collection(SearchFieldDataType.SINGLE)) - .setSearchable(true) - .setHidden(false) - .setVectorSearchDimensions(1536) - .setVectorSearchProfileName("my-vector-profile")) - .setVectorSearch(new VectorSearch() - .setProfiles( - Collections.singletonList(new VectorSearchProfile("my-vector-profile", "my-vector-config"))) - .setAlgorithms(Collections.singletonList(new HnswAlgorithmConfiguration("my-vector-config"))) - .setCompressions(new BinaryQuantizationCompression(compressionName).setTruncationDimension(100))); - - SearchIndexClient searchIndexClient = getSearchIndexClientBuilder(true).buildClient(); - searchIndexClient.createIndex(searchIndex); - - indexesToDelete.add(indexName); - - SearchIndex retrievedIndex = searchIndexClient.getIndex(indexName); - assertEquals(1, retrievedIndex.getVectorSearch().getCompressions().size()); - assertEquals(compressionName, retrievedIndex.getVectorSearch().getCompressions().get(0).getCompressionName()); - - } - - // create a test that asynchronously tests the ability to use VectorSearchCompression.truncationDimension to reduce the dimensionality of the vector - @SuppressWarnings("unchecked") - @Test - public void testVectorSearchCompressionTruncationDimensionAsync() { - // create a new index with a vector field - String indexName = randomIndexName("compressiontruncationdimensionasync"); - String compressionName = "vector-compression-100"; - - SearchIndex searchIndex = new SearchIndex(indexName) - .setFields(new SearchField("Id", SearchFieldDataType.STRING).setKey(true), - new SearchField("Name", SearchFieldDataType.STRING).setSearchable(true).setFilterable(true), - new SearchField("DescriptionVector", SearchFieldDataType.collection(SearchFieldDataType.SINGLE)) - .setSearchable(true) - .setHidden(false) - .setVectorSearchDimensions(1536) - .setVectorSearchProfileName("my-vector-profile")) - .setVectorSearch(new VectorSearch() - .setProfiles( - Collections.singletonList(new VectorSearchProfile("my-vector-profile", "my-vector-config"))) - .setAlgorithms(Collections.singletonList(new HnswAlgorithmConfiguration("my-vector-config"))) - .setCompressions(new ScalarQuantizationCompression(compressionName).setTruncationDimension(100))); - - SearchIndexAsyncClient searchIndexAsyncClient = getSearchIndexClientBuilder(false).buildAsyncClient(); - searchIndexAsyncClient.createIndex(searchIndex).block(); - waitForIndexing(); - indexesToDelete.add(indexName); - - StepVerifier.create(searchIndexAsyncClient.getIndex(indexName)).assertNext(retrievedIndex -> { - assertEquals(1, retrievedIndex.getVectorSearch().getCompressions().size()); - assertEquals(compressionName, - retrievedIndex.getVectorSearch().getCompressions().get(0).getCompressionName()); - }).verifyComplete(); - } - - // write a test that asynchronously tests the ability to upload a vector field to an index using BinaryQuantizationCompression - @SuppressWarnings("unchecked") - @Test - public void testVectorSearchCompressionBinaryQuantizationAsync() { - // create a new index with a vector field - String indexName = randomIndexName("compressionbinaryquantizationasync"); - String compressionName = "binary-vector-compression"; - - SearchIndex searchIndex - = new SearchIndex(indexName) - .setFields(new SearchField("Id", SearchFieldDataType.STRING).setKey(true), - new SearchField("Name", SearchFieldDataType.STRING) - .setSearchable(true) - .setFilterable(true), - new SearchField("BinaryCompressedVector", - SearchFieldDataType.collection(SearchFieldDataType.SINGLE)).setSearchable(true) - .setHidden(false) - .setVectorSearchDimensions(5) - .setVectorSearchProfileName("my-vector-profile")) - .setVectorSearch(new VectorSearch() - .setProfiles( - Collections.singletonList(new VectorSearchProfile("my-vector-profile", "my-vector-config"))) - .setAlgorithms(Collections.singletonList(new HnswAlgorithmConfiguration("my-vector-config"))) - .setCompressions(new BinaryQuantizationCompression(compressionName))); - - SearchIndexAsyncClient searchIndexAsyncClient = getSearchIndexClientBuilder(false).buildAsyncClient(); - searchIndexAsyncClient.createIndex(searchIndex).block(); - indexesToDelete.add(indexName); - - StepVerifier.create(searchIndexAsyncClient.getIndex(indexName)).assertNext(retrievedIndex -> { - assertEquals(1, retrievedIndex.getVectorSearch().getCompressions().size()); - assertEquals(compressionName, - retrievedIndex.getVectorSearch().getCompressions().get(0).getCompressionName()); - }).verifyComplete(); - } - - // write a test that synchronously tests the ability to upload a vector field to an index using BinaryQuantizationCompression - @SuppressWarnings("unchecked") - @Test - public void testVectorSearchCompressionBinaryQuantizationSync() { - // create a new index with a vector field - String indexName = randomIndexName("compressionbinaryquantizationsync"); - String compressionName = "binary-vector-compression"; - - SearchIndex searchIndex - = new SearchIndex(indexName) - .setFields(new SearchField("Id", SearchFieldDataType.STRING).setKey(true), - new SearchField("Name", SearchFieldDataType.STRING) - .setSearchable(true) - .setFilterable(true), - new SearchField("BinaryCompressedVector", - SearchFieldDataType.collection(SearchFieldDataType.SINGLE)).setSearchable(true) - .setHidden(false) - .setVectorSearchDimensions(5) - .setVectorSearchProfileName("my-vector-profile")) - .setVectorSearch(new VectorSearch() - .setProfiles( - Collections.singletonList(new VectorSearchProfile("my-vector-profile", "my-vector-config"))) - .setAlgorithms(Collections.singletonList(new HnswAlgorithmConfiguration("my-vector-config"))) - .setCompressions(new BinaryQuantizationCompression(compressionName))); - - SearchIndexClient searchIndexClient = getSearchIndexClientBuilder(true).buildClient(); - searchIndexClient.createIndex(searchIndex); - indexesToDelete.add(indexName); - - SearchIndex retrievedIndex = searchIndexClient.getIndex(indexName); - assertEquals(1, retrievedIndex.getVectorSearch().getCompressions().size()); - assertEquals(compressionName, retrievedIndex.getVectorSearch().getCompressions().get(0).getCompressionName()); - } - - // a test that creates a hybrid search query with a vector search query and a regular search query, and utilizes the vector query - // fiter override to filter the vector search results - @Test - public void testHybridSearchWithVectorFilterOverride() { - // create a new index with a vector field - - // create a hybrid search query with a vector search query and a regular search query - SearchOptions searchOptions = new SearchOptions().setFilter("Rating ge 3") - .setSelect("HotelId", "HotelName", "Rating") - .setVectorSearchOptions(new VectorSearchOptions().setQueries( - new VectorizedQuery(VectorSearchEmbeddings.DEFAULT_VECTORIZE_DESCRIPTION).setFields("DescriptionVector") - .setFilterOverride("HotelId eq '1'"))); - - // run the hybrid search query - SearchClient searchClient = getSearchClientBuilder(HOTEL_INDEX_NAME, true).buildClient(); - List results - = searchClient.search("fancy", searchOptions, Context.NONE).stream().collect(Collectors.toList()); - - // check that the results are as expected - assertEquals(1, results.size()); - assertEquals("1", results.get(0).getDocument(SearchDocument.class).get("HotelId")); - - } - - private static void compareFloatListToDeserializedFloatList(List expected, List actual) { - if (actual == null) { - assertNull(expected); - return; - } - - assertEquals(expected.size(), actual.size()); - - Object obj = actual.get(0); - if (obj instanceof Float || obj instanceof Double) { - for (int i = 0; i < expected.size(); i++) { - assertEquals(expected.get(i), actual.get(i).floatValue()); - } - } else { - throw new IllegalStateException( - "Deserialization of a float list returned an unexpected type. Type was: " + obj.getClass().getName()); - } - } - - private static SearchIndex getVectorIndex() { - return new SearchIndex(HOTEL_INDEX_NAME) - .setFields( - new SearchField("HotelId", SearchFieldDataType.STRING).setKey(true) - .setFilterable(true) - .setSortable(true) - .setFacetable(true), - new SearchField("HotelName", SearchFieldDataType.STRING).setSearchable(true) - .setFilterable(true) - .setSortable(true), - new SearchField("Description", SearchFieldDataType.STRING).setSearchable(true) - .setAnalyzerName(LexicalAnalyzerName.EN_LUCENE), - new SearchField("Description_fr", SearchFieldDataType.STRING).setSearchable(true) - .setAnalyzerName(LexicalAnalyzerName.FR_LUCENE), - new SearchField("DescriptionVector", SearchFieldDataType.collection(SearchFieldDataType.SINGLE)) - .setSearchable(true) - .setVectorSearchDimensions(1536) - .setVectorSearchProfileName("my-vector-profile"), - new SearchField("Category", SearchFieldDataType.STRING).setSearchable(true) - .setFilterable(true) - .setFacetable(true) - .setSortable(true), - new SearchField("Tags", SearchFieldDataType.collection(SearchFieldDataType.STRING)).setSearchable(true) - .setFilterable(true) - .setFacetable(true), - new SearchField("ParkingIncluded", SearchFieldDataType.BOOLEAN).setFilterable(true) - .setFacetable(true) - .setSortable(true), - new SearchField("SmokingAllowed", SearchFieldDataType.BOOLEAN).setFilterable(true) - .setFacetable(true) - .setSortable(true), - new SearchField("LastRenovationDate", SearchFieldDataType.DATE_TIME_OFFSET).setFilterable(true) - .setFacetable(true) - .setSortable(true), - new SearchField("Rating", SearchFieldDataType.INT32).setFilterable(true) - .setFacetable(true) - .setSortable(true), - new SearchField("Location", SearchFieldDataType.GEOGRAPHY_POINT).setFilterable(true).setSortable(true), - new SearchField("Address", SearchFieldDataType.COMPLEX).setFields( - new SearchField("StreetAddress", SearchFieldDataType.STRING).setSearchable(true), - new SearchField("City", SearchFieldDataType.STRING).setSearchable(true) - .setFilterable(true) - .setFacetable(true) - .setSortable(true), - new SearchField("StateProvince", SearchFieldDataType.STRING).setSearchable(true) - .setFilterable(true) - .setFacetable(true) - .setSortable(true), - new SearchField("Country", SearchFieldDataType.STRING).setSearchable(true) - .setFilterable(true) - .setFacetable(true) - .setSortable(true), - new SearchField("PostalCode", SearchFieldDataType.STRING).setSearchable(true) - .setFilterable(true) - .setFacetable(true) - .setSortable(true)), - new SearchField("Rooms", SearchFieldDataType.collection(SearchFieldDataType.COMPLEX)).setFields( - new SearchField("Description", SearchFieldDataType.STRING).setSearchable(true) - .setAnalyzerName(LexicalAnalyzerName.EN_LUCENE), - new SearchField("Description_fr", SearchFieldDataType.STRING).setSearchable(true) - .setAnalyzerName(LexicalAnalyzerName.FR_LUCENE), - new SearchField("Type", SearchFieldDataType.STRING).setSearchable(true) - .setFilterable(true) - .setFacetable(true), - new SearchField("BaseRate", SearchFieldDataType.DOUBLE).setFilterable(true).setFacetable(true), - new SearchField("BedOptions", SearchFieldDataType.STRING) - .setSearchable(true) - .setFilterable(true) - .setFacetable(true), - new SearchField("SleepsCount", SearchFieldDataType.INT32) - .setFilterable(true) - .setFacetable(true), - new SearchField("SmokingAllowed", SearchFieldDataType.BOOLEAN).setFilterable(true) - .setFacetable(true), - new SearchField("Tags", SearchFieldDataType.collection(SearchFieldDataType.STRING)) - .setSearchable(true) - .setFilterable(true) - .setFacetable(true))) - .setVectorSearch(new VectorSearch() - .setProfiles( - Collections.singletonList(new VectorSearchProfile("my-vector-profile", "my-vector-config"))) - .setAlgorithms(Collections.singletonList(new HnswAlgorithmConfiguration("my-vector-config")))) - .setSemanticSearch(new SemanticSearch() - .setConfigurations(Collections.singletonList(new SemanticConfiguration("my-semantic-config", - new SemanticPrioritizedFields().setTitleField(new SemanticField("HotelName")) - .setContentFields(Collections.singletonList(new SemanticField("Description"))) - .setKeywordsFields(Collections.singletonList(new SemanticField("Category"))))))) - .setSuggesters(new SearchSuggester("sg", Arrays.asList("Description", "HotelName"))) - .setScoringProfiles(new ScoringProfile("nearest").setFunctionAggregation(ScoringFunctionAggregation.SUM) - .setFunctions(new DistanceScoringFunction("Location", 2, new DistanceScoringParameters("myloc", 100)))); - } - - /* - * Hotels with vectorized data. - */ - private static final List VECTORIZED_HOTELS = Arrays.asList( - new VectorHotel().hotelId("1") - .description("Best hotel in town if you like luxury hotels. They have an amazing infinity pool, a spa, and " - + "a really helpful concierge. The location is perfect -- right downtown, close to all the tourist " - + "attractions. We highly recommend this hotel.") - .descriptionFr("Meilleur hôtel en ville si vous aimez les hôtels de luxe. Ils ont une magnifique piscine à " - + "débordement, un spa et un concierge très utile. L'emplacement est parfait – en plein centre, à " - + "proximité de toutes les attractions touristiques. Nous recommandons fortement cet hôtel.") - .descriptionVector(VectorSearchEmbeddings.HOTEL1_VECTORIZE_DESCRIPTION) - .hotelName("Fancy Stay") - .category("Luxury") - .tags(Arrays.asList("pool", "view", "wifi", "concierge")) - .parkingIncluded(false) - .smokingAllowed(false) - .lastRenovationDate(parseDate("2010-06-27T00:00:00Z")) - .rating(5) - .location(new GeoPoint(-122.131577, 47.678581)), - new VectorHotel().hotelId("2") - .description("Cheapest hotel in town. Infact, a motel.") - .descriptionFr("Hôtel le moins cher en ville. Infact, un motel.") - .descriptionVector(VectorSearchEmbeddings.HOTEL2_VECTORIZE_DESCRIPTION) - .hotelName("Roach Motel") - .category("Budget") - .tags(Arrays.asList("motel", "budget")) - .parkingIncluded(true) - .smokingAllowed(true) - .lastRenovationDate(parseDate("1982-04-28T00:00:00Z")) - .rating(1) - .location(new GeoPoint(-122.131577, 49.678581)), - new VectorHotel().hotelId("3") - .description("Very popular hotel in town") - .descriptionFr("Hôtel le plus populaire en ville") - .descriptionVector(VectorSearchEmbeddings.HOTEL3_VECTORIZE_DESCRIPTION) - .hotelName("EconoStay") - .category("Budget") - .tags(Arrays.asList("wifi", "budget")) - .parkingIncluded(true) - .smokingAllowed(false) - .lastRenovationDate(parseDate("1995-07-01T00:00:00Z")) - .rating(4) - .location(new GeoPoint(-122.131577, 46.678581)), - new VectorHotel().hotelId("4") - .description("Pretty good hotel") - .descriptionFr("Assez bon hôtel") - .descriptionVector(VectorSearchEmbeddings.HOTEL4_VECTORIZE_DESCRIPTION) - .hotelName("Express Rooms") - .category("Budget") - .tags(Arrays.asList("wifi", "budget")) - .parkingIncluded(true) - .smokingAllowed(false) - .lastRenovationDate(parseDate("1995-07-01T00:00:00Z")) - .rating(4) - .location(new GeoPoint(-122.131577, 48.678581)), - new VectorHotel().hotelId("5") - .description("Another good hotel") - .descriptionFr("Un autre bon hôtel") - .descriptionVector(VectorSearchEmbeddings.HOTEL5_VECTORIZE_DESCRIPTION) - .hotelName("Comfy Place") - .category("Budget") - .tags(Arrays.asList("wifi", "budget")) - .parkingIncluded(true) - .smokingAllowed(false) - .lastRenovationDate(parseDate("2012-08-12T00:00:00Z")) - .rating(4) - .location(new GeoPoint(-122.131577, 48.678581)) - .address(new HotelAddress().streetAddress("677 5th Ave") - .city("NEW YORK") - .stateProvince("NY") - .country("USA") - .postalCode("10022")), - new VectorHotel().hotelId("6") - .description("Surprisingly expensive. Model suites have an ocean-view.") - .descriptionVector(VectorSearchEmbeddings.HOTEL6_VECTORIZE_DESCRIPTION) - .lastRenovationDate(null), - new VectorHotel().hotelId("7") - .description("Modern architecture, very polite staff and very clean. Also very affordable.") - .descriptionFr("Architecture moderne, personnel poli et très propre. Aussi très abordable.") - .descriptionVector(VectorSearchEmbeddings.HOTEL7_VECTORIZE_DESCRIPTION) - .hotelName("Modern Stay"), - new VectorHotel().hotelId("8") - .description("Has some road noise and is next to the very police station. Bathrooms had morel coverings.") - .descriptionFr("Il y a du bruit de la route et se trouve à côté de la station de police. Les salles de " - + "bain avaient des revêtements de morilles.") - .descriptionVector(VectorSearchEmbeddings.HOTEL8_VECTORIZE_DESCRIPTION), - new VectorHotel().hotelId("9") - .hotelName("Secret Point Motel") - .description("The hotel is ideally located on the main commercial artery of the city in the heart of " - + "New York. A few minutes away is Time's Square and the historic centre of the city, as well as other " - + "places of interest that make New York one of America's most attractive and cosmopolitan cities.") - .descriptionFr("L'hôtel est idéalement situé sur la principale artère commerciale de la ville en plein " - + "cœur de New York. A quelques minutes se trouve la place du temps et le centre historique de la " - + "ville, ainsi que d'autres lieux d'intérêt qui font de New York l'une des villes les plus " - + "attractives et cosmopolites de l'Amérique.") - .descriptionVector(VectorSearchEmbeddings.HOTEL9_VECTORIZE_DESCRIPTION) - .category("Boutique") - .tags(Arrays.asList("pool", "air conditioning", "concierge")) - .parkingIncluded(false) - .smokingAllowed(true) - .lastRenovationDate(parseDate("1970-01-18T00:00:00Z")) - .rating(4) - .location(new GeoPoint(-73.97332, 40.763843)) - .address(new HotelAddress().streetAddress("677 5th Ave") - .city("New York") - .stateProvince("NY") - .country("USA") - .postalCode("10022")) - .rooms(Arrays.asList( - new HotelRoom().description("Budget Room, 1 Queen Bed (Cityside)") - .descriptionFr("Chambre Économique, 1 grand lit (côté ville)") - .type("Budget Room") - .baseRate(9.69) - .bedOptions("1 Queen Bed") - .sleepsCount(2) - .smokingAllowed(true) - .tags(new String[] { "vcr/dvd" }), - new HotelRoom().description("Budget Room, 1 King Bed (Mountain View)") - .descriptionFr("Chambre Économique, 1 très grand lit (Mountain View)") - .type("Budget Room") - .baseRate(8.09) - .bedOptions("1 King Bed") - .sleepsCount(2) - .smokingAllowed(true) - .tags(new String[] { "vcr/dvd", "jacuzzi tub" }))), - new VectorHotel().hotelId("10") - .hotelName("Countryside Hotel") - .description("Save up to 50% off traditional hotels. Free WiFi, great location near downtown, full " - + "kitchen, washer & dryer, 24/7 support, bowling alley, fitness center and more.") - .descriptionFr("Économisez jusqu'à 50% sur les hôtels traditionnels. WiFi gratuit, très bien situé près " - + "du centre-ville, cuisine complète, laveuse & sécheuse, support 24/7, bowling, centre de fitness et " - + "plus encore.") - .descriptionVector(VectorSearchEmbeddings.HOTEL10_VECTORIZE_DESCRIPTION) - .category("Budget") - .tags(Arrays.asList("24-hour front desk service", "coffee in lobby", "restaurant")) - .parkingIncluded(false) - .smokingAllowed(true) - .lastRenovationDate(parseDate("1999-09-06T00:00:00Z")) - .rating(3) - .location(new GeoPoint(-78.940483, 35.904160)) - .address(new HotelAddress().streetAddress("6910 Fayetteville Rd") - .city("Durham") - .stateProvince("NC") - .country("USA") - .postalCode("27713")) - .rooms(Arrays.asList( - new HotelRoom().description("Suite, 1 King Bed (Amenities)") - .descriptionFr("Suite, 1 très grand lit (Services)") - .type("Suite") - .baseRate(2.44) - .bedOptions("1 King Bed") - .sleepsCount(2) - .smokingAllowed(true) - .tags(new String[] { "coffee maker" }), - new HotelRoom().description("Budget Room, 1 Queen Bed (Amenities)") - .descriptionFr("Chambre Économique, 1 grand lit (Services)") - .type("Budget Room") - .baseRate(7.69) - .bedOptions("1 Queen Bed") - .sleepsCount(2) - .smokingAllowed(false) - .tags(new String[] { "coffee maker" })))); -} diff --git a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/generated/SearchClientTestBase.java b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/generated/SearchClientTestBase.java new file mode 100644 index 000000000000..4bc4aac70c55 --- /dev/null +++ b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/generated/SearchClientTestBase.java @@ -0,0 +1,160 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.search.documents.generated; + +// The Java test files under 'generated' package are generated for your reference. +// If you wish to modify these files, please copy them out of the 'generated' package, and modify there. +// See https://aka.ms/azsdk/dpg/java/tests for guide on adding a test. + +import com.azure.core.http.policy.HttpLogDetailLevel; +import com.azure.core.http.policy.HttpLogOptions; +import com.azure.core.test.TestMode; +import com.azure.core.test.TestProxyTestBase; +import com.azure.core.test.utils.MockTokenCredential; +import com.azure.core.util.Configuration; +import com.azure.identity.DefaultAzureCredentialBuilder; +import com.azure.search.documents.AliasesClient; +import com.azure.search.documents.DataSourcesClient; +import com.azure.search.documents.DocumentsClient; +import com.azure.search.documents.IndexersClient; +import com.azure.search.documents.IndexesClient; +import com.azure.search.documents.SearchClient; +import com.azure.search.documents.SearchClientBuilder; +import com.azure.search.documents.SkillsetsClient; +import com.azure.search.documents.SynonymMapsClient; + +class SearchClientTestBase extends TestProxyTestBase { + protected SearchClient searchClient; + + protected DataSourcesClient dataSourcesClient; + + protected IndexersClient indexersClient; + + protected SkillsetsClient skillsetsClient; + + protected SynonymMapsClient synonymMapsClient; + + protected IndexesClient indexesClient; + + protected AliasesClient aliasesClient; + + protected DocumentsClient documentsClient; + + @Override + protected void beforeTest() { + SearchClientBuilder searchClientbuilder + = new SearchClientBuilder().endpoint(Configuration.getGlobalConfiguration().get("ENDPOINT", "endpoint")) + .httpClient(getHttpClientOrUsePlayback(getHttpClients().findFirst().orElse(null))) + .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BASIC)); + if (getTestMode() == TestMode.PLAYBACK) { + searchClientbuilder.credential(new MockTokenCredential()); + } else if (getTestMode() == TestMode.RECORD) { + searchClientbuilder.addPolicy(interceptorManager.getRecordPolicy()) + .credential(new DefaultAzureCredentialBuilder().build()); + } else if (getTestMode() == TestMode.LIVE) { + searchClientbuilder.credential(new DefaultAzureCredentialBuilder().build()); + } + searchClient = searchClientbuilder.buildClient(); + + SearchClientBuilder dataSourcesClientbuilder + = new SearchClientBuilder().endpoint(Configuration.getGlobalConfiguration().get("ENDPOINT", "endpoint")) + .httpClient(getHttpClientOrUsePlayback(getHttpClients().findFirst().orElse(null))) + .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BASIC)); + if (getTestMode() == TestMode.PLAYBACK) { + dataSourcesClientbuilder.credential(new MockTokenCredential()); + } else if (getTestMode() == TestMode.RECORD) { + dataSourcesClientbuilder.addPolicy(interceptorManager.getRecordPolicy()) + .credential(new DefaultAzureCredentialBuilder().build()); + } else if (getTestMode() == TestMode.LIVE) { + dataSourcesClientbuilder.credential(new DefaultAzureCredentialBuilder().build()); + } + dataSourcesClient = dataSourcesClientbuilder.buildDataSourcesClient(); + + SearchClientBuilder indexersClientbuilder + = new SearchClientBuilder().endpoint(Configuration.getGlobalConfiguration().get("ENDPOINT", "endpoint")) + .httpClient(getHttpClientOrUsePlayback(getHttpClients().findFirst().orElse(null))) + .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BASIC)); + if (getTestMode() == TestMode.PLAYBACK) { + indexersClientbuilder.credential(new MockTokenCredential()); + } else if (getTestMode() == TestMode.RECORD) { + indexersClientbuilder.addPolicy(interceptorManager.getRecordPolicy()) + .credential(new DefaultAzureCredentialBuilder().build()); + } else if (getTestMode() == TestMode.LIVE) { + indexersClientbuilder.credential(new DefaultAzureCredentialBuilder().build()); + } + indexersClient = indexersClientbuilder.buildIndexersClient(); + + SearchClientBuilder skillsetsClientbuilder + = new SearchClientBuilder().endpoint(Configuration.getGlobalConfiguration().get("ENDPOINT", "endpoint")) + .httpClient(getHttpClientOrUsePlayback(getHttpClients().findFirst().orElse(null))) + .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BASIC)); + if (getTestMode() == TestMode.PLAYBACK) { + skillsetsClientbuilder.credential(new MockTokenCredential()); + } else if (getTestMode() == TestMode.RECORD) { + skillsetsClientbuilder.addPolicy(interceptorManager.getRecordPolicy()) + .credential(new DefaultAzureCredentialBuilder().build()); + } else if (getTestMode() == TestMode.LIVE) { + skillsetsClientbuilder.credential(new DefaultAzureCredentialBuilder().build()); + } + skillsetsClient = skillsetsClientbuilder.buildSkillsetsClient(); + + SearchClientBuilder synonymMapsClientbuilder + = new SearchClientBuilder().endpoint(Configuration.getGlobalConfiguration().get("ENDPOINT", "endpoint")) + .httpClient(getHttpClientOrUsePlayback(getHttpClients().findFirst().orElse(null))) + .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BASIC)); + if (getTestMode() == TestMode.PLAYBACK) { + synonymMapsClientbuilder.credential(new MockTokenCredential()); + } else if (getTestMode() == TestMode.RECORD) { + synonymMapsClientbuilder.addPolicy(interceptorManager.getRecordPolicy()) + .credential(new DefaultAzureCredentialBuilder().build()); + } else if (getTestMode() == TestMode.LIVE) { + synonymMapsClientbuilder.credential(new DefaultAzureCredentialBuilder().build()); + } + synonymMapsClient = synonymMapsClientbuilder.buildSynonymMapsClient(); + + SearchClientBuilder indexesClientbuilder + = new SearchClientBuilder().endpoint(Configuration.getGlobalConfiguration().get("ENDPOINT", "endpoint")) + .httpClient(getHttpClientOrUsePlayback(getHttpClients().findFirst().orElse(null))) + .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BASIC)); + if (getTestMode() == TestMode.PLAYBACK) { + indexesClientbuilder.credential(new MockTokenCredential()); + } else if (getTestMode() == TestMode.RECORD) { + indexesClientbuilder.addPolicy(interceptorManager.getRecordPolicy()) + .credential(new DefaultAzureCredentialBuilder().build()); + } else if (getTestMode() == TestMode.LIVE) { + indexesClientbuilder.credential(new DefaultAzureCredentialBuilder().build()); + } + indexesClient = indexesClientbuilder.buildIndexesClient(); + + SearchClientBuilder aliasesClientbuilder + = new SearchClientBuilder().endpoint(Configuration.getGlobalConfiguration().get("ENDPOINT", "endpoint")) + .httpClient(getHttpClientOrUsePlayback(getHttpClients().findFirst().orElse(null))) + .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BASIC)); + if (getTestMode() == TestMode.PLAYBACK) { + aliasesClientbuilder.credential(new MockTokenCredential()); + } else if (getTestMode() == TestMode.RECORD) { + aliasesClientbuilder.addPolicy(interceptorManager.getRecordPolicy()) + .credential(new DefaultAzureCredentialBuilder().build()); + } else if (getTestMode() == TestMode.LIVE) { + aliasesClientbuilder.credential(new DefaultAzureCredentialBuilder().build()); + } + aliasesClient = aliasesClientbuilder.buildAliasesClient(); + + SearchClientBuilder documentsClientbuilder + = new SearchClientBuilder().endpoint(Configuration.getGlobalConfiguration().get("ENDPOINT", "endpoint")) + .httpClient(getHttpClientOrUsePlayback(getHttpClients().findFirst().orElse(null))) + .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BASIC)); + if (getTestMode() == TestMode.PLAYBACK) { + documentsClientbuilder.credential(new MockTokenCredential()); + } else if (getTestMode() == TestMode.RECORD) { + documentsClientbuilder.addPolicy(interceptorManager.getRecordPolicy()) + .credential(new DefaultAzureCredentialBuilder().build()); + } else if (getTestMode() == TestMode.LIVE) { + documentsClientbuilder.credential(new DefaultAzureCredentialBuilder().build()); + } + documentsClient = documentsClientbuilder.buildDocumentsClient(); + + } +} diff --git a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/generated/SearchIndexAutocompleteDocumentsGetTests.java b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/generated/SearchIndexAutocompleteDocumentsGetTests.java new file mode 100644 index 000000000000..4fe745738bc6 --- /dev/null +++ b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/generated/SearchIndexAutocompleteDocumentsGetTests.java @@ -0,0 +1,27 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.search.documents.generated; + +import com.azure.search.documents.models.AutocompleteMode; +import com.azure.search.documents.models.AutocompleteResult; +import java.util.Arrays; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + +@Disabled +public final class SearchIndexAutocompleteDocumentsGetTests extends SearchClientTestBase { + @Test + @Disabled + public void testSearchIndexAutocompleteDocumentsGetTests() { + // method invocation + AutocompleteResult response + = documentsClient.autocompleteGet("washington medic", "sg", "myindex", AutocompleteMode.ONE_TERM, null, + false, "", "", 80.0D, Arrays.asList("title", "description"), null); + + // response assertion + Assertions.assertNotNull(response); + } +} diff --git a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/generated/SearchIndexAutocompleteDocumentsPostTests.java b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/generated/SearchIndexAutocompleteDocumentsPostTests.java new file mode 100644 index 000000000000..db291470a8a8 --- /dev/null +++ b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/generated/SearchIndexAutocompleteDocumentsPostTests.java @@ -0,0 +1,43 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.search.documents.generated; + +import com.azure.search.documents.models.AutocompleteItem; +import com.azure.search.documents.models.AutocompleteMode; +import com.azure.search.documents.models.AutocompleteRequest; +import com.azure.search.documents.models.AutocompleteResult; +import java.util.List; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + +@Disabled +public final class SearchIndexAutocompleteDocumentsPostTests extends SearchClientTestBase { + @Test + @Disabled + public void testSearchIndexAutocompleteDocumentsPostTests() { + // method invocation + AutocompleteResult response = documentsClient.autocompletePost("preview-test", + new AutocompleteRequest("p", "sg").setAutocompleteMode(AutocompleteMode.ONE_TERM) + .setFilter("ownerId ne '1'") + .setUseFuzzyMatching(true) + .setHighlightPostTag("") + .setHighlightPreTag("") + .setMinimumCoverage(80.0D) + .setSearchFields("category, ownerId") + .setTop(10)); + + // response assertion + Assertions.assertNotNull(response); + // verify property "coverage" + Assertions.assertEquals(100.0D, response.getCoverage()); + // verify property "results" + List responseResults = response.getResults(); + AutocompleteItem responseResultsFirstItem = responseResults.iterator().next(); + Assertions.assertNotNull(responseResultsFirstItem); + Assertions.assertEquals("purple", responseResultsFirstItem.getText()); + Assertions.assertEquals("purple", responseResultsFirstItem.getQueryPlusText()); + } +} diff --git a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/generated/SearchIndexCountDocumentsTests.java b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/generated/SearchIndexCountDocumentsTests.java new file mode 100644 index 000000000000..895c5745967c --- /dev/null +++ b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/generated/SearchIndexCountDocumentsTests.java @@ -0,0 +1,22 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.search.documents.generated; + +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + +@Disabled +public final class SearchIndexCountDocumentsTests extends SearchClientTestBase { + @Test + @Disabled + public void testSearchIndexCountDocumentsTests() { + // method invocation + int response = documentsClient.count("preview-test"); + + // response assertion + Assertions.assertEquals(50, response); + } +} diff --git a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/generated/SearchIndexGetDocumentTests.java b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/generated/SearchIndexGetDocumentTests.java new file mode 100644 index 000000000000..bb3d88ea07e2 --- /dev/null +++ b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/generated/SearchIndexGetDocumentTests.java @@ -0,0 +1,25 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.search.documents.generated; + +import com.azure.search.documents.models.LookupDocument; +import java.util.Arrays; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + +@Disabled +public final class SearchIndexGetDocumentTests extends SearchClientTestBase { + @Test + @Disabled + public void testSearchIndexGetDocumentTests() { + // method invocation + LookupDocument response = documentsClient.get("1", "preview-test", + Arrays.asList("id", "description", "name", "category", "ownerId")); + + // response assertion + Assertions.assertNotNull(response); + } +} diff --git a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/generated/SearchIndexIndexDocumentsTests.java b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/generated/SearchIndexIndexDocumentsTests.java new file mode 100644 index 000000000000..b608c8b1d8cd --- /dev/null +++ b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/generated/SearchIndexIndexDocumentsTests.java @@ -0,0 +1,737 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.search.documents.generated; + +import com.azure.core.util.BinaryData; +import com.azure.search.documents.models.IndexAction; +import com.azure.search.documents.models.IndexBatch; +import com.azure.search.documents.models.IndexDocumentsResult; +import com.azure.search.documents.models.IndexingResult; +import java.nio.charset.StandardCharsets; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + +@Disabled +public final class SearchIndexIndexDocumentsTests extends SearchClientTestBase { + @Test + @Disabled + public void testSearchIndexIndexDocumentsTests() { + // method invocation + IndexDocumentsResult response = documentsClient.index("preview-test", new IndexBatch(Arrays.asList( + new IndexAction().setAdditionalProperties(mapOf("vector1b", + BinaryData.fromBytes("[10, 11, 12, 13, 14, 15, 16, 17, 18, 19]".getBytes(StandardCharsets.UTF_8)), + "vector3", BinaryData.fromBytes("[0, 1, 2, 3, 4]".getBytes(StandardCharsets.UTF_8)), "@search.action", + BinaryData.fromBytes("mergeOrUpload".getBytes(StandardCharsets.UTF_8)), "vector22", + BinaryData.fromBytes("[20, 21, 22, 23, 24, 25, 26, 27, 28, 29]".getBytes(StandardCharsets.UTF_8)), + "price", BinaryData.fromBytes("0".getBytes(StandardCharsets.UTF_8)), "name", + BinaryData.fromBytes("test".getBytes(StandardCharsets.UTF_8)), "description", + BinaryData.fromBytes("test0 hello".getBytes(StandardCharsets.UTF_8)), "id", + BinaryData.fromBytes("0".getBytes(StandardCharsets.UTF_8)), "vector1", + BinaryData.fromBytes("[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]" + .getBytes(StandardCharsets.UTF_8)), + "ownerId", BinaryData.fromBytes("benny".getBytes(StandardCharsets.UTF_8)), "category", + BinaryData.fromBytes("purple".getBytes(StandardCharsets.UTF_8)), "vector2", + BinaryData.fromBytes("[0, 1, 2, 3, 4]".getBytes(StandardCharsets.UTF_8)))), + new IndexAction().setAdditionalProperties(mapOf("vector1b", + BinaryData.fromBytes("[11, 12, 13, 14, 15, 16, 17, 18, 19, 20]".getBytes(StandardCharsets.UTF_8)), + "vector3", BinaryData.fromBytes("[1, 2, 3, 4, 5]".getBytes(StandardCharsets.UTF_8)), "@search.action", + BinaryData.fromBytes("mergeOrUpload".getBytes(StandardCharsets.UTF_8)), "vector22", + BinaryData.fromBytes("[21, 22, 23, 24, 25, 26, 27, 28, 29, 30]".getBytes(StandardCharsets.UTF_8)), + "price", BinaryData.fromBytes("1".getBytes(StandardCharsets.UTF_8)), "name", + BinaryData.fromBytes("test".getBytes(StandardCharsets.UTF_8)), "description", + BinaryData.fromBytes("test1 hello".getBytes(StandardCharsets.UTF_8)), "id", + BinaryData.fromBytes("1".getBytes(StandardCharsets.UTF_8)), "vector1", + BinaryData.fromBytes("[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]" + .getBytes(StandardCharsets.UTF_8)), + "ownerId", BinaryData.fromBytes("sam".getBytes(StandardCharsets.UTF_8)), "category", + BinaryData.fromBytes("purple".getBytes(StandardCharsets.UTF_8)), "vector2", + BinaryData.fromBytes("[1, 2, 3, 4, 5]".getBytes(StandardCharsets.UTF_8)))), + new IndexAction().setAdditionalProperties(mapOf("vector1b", + BinaryData.fromBytes("[12, 13, 14, 15, 16, 17, 18, 19, 20, 21]".getBytes(StandardCharsets.UTF_8)), + "vector3", BinaryData.fromBytes("[2, 3, 4, 5, 6]".getBytes(StandardCharsets.UTF_8)), "@search.action", + BinaryData.fromBytes("mergeOrUpload".getBytes(StandardCharsets.UTF_8)), "vector22", + BinaryData.fromBytes("[22, 23, 24, 25, 26, 27, 28, 29, 30, 31]".getBytes(StandardCharsets.UTF_8)), + "price", BinaryData.fromBytes("2".getBytes(StandardCharsets.UTF_8)), "name", + BinaryData.fromBytes("test".getBytes(StandardCharsets.UTF_8)), "description", + BinaryData.fromBytes("test2 hello".getBytes(StandardCharsets.UTF_8)), "id", + BinaryData.fromBytes("2".getBytes(StandardCharsets.UTF_8)), "vector1", + BinaryData.fromBytes("[2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21]" + .getBytes(StandardCharsets.UTF_8)), + "ownerId", BinaryData.fromBytes("sam".getBytes(StandardCharsets.UTF_8)), "category", + BinaryData.fromBytes("purple".getBytes(StandardCharsets.UTF_8)), "vector2", + BinaryData.fromBytes("[2, 3, 4, 5, 6]".getBytes(StandardCharsets.UTF_8)))), + new IndexAction().setAdditionalProperties(mapOf("vector1b", + BinaryData.fromBytes("[13, 14, 15, 16, 17, 18, 19, 20, 21, 22]".getBytes(StandardCharsets.UTF_8)), + "vector3", BinaryData.fromBytes("[3, 4, 5, 6, 7]".getBytes(StandardCharsets.UTF_8)), "@search.action", + BinaryData.fromBytes("mergeOrUpload".getBytes(StandardCharsets.UTF_8)), "vector22", + BinaryData.fromBytes("[23, 24, 25, 26, 27, 28, 29, 30, 31, 32]".getBytes(StandardCharsets.UTF_8)), + "price", BinaryData.fromBytes("3".getBytes(StandardCharsets.UTF_8)), "name", + BinaryData.fromBytes("test".getBytes(StandardCharsets.UTF_8)), "description", + BinaryData.fromBytes("test3 hello".getBytes(StandardCharsets.UTF_8)), "id", + BinaryData.fromBytes("3".getBytes(StandardCharsets.UTF_8)), "vector1", + BinaryData.fromBytes("[3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22]" + .getBytes(StandardCharsets.UTF_8)), + "ownerId", BinaryData.fromBytes("ryan".getBytes(StandardCharsets.UTF_8)), "category", + BinaryData.fromBytes("purple".getBytes(StandardCharsets.UTF_8)), "vector2", + BinaryData.fromBytes("[3, 4, 5, 6, 7]".getBytes(StandardCharsets.UTF_8)))), + new IndexAction().setAdditionalProperties(mapOf("vector1b", + BinaryData.fromBytes("[14, 15, 16, 17, 18, 19, 20, 21, 22, 23]".getBytes(StandardCharsets.UTF_8)), + "vector3", BinaryData.fromBytes("[4, 5, 6, 7, 8]".getBytes(StandardCharsets.UTF_8)), "@search.action", + BinaryData.fromBytes("mergeOrUpload".getBytes(StandardCharsets.UTF_8)), "vector22", + BinaryData.fromBytes("[24, 25, 26, 27, 28, 29, 30, 31, 32, 33]".getBytes(StandardCharsets.UTF_8)), + "price", BinaryData.fromBytes("4".getBytes(StandardCharsets.UTF_8)), "name", + BinaryData.fromBytes("test".getBytes(StandardCharsets.UTF_8)), "description", + BinaryData.fromBytes("test4 hello".getBytes(StandardCharsets.UTF_8)), "id", + BinaryData.fromBytes("4".getBytes(StandardCharsets.UTF_8)), "vector1", + BinaryData.fromBytes("[4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23]" + .getBytes(StandardCharsets.UTF_8)), + "ownerId", BinaryData.fromBytes("sam".getBytes(StandardCharsets.UTF_8)), "category", + BinaryData.fromBytes("purple".getBytes(StandardCharsets.UTF_8)), "vector2", + BinaryData.fromBytes("[4, 5, 6, 7, 8]".getBytes(StandardCharsets.UTF_8)))), + new IndexAction().setAdditionalProperties(mapOf("vector1b", + BinaryData.fromBytes("[15, 16, 17, 18, 19, 20, 21, 22, 23, 24]".getBytes(StandardCharsets.UTF_8)), + "vector3", BinaryData.fromBytes("[5, 6, 7, 8, 9]".getBytes(StandardCharsets.UTF_8)), "@search.action", + BinaryData.fromBytes("mergeOrUpload".getBytes(StandardCharsets.UTF_8)), "vector22", + BinaryData.fromBytes("[25, 26, 27, 28, 29, 30, 31, 32, 33, 34]".getBytes(StandardCharsets.UTF_8)), + "price", BinaryData.fromBytes("5".getBytes(StandardCharsets.UTF_8)), "name", + BinaryData.fromBytes("test".getBytes(StandardCharsets.UTF_8)), "description", + BinaryData.fromBytes("test5 hello".getBytes(StandardCharsets.UTF_8)), "id", + BinaryData.fromBytes("5".getBytes(StandardCharsets.UTF_8)), "vector1", + BinaryData.fromBytes("[5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24]" + .getBytes(StandardCharsets.UTF_8)), + "ownerId", BinaryData.fromBytes("sam".getBytes(StandardCharsets.UTF_8)), "category", + BinaryData.fromBytes("purple".getBytes(StandardCharsets.UTF_8)), "vector2", + BinaryData.fromBytes("[5, 6, 7, 8, 9]".getBytes(StandardCharsets.UTF_8)))), + new IndexAction().setAdditionalProperties(mapOf("vector1b", + BinaryData.fromBytes("[16, 17, 18, 19, 20, 21, 22, 23, 24, 25]".getBytes(StandardCharsets.UTF_8)), + "vector3", BinaryData.fromBytes("[6, 7, 8, 9, 10]".getBytes(StandardCharsets.UTF_8)), "@search.action", + BinaryData.fromBytes("mergeOrUpload".getBytes(StandardCharsets.UTF_8)), "vector22", + BinaryData.fromBytes("[26, 27, 28, 29, 30, 31, 32, 33, 34, 35]".getBytes(StandardCharsets.UTF_8)), + "price", BinaryData.fromBytes("6".getBytes(StandardCharsets.UTF_8)), "name", + BinaryData.fromBytes("test".getBytes(StandardCharsets.UTF_8)), "description", + BinaryData.fromBytes("test6 hello".getBytes(StandardCharsets.UTF_8)), "id", + BinaryData.fromBytes("6".getBytes(StandardCharsets.UTF_8)), "vector1", + BinaryData.fromBytes("[6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25]" + .getBytes(StandardCharsets.UTF_8)), + "ownerId", BinaryData.fromBytes("ryan".getBytes(StandardCharsets.UTF_8)), "category", + BinaryData.fromBytes("purple".getBytes(StandardCharsets.UTF_8)), "vector2", + BinaryData.fromBytes("[6, 7, 8, 9, 10]".getBytes(StandardCharsets.UTF_8)))), + new IndexAction().setAdditionalProperties(mapOf("vector1b", + BinaryData.fromBytes("[17, 18, 19, 20, 21, 22, 23, 24, 25, 26]".getBytes(StandardCharsets.UTF_8)), + "vector3", BinaryData.fromBytes("[7, 8, 9, 10, 11]".getBytes(StandardCharsets.UTF_8)), "@search.action", + BinaryData.fromBytes("mergeOrUpload".getBytes(StandardCharsets.UTF_8)), "vector22", + BinaryData.fromBytes("[27, 28, 29, 30, 31, 32, 33, 34, 35, 36]".getBytes(StandardCharsets.UTF_8)), + "price", BinaryData.fromBytes("7".getBytes(StandardCharsets.UTF_8)), "name", + BinaryData.fromBytes("test".getBytes(StandardCharsets.UTF_8)), "description", + BinaryData.fromBytes("test7 hello".getBytes(StandardCharsets.UTF_8)), "id", + BinaryData.fromBytes("7".getBytes(StandardCharsets.UTF_8)), "vector1", + BinaryData.fromBytes("[7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26]" + .getBytes(StandardCharsets.UTF_8)), + "ownerId", BinaryData.fromBytes("sam".getBytes(StandardCharsets.UTF_8)), "category", + BinaryData.fromBytes("purple".getBytes(StandardCharsets.UTF_8)), "vector2", + BinaryData.fromBytes("[7, 8, 9, 10, 11]".getBytes(StandardCharsets.UTF_8)))), + new IndexAction().setAdditionalProperties(mapOf("vector1b", + BinaryData.fromBytes("[18, 19, 20, 21, 22, 23, 24, 25, 26, 27]".getBytes(StandardCharsets.UTF_8)), + "vector3", BinaryData.fromBytes("[8, 9, 10, 11, 12]".getBytes(StandardCharsets.UTF_8)), + "@search.action", BinaryData.fromBytes("mergeOrUpload".getBytes(StandardCharsets.UTF_8)), "vector22", + BinaryData.fromBytes("[28, 29, 30, 31, 32, 33, 34, 35, 36, 37]".getBytes(StandardCharsets.UTF_8)), + "price", BinaryData.fromBytes("8".getBytes(StandardCharsets.UTF_8)), "name", + BinaryData.fromBytes("test".getBytes(StandardCharsets.UTF_8)), "description", + BinaryData.fromBytes("test8 hello".getBytes(StandardCharsets.UTF_8)), "id", + BinaryData.fromBytes("8".getBytes(StandardCharsets.UTF_8)), "vector1", + BinaryData.fromBytes("[8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27]" + .getBytes(StandardCharsets.UTF_8)), + "ownerId", BinaryData.fromBytes("sam".getBytes(StandardCharsets.UTF_8)), "category", + BinaryData.fromBytes("purple".getBytes(StandardCharsets.UTF_8)), "vector2", + BinaryData.fromBytes("[8, 9, 10, 11, 12]".getBytes(StandardCharsets.UTF_8)))), + new IndexAction().setAdditionalProperties(mapOf("vector1b", + BinaryData.fromBytes("[19, 20, 21, 22, 23, 24, 25, 26, 27, 28]".getBytes(StandardCharsets.UTF_8)), + "vector3", BinaryData.fromBytes("[9, 10, 11, 12, 13]".getBytes(StandardCharsets.UTF_8)), + "@search.action", BinaryData.fromBytes("mergeOrUpload".getBytes(StandardCharsets.UTF_8)), "vector22", + BinaryData.fromBytes("[29, 30, 31, 32, 33, 34, 35, 36, 37, 38]".getBytes(StandardCharsets.UTF_8)), + "price", BinaryData.fromBytes("9".getBytes(StandardCharsets.UTF_8)), "name", + BinaryData.fromBytes("test".getBytes(StandardCharsets.UTF_8)), "description", + BinaryData.fromBytes("test9 hello".getBytes(StandardCharsets.UTF_8)), "id", + BinaryData.fromBytes("9".getBytes(StandardCharsets.UTF_8)), "vector1", + BinaryData.fromBytes("[9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28]" + .getBytes(StandardCharsets.UTF_8)), + "ownerId", BinaryData.fromBytes("ryan".getBytes(StandardCharsets.UTF_8)), "category", + BinaryData.fromBytes("purple".getBytes(StandardCharsets.UTF_8)), "vector2", + BinaryData.fromBytes("[9, 10, 11, 12, 13]".getBytes(StandardCharsets.UTF_8)))), + new IndexAction().setAdditionalProperties(mapOf("vector1b", + BinaryData.fromBytes("[20, 21, 22, 23, 24, 25, 26, 27, 28, 29]".getBytes(StandardCharsets.UTF_8)), + "vector3", BinaryData.fromBytes("[10, 11, 12, 13, 14]".getBytes(StandardCharsets.UTF_8)), + "@search.action", BinaryData.fromBytes("mergeOrUpload".getBytes(StandardCharsets.UTF_8)), "vector22", + BinaryData.fromBytes("[30, 31, 32, 33, 34, 35, 36, 37, 38, 39]".getBytes(StandardCharsets.UTF_8)), + "price", BinaryData.fromBytes("10".getBytes(StandardCharsets.UTF_8)), "name", + BinaryData.fromBytes("test".getBytes(StandardCharsets.UTF_8)), "description", + BinaryData.fromBytes("test10 hello".getBytes(StandardCharsets.UTF_8)), "id", + BinaryData.fromBytes("10".getBytes(StandardCharsets.UTF_8)), "vector1", + BinaryData.fromBytes("[10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29]" + .getBytes(StandardCharsets.UTF_8)), + "ownerId", BinaryData.fromBytes("benny".getBytes(StandardCharsets.UTF_8)), "category", + BinaryData.fromBytes("purple".getBytes(StandardCharsets.UTF_8)), "vector2", + BinaryData.fromBytes("[10, 11, 12, 13, 14]".getBytes(StandardCharsets.UTF_8)))), + new IndexAction().setAdditionalProperties(mapOf("vector1b", + BinaryData.fromBytes("[21, 22, 23, 24, 25, 26, 27, 28, 29, 30]".getBytes(StandardCharsets.UTF_8)), + "vector3", BinaryData.fromBytes("[11, 12, 13, 14, 15]".getBytes(StandardCharsets.UTF_8)), + "@search.action", BinaryData.fromBytes("mergeOrUpload".getBytes(StandardCharsets.UTF_8)), "vector22", + BinaryData.fromBytes("[31, 32, 33, 34, 35, 36, 37, 38, 39, 40]".getBytes(StandardCharsets.UTF_8)), + "price", BinaryData.fromBytes("11".getBytes(StandardCharsets.UTF_8)), "name", + BinaryData.fromBytes("test".getBytes(StandardCharsets.UTF_8)), "description", + BinaryData.fromBytes("test11 hello".getBytes(StandardCharsets.UTF_8)), "id", + BinaryData.fromBytes("11".getBytes(StandardCharsets.UTF_8)), "vector1", + BinaryData.fromBytes("[11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30]" + .getBytes(StandardCharsets.UTF_8)), + "ownerId", BinaryData.fromBytes("sam".getBytes(StandardCharsets.UTF_8)), "category", + BinaryData.fromBytes("purple".getBytes(StandardCharsets.UTF_8)), "vector2", + BinaryData.fromBytes("[11, 12, 13, 14, 15]".getBytes(StandardCharsets.UTF_8)))), + new IndexAction().setAdditionalProperties(mapOf("vector1b", + BinaryData.fromBytes("[22, 23, 24, 25, 26, 27, 28, 29, 30, 31]".getBytes(StandardCharsets.UTF_8)), + "vector3", BinaryData.fromBytes("[12, 13, 14, 15, 16]".getBytes(StandardCharsets.UTF_8)), + "@search.action", BinaryData.fromBytes("mergeOrUpload".getBytes(StandardCharsets.UTF_8)), "vector22", + BinaryData.fromBytes("[32, 33, 34, 35, 36, 37, 38, 39, 40, 41]".getBytes(StandardCharsets.UTF_8)), + "price", BinaryData.fromBytes("12".getBytes(StandardCharsets.UTF_8)), "name", + BinaryData.fromBytes("test".getBytes(StandardCharsets.UTF_8)), "description", + BinaryData.fromBytes("test12 hello".getBytes(StandardCharsets.UTF_8)), "id", + BinaryData.fromBytes("12".getBytes(StandardCharsets.UTF_8)), "vector1", + BinaryData.fromBytes("[12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31]" + .getBytes(StandardCharsets.UTF_8)), + "ownerId", BinaryData.fromBytes("ryan".getBytes(StandardCharsets.UTF_8)), "category", + BinaryData.fromBytes("purple".getBytes(StandardCharsets.UTF_8)), "vector2", + BinaryData.fromBytes("[12, 13, 14, 15, 16]".getBytes(StandardCharsets.UTF_8)))), + new IndexAction().setAdditionalProperties(mapOf("vector1b", + BinaryData.fromBytes("[23, 24, 25, 26, 27, 28, 29, 30, 31, 32]".getBytes(StandardCharsets.UTF_8)), + "vector3", BinaryData.fromBytes("[13, 14, 15, 16, 17]".getBytes(StandardCharsets.UTF_8)), + "@search.action", BinaryData.fromBytes("mergeOrUpload".getBytes(StandardCharsets.UTF_8)), "vector22", + BinaryData.fromBytes("[33, 34, 35, 36, 37, 38, 39, 40, 41, 42]".getBytes(StandardCharsets.UTF_8)), + "price", BinaryData.fromBytes("13".getBytes(StandardCharsets.UTF_8)), "name", + BinaryData.fromBytes("test".getBytes(StandardCharsets.UTF_8)), "description", + BinaryData.fromBytes("test13 hello".getBytes(StandardCharsets.UTF_8)), "id", + BinaryData.fromBytes("13".getBytes(StandardCharsets.UTF_8)), "vector1", + BinaryData.fromBytes("[13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32]" + .getBytes(StandardCharsets.UTF_8)), + "ownerId", BinaryData.fromBytes("sam".getBytes(StandardCharsets.UTF_8)), "category", + BinaryData.fromBytes("purple".getBytes(StandardCharsets.UTF_8)), "vector2", + BinaryData.fromBytes("[13, 14, 15, 16, 17]".getBytes(StandardCharsets.UTF_8)))), + new IndexAction().setAdditionalProperties(mapOf("vector1b", + BinaryData.fromBytes("[24, 25, 26, 27, 28, 29, 30, 31, 32, 33]".getBytes(StandardCharsets.UTF_8)), + "vector3", BinaryData.fromBytes("[14, 15, 16, 17, 18]".getBytes(StandardCharsets.UTF_8)), + "@search.action", BinaryData.fromBytes("mergeOrUpload".getBytes(StandardCharsets.UTF_8)), "vector22", + BinaryData.fromBytes("[34, 35, 36, 37, 38, 39, 40, 41, 42, 43]".getBytes(StandardCharsets.UTF_8)), + "price", BinaryData.fromBytes("14".getBytes(StandardCharsets.UTF_8)), "name", + BinaryData.fromBytes("test".getBytes(StandardCharsets.UTF_8)), "description", + BinaryData.fromBytes("test14 hello".getBytes(StandardCharsets.UTF_8)), "id", + BinaryData.fromBytes("14".getBytes(StandardCharsets.UTF_8)), "vector1", + BinaryData.fromBytes("[14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33]" + .getBytes(StandardCharsets.UTF_8)), + "ownerId", BinaryData.fromBytes("sam".getBytes(StandardCharsets.UTF_8)), "category", + BinaryData.fromBytes("purple".getBytes(StandardCharsets.UTF_8)), "vector2", + BinaryData.fromBytes("[14, 15, 16, 17, 18]".getBytes(StandardCharsets.UTF_8)))), + new IndexAction().setAdditionalProperties(mapOf("vector1b", + BinaryData.fromBytes("[25, 26, 27, 28, 29, 30, 31, 32, 33, 34]".getBytes(StandardCharsets.UTF_8)), + "vector3", BinaryData.fromBytes("[15, 16, 17, 18, 19]".getBytes(StandardCharsets.UTF_8)), + "@search.action", BinaryData.fromBytes("mergeOrUpload".getBytes(StandardCharsets.UTF_8)), "vector22", + BinaryData.fromBytes("[35, 36, 37, 38, 39, 40, 41, 42, 43, 44]".getBytes(StandardCharsets.UTF_8)), + "price", BinaryData.fromBytes("15".getBytes(StandardCharsets.UTF_8)), "name", + BinaryData.fromBytes("test".getBytes(StandardCharsets.UTF_8)), "description", + BinaryData.fromBytes("test15 hello".getBytes(StandardCharsets.UTF_8)), "id", + BinaryData.fromBytes("15".getBytes(StandardCharsets.UTF_8)), "vector1", + BinaryData.fromBytes("[15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34]" + .getBytes(StandardCharsets.UTF_8)), + "ownerId", BinaryData.fromBytes("ryan".getBytes(StandardCharsets.UTF_8)), "category", + BinaryData.fromBytes("purple".getBytes(StandardCharsets.UTF_8)), "vector2", + BinaryData.fromBytes("[15, 16, 17, 18, 19]".getBytes(StandardCharsets.UTF_8)))), + new IndexAction().setAdditionalProperties(mapOf("vector1b", + BinaryData.fromBytes("[26, 27, 28, 29, 30, 31, 32, 33, 34, 35]".getBytes(StandardCharsets.UTF_8)), + "vector3", BinaryData.fromBytes("[16, 17, 18, 19, 20]".getBytes(StandardCharsets.UTF_8)), + "@search.action", BinaryData.fromBytes("mergeOrUpload".getBytes(StandardCharsets.UTF_8)), "vector22", + BinaryData.fromBytes("[36, 37, 38, 39, 40, 41, 42, 43, 44, 45]".getBytes(StandardCharsets.UTF_8)), + "price", BinaryData.fromBytes("16".getBytes(StandardCharsets.UTF_8)), "name", + BinaryData.fromBytes("test".getBytes(StandardCharsets.UTF_8)), "description", + BinaryData.fromBytes("test16 hello".getBytes(StandardCharsets.UTF_8)), "id", + BinaryData.fromBytes("16".getBytes(StandardCharsets.UTF_8)), "vector1", + BinaryData.fromBytes("[16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35]" + .getBytes(StandardCharsets.UTF_8)), + "ownerId", BinaryData.fromBytes("sam".getBytes(StandardCharsets.UTF_8)), "category", + BinaryData.fromBytes("purple".getBytes(StandardCharsets.UTF_8)), "vector2", + BinaryData.fromBytes("[16, 17, 18, 19, 20]".getBytes(StandardCharsets.UTF_8)))), + new IndexAction().setAdditionalProperties(mapOf("vector1b", + BinaryData.fromBytes("[27, 28, 29, 30, 31, 32, 33, 34, 35, 36]".getBytes(StandardCharsets.UTF_8)), + "vector3", BinaryData.fromBytes("[17, 18, 19, 20, 21]".getBytes(StandardCharsets.UTF_8)), + "@search.action", BinaryData.fromBytes("mergeOrUpload".getBytes(StandardCharsets.UTF_8)), "vector22", + BinaryData.fromBytes("[37, 38, 39, 40, 41, 42, 43, 44, 45, 46]".getBytes(StandardCharsets.UTF_8)), + "price", BinaryData.fromBytes("17".getBytes(StandardCharsets.UTF_8)), "name", + BinaryData.fromBytes("test".getBytes(StandardCharsets.UTF_8)), "description", + BinaryData.fromBytes("test17 hello".getBytes(StandardCharsets.UTF_8)), "id", + BinaryData.fromBytes("17".getBytes(StandardCharsets.UTF_8)), "vector1", + BinaryData.fromBytes("[17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36]" + .getBytes(StandardCharsets.UTF_8)), + "ownerId", BinaryData.fromBytes("sam".getBytes(StandardCharsets.UTF_8)), "category", + BinaryData.fromBytes("purple".getBytes(StandardCharsets.UTF_8)), "vector2", + BinaryData.fromBytes("[17, 18, 19, 20, 21]".getBytes(StandardCharsets.UTF_8)))), + new IndexAction().setAdditionalProperties(mapOf("vector1b", + BinaryData.fromBytes("[28, 29, 30, 31, 32, 33, 34, 35, 36, 37]".getBytes(StandardCharsets.UTF_8)), + "vector3", BinaryData.fromBytes("[18, 19, 20, 21, 22]".getBytes(StandardCharsets.UTF_8)), + "@search.action", BinaryData.fromBytes("mergeOrUpload".getBytes(StandardCharsets.UTF_8)), "vector22", + BinaryData.fromBytes("[38, 39, 40, 41, 42, 43, 44, 45, 46, 47]".getBytes(StandardCharsets.UTF_8)), + "price", BinaryData.fromBytes("18".getBytes(StandardCharsets.UTF_8)), "name", + BinaryData.fromBytes("test".getBytes(StandardCharsets.UTF_8)), "description", + BinaryData.fromBytes("test18 hello".getBytes(StandardCharsets.UTF_8)), "id", + BinaryData.fromBytes("18".getBytes(StandardCharsets.UTF_8)), "vector1", + BinaryData.fromBytes("[18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37]" + .getBytes(StandardCharsets.UTF_8)), + "ownerId", BinaryData.fromBytes("ryan".getBytes(StandardCharsets.UTF_8)), "category", + BinaryData.fromBytes("purple".getBytes(StandardCharsets.UTF_8)), "vector2", + BinaryData.fromBytes("[18, 19, 20, 21, 22]".getBytes(StandardCharsets.UTF_8)))), + new IndexAction().setAdditionalProperties(mapOf("vector1b", + BinaryData.fromBytes("[29, 30, 31, 32, 33, 34, 35, 36, 37, 38]".getBytes(StandardCharsets.UTF_8)), + "vector3", BinaryData.fromBytes("[19, 20, 21, 22, 23]".getBytes(StandardCharsets.UTF_8)), + "@search.action", BinaryData.fromBytes("mergeOrUpload".getBytes(StandardCharsets.UTF_8)), "vector22", + BinaryData.fromBytes("[39, 40, 41, 42, 43, 44, 45, 46, 47, 48]".getBytes(StandardCharsets.UTF_8)), + "price", BinaryData.fromBytes("19".getBytes(StandardCharsets.UTF_8)), "name", + BinaryData.fromBytes("test".getBytes(StandardCharsets.UTF_8)), "description", + BinaryData.fromBytes("test19 hello".getBytes(StandardCharsets.UTF_8)), "id", + BinaryData.fromBytes("19".getBytes(StandardCharsets.UTF_8)), "vector1", + BinaryData.fromBytes("[19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38]" + .getBytes(StandardCharsets.UTF_8)), + "ownerId", BinaryData.fromBytes("sam".getBytes(StandardCharsets.UTF_8)), "category", + BinaryData.fromBytes("purple".getBytes(StandardCharsets.UTF_8)), "vector2", + BinaryData.fromBytes("[19, 20, 21, 22, 23]".getBytes(StandardCharsets.UTF_8)))), + new IndexAction().setAdditionalProperties(mapOf("vector1b", + BinaryData.fromBytes("[30, 31, 32, 33, 34, 35, 36, 37, 38, 39]".getBytes(StandardCharsets.UTF_8)), + "vector3", BinaryData.fromBytes("[20, 21, 22, 23, 24]".getBytes(StandardCharsets.UTF_8)), + "@search.action", BinaryData.fromBytes("mergeOrUpload".getBytes(StandardCharsets.UTF_8)), "vector22", + BinaryData.fromBytes("[40, 41, 42, 43, 44, 45, 46, 47, 48, 49]".getBytes(StandardCharsets.UTF_8)), + "price", BinaryData.fromBytes("20".getBytes(StandardCharsets.UTF_8)), "name", + BinaryData.fromBytes("test".getBytes(StandardCharsets.UTF_8)), "description", + BinaryData.fromBytes("test20 hello".getBytes(StandardCharsets.UTF_8)), "id", + BinaryData.fromBytes("20".getBytes(StandardCharsets.UTF_8)), "vector1", + BinaryData.fromBytes("[20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39]" + .getBytes(StandardCharsets.UTF_8)), + "ownerId", BinaryData.fromBytes("benny".getBytes(StandardCharsets.UTF_8)), "category", + BinaryData.fromBytes("purple".getBytes(StandardCharsets.UTF_8)), "vector2", + BinaryData.fromBytes("[20, 21, 22, 23, 24]".getBytes(StandardCharsets.UTF_8)))), + new IndexAction().setAdditionalProperties(mapOf("vector1b", + BinaryData.fromBytes("[31, 32, 33, 34, 35, 36, 37, 38, 39, 40]".getBytes(StandardCharsets.UTF_8)), + "vector3", BinaryData.fromBytes("[21, 22, 23, 24, 25]".getBytes(StandardCharsets.UTF_8)), + "@search.action", BinaryData.fromBytes("mergeOrUpload".getBytes(StandardCharsets.UTF_8)), "vector22", + BinaryData.fromBytes("[41, 42, 43, 44, 45, 46, 47, 48, 49, 50]".getBytes(StandardCharsets.UTF_8)), + "price", BinaryData.fromBytes("21".getBytes(StandardCharsets.UTF_8)), "name", + BinaryData.fromBytes("test".getBytes(StandardCharsets.UTF_8)), "description", + BinaryData.fromBytes("test21 hello".getBytes(StandardCharsets.UTF_8)), "id", + BinaryData.fromBytes("21".getBytes(StandardCharsets.UTF_8)), "vector1", + BinaryData.fromBytes("[21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40]" + .getBytes(StandardCharsets.UTF_8)), + "ownerId", BinaryData.fromBytes("ryan".getBytes(StandardCharsets.UTF_8)), "category", + BinaryData.fromBytes("purple".getBytes(StandardCharsets.UTF_8)), "vector2", + BinaryData.fromBytes("[21, 22, 23, 24, 25]".getBytes(StandardCharsets.UTF_8)))), + new IndexAction().setAdditionalProperties(mapOf("vector1b", + BinaryData.fromBytes("[32, 33, 34, 35, 36, 37, 38, 39, 40, 41]".getBytes(StandardCharsets.UTF_8)), + "vector3", BinaryData.fromBytes("[22, 23, 24, 25, 26]".getBytes(StandardCharsets.UTF_8)), + "@search.action", BinaryData.fromBytes("mergeOrUpload".getBytes(StandardCharsets.UTF_8)), "vector22", + BinaryData.fromBytes("[42, 43, 44, 45, 46, 47, 48, 49, 50, 51]".getBytes(StandardCharsets.UTF_8)), + "price", BinaryData.fromBytes("22".getBytes(StandardCharsets.UTF_8)), "name", + BinaryData.fromBytes("test".getBytes(StandardCharsets.UTF_8)), "description", + BinaryData.fromBytes("test22 hello".getBytes(StandardCharsets.UTF_8)), "id", + BinaryData.fromBytes("22".getBytes(StandardCharsets.UTF_8)), "vector1", + BinaryData.fromBytes("[22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41]" + .getBytes(StandardCharsets.UTF_8)), + "ownerId", BinaryData.fromBytes("sam".getBytes(StandardCharsets.UTF_8)), "category", + BinaryData.fromBytes("purple".getBytes(StandardCharsets.UTF_8)), "vector2", + BinaryData.fromBytes("[22, 23, 24, 25, 26]".getBytes(StandardCharsets.UTF_8)))), + new IndexAction().setAdditionalProperties(mapOf("vector1b", + BinaryData.fromBytes("[33, 34, 35, 36, 37, 38, 39, 40, 41, 42]".getBytes(StandardCharsets.UTF_8)), + "vector3", BinaryData.fromBytes("[23, 24, 25, 26, 27]".getBytes(StandardCharsets.UTF_8)), + "@search.action", BinaryData.fromBytes("mergeOrUpload".getBytes(StandardCharsets.UTF_8)), "vector22", + BinaryData.fromBytes("[43, 44, 45, 46, 47, 48, 49, 50, 51, 52]".getBytes(StandardCharsets.UTF_8)), + "price", BinaryData.fromBytes("23".getBytes(StandardCharsets.UTF_8)), "name", + BinaryData.fromBytes("test".getBytes(StandardCharsets.UTF_8)), "description", + BinaryData.fromBytes("test23 hello".getBytes(StandardCharsets.UTF_8)), "id", + BinaryData.fromBytes("23".getBytes(StandardCharsets.UTF_8)), "vector1", + BinaryData.fromBytes("[23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42]" + .getBytes(StandardCharsets.UTF_8)), + "ownerId", BinaryData.fromBytes("sam".getBytes(StandardCharsets.UTF_8)), "category", + BinaryData.fromBytes("purple".getBytes(StandardCharsets.UTF_8)), "vector2", + BinaryData.fromBytes("[23, 24, 25, 26, 27]".getBytes(StandardCharsets.UTF_8)))), + new IndexAction().setAdditionalProperties(mapOf("vector1b", + BinaryData.fromBytes("[34, 35, 36, 37, 38, 39, 40, 41, 42, 43]".getBytes(StandardCharsets.UTF_8)), + "vector3", BinaryData.fromBytes("[24, 25, 26, 27, 28]".getBytes(StandardCharsets.UTF_8)), + "@search.action", BinaryData.fromBytes("mergeOrUpload".getBytes(StandardCharsets.UTF_8)), "vector22", + BinaryData.fromBytes("[44, 45, 46, 47, 48, 49, 50, 51, 52, 53]".getBytes(StandardCharsets.UTF_8)), + "price", BinaryData.fromBytes("24".getBytes(StandardCharsets.UTF_8)), "name", + BinaryData.fromBytes("test".getBytes(StandardCharsets.UTF_8)), "description", + BinaryData.fromBytes("test24 hello".getBytes(StandardCharsets.UTF_8)), "id", + BinaryData.fromBytes("24".getBytes(StandardCharsets.UTF_8)), "vector1", + BinaryData.fromBytes("[24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43]" + .getBytes(StandardCharsets.UTF_8)), + "ownerId", BinaryData.fromBytes("ryan".getBytes(StandardCharsets.UTF_8)), "category", + BinaryData.fromBytes("purple".getBytes(StandardCharsets.UTF_8)), "vector2", + BinaryData.fromBytes("[24, 25, 26, 27, 28]".getBytes(StandardCharsets.UTF_8)))), + new IndexAction().setAdditionalProperties(mapOf("vector1b", + BinaryData.fromBytes("[35, 36, 37, 38, 39, 40, 41, 42, 43, 44]".getBytes(StandardCharsets.UTF_8)), + "vector3", BinaryData.fromBytes("[25, 26, 27, 28, 29]".getBytes(StandardCharsets.UTF_8)), + "@search.action", BinaryData.fromBytes("mergeOrUpload".getBytes(StandardCharsets.UTF_8)), "vector22", + BinaryData.fromBytes("[45, 46, 47, 48, 49, 50, 51, 52, 53, 54]".getBytes(StandardCharsets.UTF_8)), + "price", BinaryData.fromBytes("25".getBytes(StandardCharsets.UTF_8)), "name", + BinaryData.fromBytes("test".getBytes(StandardCharsets.UTF_8)), "description", + BinaryData.fromBytes("test25 hello".getBytes(StandardCharsets.UTF_8)), "id", + BinaryData.fromBytes("25".getBytes(StandardCharsets.UTF_8)), "vector1", + BinaryData.fromBytes("[25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44]" + .getBytes(StandardCharsets.UTF_8)), + "ownerId", BinaryData.fromBytes("sam".getBytes(StandardCharsets.UTF_8)), "category", + BinaryData.fromBytes("pink".getBytes(StandardCharsets.UTF_8)), "vector2", + BinaryData.fromBytes("[25, 26, 27, 28, 29]".getBytes(StandardCharsets.UTF_8)))), + new IndexAction().setAdditionalProperties(mapOf("vector1b", + BinaryData.fromBytes("[36, 37, 38, 39, 40, 41, 42, 43, 44, 45]".getBytes(StandardCharsets.UTF_8)), + "vector3", BinaryData.fromBytes("[26, 27, 28, 29, 30]".getBytes(StandardCharsets.UTF_8)), + "@search.action", BinaryData.fromBytes("mergeOrUpload".getBytes(StandardCharsets.UTF_8)), "vector22", + BinaryData.fromBytes("[46, 47, 48, 49, 50, 51, 52, 53, 54, 55]".getBytes(StandardCharsets.UTF_8)), + "price", BinaryData.fromBytes("26".getBytes(StandardCharsets.UTF_8)), "name", + BinaryData.fromBytes("test".getBytes(StandardCharsets.UTF_8)), "description", + BinaryData.fromBytes("test26 hello".getBytes(StandardCharsets.UTF_8)), "id", + BinaryData.fromBytes("26".getBytes(StandardCharsets.UTF_8)), "vector1", + BinaryData.fromBytes("[26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45]" + .getBytes(StandardCharsets.UTF_8)), + "ownerId", BinaryData.fromBytes("sam".getBytes(StandardCharsets.UTF_8)), "category", + BinaryData.fromBytes("pink".getBytes(StandardCharsets.UTF_8)), "vector2", + BinaryData.fromBytes("[26, 27, 28, 29, 30]".getBytes(StandardCharsets.UTF_8)))), + new IndexAction().setAdditionalProperties(mapOf("vector1b", + BinaryData.fromBytes("[37, 38, 39, 40, 41, 42, 43, 44, 45, 46]".getBytes(StandardCharsets.UTF_8)), + "vector3", BinaryData.fromBytes("[27, 28, 29, 30, 31]".getBytes(StandardCharsets.UTF_8)), + "@search.action", BinaryData.fromBytes("mergeOrUpload".getBytes(StandardCharsets.UTF_8)), "vector22", + BinaryData.fromBytes("[47, 48, 49, 50, 51, 52, 53, 54, 55, 56]".getBytes(StandardCharsets.UTF_8)), + "price", BinaryData.fromBytes("27".getBytes(StandardCharsets.UTF_8)), "name", + BinaryData.fromBytes("test".getBytes(StandardCharsets.UTF_8)), "description", + BinaryData.fromBytes("test27 hello".getBytes(StandardCharsets.UTF_8)), "id", + BinaryData.fromBytes("27".getBytes(StandardCharsets.UTF_8)), "vector1", + BinaryData.fromBytes("[27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46]" + .getBytes(StandardCharsets.UTF_8)), + "ownerId", BinaryData.fromBytes("ryan".getBytes(StandardCharsets.UTF_8)), "category", + BinaryData.fromBytes("pink".getBytes(StandardCharsets.UTF_8)), "vector2", + BinaryData.fromBytes("[27, 28, 29, 30, 31]".getBytes(StandardCharsets.UTF_8)))), + new IndexAction().setAdditionalProperties(mapOf("vector1b", + BinaryData.fromBytes("[38, 39, 40, 41, 42, 43, 44, 45, 46, 47]".getBytes(StandardCharsets.UTF_8)), + "vector3", BinaryData.fromBytes("[28, 29, 30, 31, 32]".getBytes(StandardCharsets.UTF_8)), + "@search.action", BinaryData.fromBytes("mergeOrUpload".getBytes(StandardCharsets.UTF_8)), "vector22", + BinaryData.fromBytes("[48, 49, 50, 51, 52, 53, 54, 55, 56, 57]".getBytes(StandardCharsets.UTF_8)), + "price", BinaryData.fromBytes("28".getBytes(StandardCharsets.UTF_8)), "name", + BinaryData.fromBytes("test".getBytes(StandardCharsets.UTF_8)), "description", + BinaryData.fromBytes("test28 hello".getBytes(StandardCharsets.UTF_8)), "id", + BinaryData.fromBytes("28".getBytes(StandardCharsets.UTF_8)), "vector1", + BinaryData.fromBytes("[28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47]" + .getBytes(StandardCharsets.UTF_8)), + "ownerId", BinaryData.fromBytes("sam".getBytes(StandardCharsets.UTF_8)), "category", + BinaryData.fromBytes("pink".getBytes(StandardCharsets.UTF_8)), "vector2", + BinaryData.fromBytes("[28, 29, 30, 31, 32]".getBytes(StandardCharsets.UTF_8)))), + new IndexAction().setAdditionalProperties(mapOf("vector1b", + BinaryData.fromBytes("[39, 40, 41, 42, 43, 44, 45, 46, 47, 48]".getBytes(StandardCharsets.UTF_8)), + "vector3", BinaryData.fromBytes("[29, 30, 31, 32, 33]".getBytes(StandardCharsets.UTF_8)), + "@search.action", BinaryData.fromBytes("mergeOrUpload".getBytes(StandardCharsets.UTF_8)), "vector22", + BinaryData.fromBytes("[49, 50, 51, 52, 53, 54, 55, 56, 57, 58]".getBytes(StandardCharsets.UTF_8)), + "price", BinaryData.fromBytes("29".getBytes(StandardCharsets.UTF_8)), "name", + BinaryData.fromBytes("test".getBytes(StandardCharsets.UTF_8)), "description", + BinaryData.fromBytes("test29 hello".getBytes(StandardCharsets.UTF_8)), "id", + BinaryData.fromBytes("29".getBytes(StandardCharsets.UTF_8)), "vector1", + BinaryData.fromBytes("[29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48]" + .getBytes(StandardCharsets.UTF_8)), + "ownerId", BinaryData.fromBytes("sam".getBytes(StandardCharsets.UTF_8)), "category", + BinaryData.fromBytes("pink".getBytes(StandardCharsets.UTF_8)), "vector2", + BinaryData.fromBytes("[29, 30, 31, 32, 33]".getBytes(StandardCharsets.UTF_8)))), + new IndexAction().setAdditionalProperties(mapOf("vector1b", + BinaryData.fromBytes("[40, 41, 42, 43, 44, 45, 46, 47, 48, 49]".getBytes(StandardCharsets.UTF_8)), + "vector3", BinaryData.fromBytes("[30, 31, 32, 33, 34]".getBytes(StandardCharsets.UTF_8)), + "@search.action", BinaryData.fromBytes("mergeOrUpload".getBytes(StandardCharsets.UTF_8)), "vector22", + BinaryData.fromBytes("[50, 51, 52, 53, 54, 55, 56, 57, 58, 59]".getBytes(StandardCharsets.UTF_8)), + "price", BinaryData.fromBytes("30".getBytes(StandardCharsets.UTF_8)), "name", + BinaryData.fromBytes("test".getBytes(StandardCharsets.UTF_8)), "description", + BinaryData.fromBytes("test30 hello".getBytes(StandardCharsets.UTF_8)), "id", + BinaryData.fromBytes("30".getBytes(StandardCharsets.UTF_8)), "vector1", + BinaryData.fromBytes("[30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49]" + .getBytes(StandardCharsets.UTF_8)), + "ownerId", BinaryData.fromBytes("benny".getBytes(StandardCharsets.UTF_8)), "category", + BinaryData.fromBytes("pink".getBytes(StandardCharsets.UTF_8)), "vector2", + BinaryData.fromBytes("[30, 31, 32, 33, 34]".getBytes(StandardCharsets.UTF_8)))), + new IndexAction().setAdditionalProperties(mapOf("vector1b", + BinaryData.fromBytes("[41, 42, 43, 44, 45, 46, 47, 48, 49, 50]".getBytes(StandardCharsets.UTF_8)), + "vector3", BinaryData.fromBytes("[31, 32, 33, 34, 35]".getBytes(StandardCharsets.UTF_8)), + "@search.action", BinaryData.fromBytes("mergeOrUpload".getBytes(StandardCharsets.UTF_8)), "vector22", + BinaryData.fromBytes("[51, 52, 53, 54, 55, 56, 57, 58, 59, 60]".getBytes(StandardCharsets.UTF_8)), + "price", BinaryData.fromBytes("31".getBytes(StandardCharsets.UTF_8)), "name", + BinaryData.fromBytes("test".getBytes(StandardCharsets.UTF_8)), "description", + BinaryData.fromBytes("test31 hello".getBytes(StandardCharsets.UTF_8)), "id", + BinaryData.fromBytes("31".getBytes(StandardCharsets.UTF_8)), "vector1", + BinaryData.fromBytes("[31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50]" + .getBytes(StandardCharsets.UTF_8)), + "ownerId", BinaryData.fromBytes("sam".getBytes(StandardCharsets.UTF_8)), "category", + BinaryData.fromBytes("pink".getBytes(StandardCharsets.UTF_8)), "vector2", + BinaryData.fromBytes("[31, 32, 33, 34, 35]".getBytes(StandardCharsets.UTF_8)))), + new IndexAction().setAdditionalProperties(mapOf("vector1b", + BinaryData.fromBytes("[42, 43, 44, 45, 46, 47, 48, 49, 50, 51]".getBytes(StandardCharsets.UTF_8)), + "vector3", BinaryData.fromBytes("[32, 33, 34, 35, 36]".getBytes(StandardCharsets.UTF_8)), + "@search.action", BinaryData.fromBytes("mergeOrUpload".getBytes(StandardCharsets.UTF_8)), "vector22", + BinaryData.fromBytes("[52, 53, 54, 55, 56, 57, 58, 59, 60, 61]".getBytes(StandardCharsets.UTF_8)), + "price", BinaryData.fromBytes("32".getBytes(StandardCharsets.UTF_8)), "name", + BinaryData.fromBytes("test".getBytes(StandardCharsets.UTF_8)), "description", + BinaryData.fromBytes("test32 hello".getBytes(StandardCharsets.UTF_8)), "id", + BinaryData.fromBytes("32".getBytes(StandardCharsets.UTF_8)), "vector1", + BinaryData.fromBytes("[32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51]" + .getBytes(StandardCharsets.UTF_8)), + "ownerId", BinaryData.fromBytes("sam".getBytes(StandardCharsets.UTF_8)), "category", + BinaryData.fromBytes("pink".getBytes(StandardCharsets.UTF_8)), "vector2", + BinaryData.fromBytes("[32, 33, 34, 35, 36]".getBytes(StandardCharsets.UTF_8)))), + new IndexAction().setAdditionalProperties(mapOf("vector1b", + BinaryData.fromBytes("[43, 44, 45, 46, 47, 48, 49, 50, 51, 52]".getBytes(StandardCharsets.UTF_8)), + "vector3", BinaryData.fromBytes("[33, 34, 35, 36, 37]".getBytes(StandardCharsets.UTF_8)), + "@search.action", BinaryData.fromBytes("mergeOrUpload".getBytes(StandardCharsets.UTF_8)), "vector22", + BinaryData.fromBytes("[53, 54, 55, 56, 57, 58, 59, 60, 61, 62]".getBytes(StandardCharsets.UTF_8)), + "price", BinaryData.fromBytes("33".getBytes(StandardCharsets.UTF_8)), "name", + BinaryData.fromBytes("test".getBytes(StandardCharsets.UTF_8)), "description", + BinaryData.fromBytes("test33 hello".getBytes(StandardCharsets.UTF_8)), "id", + BinaryData.fromBytes("33".getBytes(StandardCharsets.UTF_8)), "vector1", + BinaryData.fromBytes("[33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52]" + .getBytes(StandardCharsets.UTF_8)), + "ownerId", BinaryData.fromBytes("ryan".getBytes(StandardCharsets.UTF_8)), "category", + BinaryData.fromBytes("pink".getBytes(StandardCharsets.UTF_8)), "vector2", + BinaryData.fromBytes("[33, 34, 35, 36, 37]".getBytes(StandardCharsets.UTF_8)))), + new IndexAction().setAdditionalProperties(mapOf("vector1b", + BinaryData.fromBytes("[44, 45, 46, 47, 48, 49, 50, 51, 52, 53]".getBytes(StandardCharsets.UTF_8)), + "vector3", BinaryData.fromBytes("[34, 35, 36, 37, 38]".getBytes(StandardCharsets.UTF_8)), + "@search.action", BinaryData.fromBytes("mergeOrUpload".getBytes(StandardCharsets.UTF_8)), "vector22", + BinaryData.fromBytes("[54, 55, 56, 57, 58, 59, 60, 61, 62, 63]".getBytes(StandardCharsets.UTF_8)), + "price", BinaryData.fromBytes("34".getBytes(StandardCharsets.UTF_8)), "name", + BinaryData.fromBytes("test".getBytes(StandardCharsets.UTF_8)), "description", + BinaryData.fromBytes("test34 hello".getBytes(StandardCharsets.UTF_8)), "id", + BinaryData.fromBytes("34".getBytes(StandardCharsets.UTF_8)), "vector1", + BinaryData.fromBytes("[34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53]" + .getBytes(StandardCharsets.UTF_8)), + "ownerId", BinaryData.fromBytes("sam".getBytes(StandardCharsets.UTF_8)), "category", + BinaryData.fromBytes("pink".getBytes(StandardCharsets.UTF_8)), "vector2", + BinaryData.fromBytes("[34, 35, 36, 37, 38]".getBytes(StandardCharsets.UTF_8)))), + new IndexAction().setAdditionalProperties(mapOf("vector1b", + BinaryData.fromBytes("[45, 46, 47, 48, 49, 50, 51, 52, 53, 54]".getBytes(StandardCharsets.UTF_8)), + "vector3", BinaryData.fromBytes("[35, 36, 37, 38, 39]".getBytes(StandardCharsets.UTF_8)), + "@search.action", BinaryData.fromBytes("mergeOrUpload".getBytes(StandardCharsets.UTF_8)), "vector22", + BinaryData.fromBytes("[55, 56, 57, 58, 59, 60, 61, 62, 63, 64]".getBytes(StandardCharsets.UTF_8)), + "price", BinaryData.fromBytes("35".getBytes(StandardCharsets.UTF_8)), "name", + BinaryData.fromBytes("test".getBytes(StandardCharsets.UTF_8)), "description", + BinaryData.fromBytes("test35 hello".getBytes(StandardCharsets.UTF_8)), "id", + BinaryData.fromBytes("35".getBytes(StandardCharsets.UTF_8)), "vector1", + BinaryData.fromBytes("[35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54]" + .getBytes(StandardCharsets.UTF_8)), + "ownerId", BinaryData.fromBytes("sam".getBytes(StandardCharsets.UTF_8)), "category", + BinaryData.fromBytes("pink".getBytes(StandardCharsets.UTF_8)), "vector2", + BinaryData.fromBytes("[35, 36, 37, 38, 39]".getBytes(StandardCharsets.UTF_8)))), + new IndexAction().setAdditionalProperties(mapOf("vector1b", + BinaryData.fromBytes("[46, 47, 48, 49, 50, 51, 52, 53, 54, 55]".getBytes(StandardCharsets.UTF_8)), + "vector3", BinaryData.fromBytes("[36, 37, 38, 39, 40]".getBytes(StandardCharsets.UTF_8)), + "@search.action", BinaryData.fromBytes("mergeOrUpload".getBytes(StandardCharsets.UTF_8)), "vector22", + BinaryData.fromBytes("[56, 57, 58, 59, 60, 61, 62, 63, 64, 65]".getBytes(StandardCharsets.UTF_8)), + "price", BinaryData.fromBytes("36".getBytes(StandardCharsets.UTF_8)), "name", + BinaryData.fromBytes("test".getBytes(StandardCharsets.UTF_8)), "description", + BinaryData.fromBytes("test36 hello".getBytes(StandardCharsets.UTF_8)), "id", + BinaryData.fromBytes("36".getBytes(StandardCharsets.UTF_8)), "vector1", + BinaryData.fromBytes("[36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55]" + .getBytes(StandardCharsets.UTF_8)), + "ownerId", BinaryData.fromBytes("ryan".getBytes(StandardCharsets.UTF_8)), "category", + BinaryData.fromBytes("pink".getBytes(StandardCharsets.UTF_8)), "vector2", + BinaryData.fromBytes("[36, 37, 38, 39, 40]".getBytes(StandardCharsets.UTF_8)))), + new IndexAction().setAdditionalProperties(mapOf("vector1b", + BinaryData.fromBytes("[47, 48, 49, 50, 51, 52, 53, 54, 55, 56]".getBytes(StandardCharsets.UTF_8)), + "vector3", BinaryData.fromBytes("[37, 38, 39, 40, 41]".getBytes(StandardCharsets.UTF_8)), + "@search.action", BinaryData.fromBytes("mergeOrUpload".getBytes(StandardCharsets.UTF_8)), "vector22", + BinaryData.fromBytes("[57, 58, 59, 60, 61, 62, 63, 64, 65, 66]".getBytes(StandardCharsets.UTF_8)), + "price", BinaryData.fromBytes("37".getBytes(StandardCharsets.UTF_8)), "name", + BinaryData.fromBytes("test".getBytes(StandardCharsets.UTF_8)), "description", + BinaryData.fromBytes("test37 hello".getBytes(StandardCharsets.UTF_8)), "id", + BinaryData.fromBytes("37".getBytes(StandardCharsets.UTF_8)), "vector1", + BinaryData.fromBytes("[37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56]" + .getBytes(StandardCharsets.UTF_8)), + "ownerId", BinaryData.fromBytes("sam".getBytes(StandardCharsets.UTF_8)), "category", + BinaryData.fromBytes("pink".getBytes(StandardCharsets.UTF_8)), "vector2", + BinaryData.fromBytes("[37, 38, 39, 40, 41]".getBytes(StandardCharsets.UTF_8)))), + new IndexAction().setAdditionalProperties(mapOf("vector1b", + BinaryData.fromBytes("[48, 49, 50, 51, 52, 53, 54, 55, 56, 57]".getBytes(StandardCharsets.UTF_8)), + "vector3", BinaryData.fromBytes("[38, 39, 40, 41, 42]".getBytes(StandardCharsets.UTF_8)), + "@search.action", BinaryData.fromBytes("mergeOrUpload".getBytes(StandardCharsets.UTF_8)), "vector22", + BinaryData.fromBytes("[58, 59, 60, 61, 62, 63, 64, 65, 66, 67]".getBytes(StandardCharsets.UTF_8)), + "price", BinaryData.fromBytes("38".getBytes(StandardCharsets.UTF_8)), "name", + BinaryData.fromBytes("test".getBytes(StandardCharsets.UTF_8)), "description", + BinaryData.fromBytes("test38 hello".getBytes(StandardCharsets.UTF_8)), "id", + BinaryData.fromBytes("38".getBytes(StandardCharsets.UTF_8)), "vector1", + BinaryData.fromBytes("[38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57]" + .getBytes(StandardCharsets.UTF_8)), + "ownerId", BinaryData.fromBytes("sam".getBytes(StandardCharsets.UTF_8)), "category", + BinaryData.fromBytes("pink".getBytes(StandardCharsets.UTF_8)), "vector2", + BinaryData.fromBytes("[38, 39, 40, 41, 42]".getBytes(StandardCharsets.UTF_8)))), + new IndexAction().setAdditionalProperties(mapOf("vector1b", + BinaryData.fromBytes("[49, 50, 51, 52, 53, 54, 55, 56, 57, 58]".getBytes(StandardCharsets.UTF_8)), + "vector3", BinaryData.fromBytes("[39, 40, 41, 42, 43]".getBytes(StandardCharsets.UTF_8)), + "@search.action", BinaryData.fromBytes("mergeOrUpload".getBytes(StandardCharsets.UTF_8)), "vector22", + BinaryData.fromBytes("[59, 60, 61, 62, 63, 64, 65, 66, 67, 68]".getBytes(StandardCharsets.UTF_8)), + "price", BinaryData.fromBytes("39".getBytes(StandardCharsets.UTF_8)), "name", + BinaryData.fromBytes("test".getBytes(StandardCharsets.UTF_8)), "description", + BinaryData.fromBytes("test39 hello".getBytes(StandardCharsets.UTF_8)), "id", + BinaryData.fromBytes("39".getBytes(StandardCharsets.UTF_8)), "vector1", + BinaryData.fromBytes("[39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58]" + .getBytes(StandardCharsets.UTF_8)), + "ownerId", BinaryData.fromBytes("ryan".getBytes(StandardCharsets.UTF_8)), "category", + BinaryData.fromBytes("pink".getBytes(StandardCharsets.UTF_8)), "vector2", + BinaryData.fromBytes("[39, 40, 41, 42, 43]".getBytes(StandardCharsets.UTF_8)))), + new IndexAction().setAdditionalProperties(mapOf("vector1b", + BinaryData.fromBytes("[50, 51, 52, 53, 54, 55, 56, 57, 58, 59]".getBytes(StandardCharsets.UTF_8)), + "vector3", BinaryData.fromBytes("[40, 41, 42, 43, 44]".getBytes(StandardCharsets.UTF_8)), + "@search.action", BinaryData.fromBytes("mergeOrUpload".getBytes(StandardCharsets.UTF_8)), "vector22", + BinaryData.fromBytes("[60, 61, 62, 63, 64, 65, 66, 67, 68, 69]".getBytes(StandardCharsets.UTF_8)), + "price", BinaryData.fromBytes("40".getBytes(StandardCharsets.UTF_8)), "name", + BinaryData.fromBytes("test".getBytes(StandardCharsets.UTF_8)), "description", + BinaryData.fromBytes("test40 hello".getBytes(StandardCharsets.UTF_8)), "id", + BinaryData.fromBytes("40".getBytes(StandardCharsets.UTF_8)), "vector1", + BinaryData.fromBytes("[40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59]" + .getBytes(StandardCharsets.UTF_8)), + "ownerId", BinaryData.fromBytes("benny".getBytes(StandardCharsets.UTF_8)), "category", + BinaryData.fromBytes("green".getBytes(StandardCharsets.UTF_8)), "vector2", + BinaryData.fromBytes("[40, 41, 42, 43, 44]".getBytes(StandardCharsets.UTF_8)))), + new IndexAction().setAdditionalProperties(mapOf("vector1b", + BinaryData.fromBytes("[51, 52, 53, 54, 55, 56, 57, 58, 59, 60]".getBytes(StandardCharsets.UTF_8)), + "vector3", BinaryData.fromBytes("[41, 42, 43, 44, 45]".getBytes(StandardCharsets.UTF_8)), + "@search.action", BinaryData.fromBytes("mergeOrUpload".getBytes(StandardCharsets.UTF_8)), "vector22", + BinaryData.fromBytes("[61, 62, 63, 64, 65, 66, 67, 68, 69, 70]".getBytes(StandardCharsets.UTF_8)), + "price", BinaryData.fromBytes("41".getBytes(StandardCharsets.UTF_8)), "name", + BinaryData.fromBytes("test".getBytes(StandardCharsets.UTF_8)), "description", + BinaryData.fromBytes("test41 hello".getBytes(StandardCharsets.UTF_8)), "id", + BinaryData.fromBytes("41".getBytes(StandardCharsets.UTF_8)), "vector1", + BinaryData.fromBytes("[41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60]" + .getBytes(StandardCharsets.UTF_8)), + "ownerId", BinaryData.fromBytes("sam".getBytes(StandardCharsets.UTF_8)), "category", + BinaryData.fromBytes("green".getBytes(StandardCharsets.UTF_8)), "vector2", + BinaryData.fromBytes("[41, 42, 43, 44, 45]".getBytes(StandardCharsets.UTF_8)))), + new IndexAction().setAdditionalProperties(mapOf("vector1b", + BinaryData.fromBytes("[52, 53, 54, 55, 56, 57, 58, 59, 60, 61]".getBytes(StandardCharsets.UTF_8)), + "vector3", BinaryData.fromBytes("[42, 43, 44, 45, 46]".getBytes(StandardCharsets.UTF_8)), + "@search.action", BinaryData.fromBytes("mergeOrUpload".getBytes(StandardCharsets.UTF_8)), "vector22", + BinaryData.fromBytes("[62, 63, 64, 65, 66, 67, 68, 69, 70, 71]".getBytes(StandardCharsets.UTF_8)), + "price", BinaryData.fromBytes("42".getBytes(StandardCharsets.UTF_8)), "name", + BinaryData.fromBytes("test".getBytes(StandardCharsets.UTF_8)), "description", + BinaryData.fromBytes("test42 hello".getBytes(StandardCharsets.UTF_8)), "id", + BinaryData.fromBytes("42".getBytes(StandardCharsets.UTF_8)), "vector1", + BinaryData.fromBytes("[42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61]" + .getBytes(StandardCharsets.UTF_8)), + "ownerId", BinaryData.fromBytes("ryan".getBytes(StandardCharsets.UTF_8)), "category", + BinaryData.fromBytes("green".getBytes(StandardCharsets.UTF_8)), "vector2", + BinaryData.fromBytes("[42, 43, 44, 45, 46]".getBytes(StandardCharsets.UTF_8)))), + new IndexAction().setAdditionalProperties(mapOf("vector1b", + BinaryData.fromBytes("[53, 54, 55, 56, 57, 58, 59, 60, 61, 62]".getBytes(StandardCharsets.UTF_8)), + "vector3", BinaryData.fromBytes("[43, 44, 45, 46, 47]".getBytes(StandardCharsets.UTF_8)), + "@search.action", BinaryData.fromBytes("mergeOrUpload".getBytes(StandardCharsets.UTF_8)), "vector22", + BinaryData.fromBytes("[63, 64, 65, 66, 67, 68, 69, 70, 71, 72]".getBytes(StandardCharsets.UTF_8)), + "price", BinaryData.fromBytes("43".getBytes(StandardCharsets.UTF_8)), "name", + BinaryData.fromBytes("test".getBytes(StandardCharsets.UTF_8)), "description", + BinaryData.fromBytes("test43 hello".getBytes(StandardCharsets.UTF_8)), "id", + BinaryData.fromBytes("43".getBytes(StandardCharsets.UTF_8)), "vector1", + BinaryData.fromBytes("[43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62]" + .getBytes(StandardCharsets.UTF_8)), + "ownerId", BinaryData.fromBytes("sam".getBytes(StandardCharsets.UTF_8)), "category", + BinaryData.fromBytes("green".getBytes(StandardCharsets.UTF_8)), "vector2", + BinaryData.fromBytes("[43, 44, 45, 46, 47]".getBytes(StandardCharsets.UTF_8)))), + new IndexAction().setAdditionalProperties(mapOf("vector1b", + BinaryData.fromBytes("[54, 55, 56, 57, 58, 59, 60, 61, 62, 63]".getBytes(StandardCharsets.UTF_8)), + "vector3", BinaryData.fromBytes("[44, 45, 46, 47, 48]".getBytes(StandardCharsets.UTF_8)), + "@search.action", BinaryData.fromBytes("mergeOrUpload".getBytes(StandardCharsets.UTF_8)), "vector22", + BinaryData.fromBytes("[64, 65, 66, 67, 68, 69, 70, 71, 72, 73]".getBytes(StandardCharsets.UTF_8)), + "price", BinaryData.fromBytes("44".getBytes(StandardCharsets.UTF_8)), "name", + BinaryData.fromBytes("test".getBytes(StandardCharsets.UTF_8)), "description", + BinaryData.fromBytes("test44 hello".getBytes(StandardCharsets.UTF_8)), "id", + BinaryData.fromBytes("44".getBytes(StandardCharsets.UTF_8)), "vector1", + BinaryData.fromBytes("[44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63]" + .getBytes(StandardCharsets.UTF_8)), + "ownerId", BinaryData.fromBytes("sam".getBytes(StandardCharsets.UTF_8)), "category", + BinaryData.fromBytes("green".getBytes(StandardCharsets.UTF_8)), "vector2", + BinaryData.fromBytes("[44, 45, 46, 47, 48]".getBytes(StandardCharsets.UTF_8)))), + new IndexAction().setAdditionalProperties(mapOf("vector1b", + BinaryData.fromBytes("[55, 56, 57, 58, 59, 60, 61, 62, 63, 64]".getBytes(StandardCharsets.UTF_8)), + "vector3", BinaryData.fromBytes("[45, 46, 47, 48, 49]".getBytes(StandardCharsets.UTF_8)), + "@search.action", BinaryData.fromBytes("mergeOrUpload".getBytes(StandardCharsets.UTF_8)), "vector22", + BinaryData.fromBytes("[65, 66, 67, 68, 69, 70, 71, 72, 73, 74]".getBytes(StandardCharsets.UTF_8)), + "price", BinaryData.fromBytes("45".getBytes(StandardCharsets.UTF_8)), "name", + BinaryData.fromBytes("test".getBytes(StandardCharsets.UTF_8)), "description", + BinaryData.fromBytes("test45 hello".getBytes(StandardCharsets.UTF_8)), "id", + BinaryData.fromBytes("45".getBytes(StandardCharsets.UTF_8)), "vector1", + BinaryData.fromBytes("[45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64]" + .getBytes(StandardCharsets.UTF_8)), + "ownerId", BinaryData.fromBytes("ryan".getBytes(StandardCharsets.UTF_8)), "category", + BinaryData.fromBytes("orange".getBytes(StandardCharsets.UTF_8)), "vector2", + BinaryData.fromBytes("[45, 46, 47, 48, 49]".getBytes(StandardCharsets.UTF_8)))), + new IndexAction().setAdditionalProperties(mapOf("vector1b", + BinaryData.fromBytes("[56, 57, 58, 59, 60, 61, 62, 63, 64, 65]".getBytes(StandardCharsets.UTF_8)), + "vector3", BinaryData.fromBytes("[46, 47, 48, 49, 50]".getBytes(StandardCharsets.UTF_8)), + "@search.action", BinaryData.fromBytes("mergeOrUpload".getBytes(StandardCharsets.UTF_8)), "vector22", + BinaryData.fromBytes("[66, 67, 68, 69, 70, 71, 72, 73, 74, 75]".getBytes(StandardCharsets.UTF_8)), + "price", BinaryData.fromBytes("46".getBytes(StandardCharsets.UTF_8)), "name", + BinaryData.fromBytes("test".getBytes(StandardCharsets.UTF_8)), "description", + BinaryData.fromBytes("test46 hello".getBytes(StandardCharsets.UTF_8)), "id", + BinaryData.fromBytes("46".getBytes(StandardCharsets.UTF_8)), "vector1", + BinaryData.fromBytes("[46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65]" + .getBytes(StandardCharsets.UTF_8)), + "ownerId", BinaryData.fromBytes("sam".getBytes(StandardCharsets.UTF_8)), "category", + BinaryData.fromBytes("orange".getBytes(StandardCharsets.UTF_8)), "vector2", + BinaryData.fromBytes("[46, 47, 48, 49, 50]".getBytes(StandardCharsets.UTF_8)))), + new IndexAction().setAdditionalProperties(mapOf("vector1b", + BinaryData.fromBytes("[57, 58, 59, 60, 61, 62, 63, 64, 65, 66]".getBytes(StandardCharsets.UTF_8)), + "vector3", BinaryData.fromBytes("[47, 48, 49, 50, 51]".getBytes(StandardCharsets.UTF_8)), + "@search.action", BinaryData.fromBytes("mergeOrUpload".getBytes(StandardCharsets.UTF_8)), "vector22", + BinaryData.fromBytes("[67, 68, 69, 70, 71, 72, 73, 74, 75, 76]".getBytes(StandardCharsets.UTF_8)), + "price", BinaryData.fromBytes("47".getBytes(StandardCharsets.UTF_8)), "name", + BinaryData.fromBytes("test".getBytes(StandardCharsets.UTF_8)), "description", + BinaryData.fromBytes("test47 hello".getBytes(StandardCharsets.UTF_8)), "id", + BinaryData.fromBytes("47".getBytes(StandardCharsets.UTF_8)), "vector1", + BinaryData.fromBytes("[47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66]" + .getBytes(StandardCharsets.UTF_8)), + "ownerId", BinaryData.fromBytes("sam".getBytes(StandardCharsets.UTF_8)), "category", + BinaryData.fromBytes("orange".getBytes(StandardCharsets.UTF_8)), "vector2", + BinaryData.fromBytes("[47, 48, 49, 50, 51]".getBytes(StandardCharsets.UTF_8)))), + new IndexAction().setAdditionalProperties( + mapOf("@search.action", BinaryData.fromBytes("mergeOrUpload".getBytes(StandardCharsets.UTF_8)), "name", + BinaryData.fromBytes("test".getBytes(StandardCharsets.UTF_8)), "description", + BinaryData.fromBytes("no vector".getBytes(StandardCharsets.UTF_8)), "id", + BinaryData.fromBytes("no-vectors".getBytes(StandardCharsets.UTF_8)), "ownerId", + BinaryData.fromBytes("sam".getBytes(StandardCharsets.UTF_8)), "category", + BinaryData.fromBytes("purple".getBytes(StandardCharsets.UTF_8)))), + new IndexAction().setAdditionalProperties( + mapOf("@search.action", BinaryData.fromBytes("mergeOrUpload".getBytes(StandardCharsets.UTF_8)), "name", + BinaryData.fromBytes("test".getBytes(StandardCharsets.UTF_8)), "description", + BinaryData.fromBytes("no vector".getBytes(StandardCharsets.UTF_8)), "id", + BinaryData.fromBytes("empty-vectors".getBytes(StandardCharsets.UTF_8)), "ownerId", + BinaryData.fromBytes("sam".getBytes(StandardCharsets.UTF_8)), "category", + BinaryData.fromBytes("purple".getBytes(StandardCharsets.UTF_8))))))); + + // response assertion + Assertions.assertNotNull(response); + // verify property "results" + List responseResults = response.getResults(); + IndexingResult responseResultsFirstItem = responseResults.iterator().next(); + Assertions.assertNotNull(responseResultsFirstItem); + Assertions.assertEquals("0", responseResultsFirstItem.getKey()); + Assertions.assertEquals(true, responseResultsFirstItem.isSucceeded()); + Assertions.assertEquals(201, responseResultsFirstItem.getStatusCode()); + } + + // Use "Map.of" if available + @SuppressWarnings("unchecked") + private static Map mapOf(Object... inputs) { + Map map = new HashMap<>(); + for (int i = 0; i < inputs.length; i += 2) { + String key = (String) inputs[i]; + T value = (T) inputs[i + 1]; + map.put(key, value); + } + return map; + } +} diff --git a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/generated/SearchIndexSearchDocumentsGetTests.java b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/generated/SearchIndexSearchDocumentsGetTests.java new file mode 100644 index 000000000000..c409ca6ac673 --- /dev/null +++ b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/generated/SearchIndexSearchDocumentsGetTests.java @@ -0,0 +1,46 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.search.documents.generated; + +import com.azure.search.documents.models.QueryType; +import com.azure.search.documents.models.ScoringStatistics; +import com.azure.search.documents.models.SearchDocumentsResult; +import com.azure.search.documents.models.SearchMode; +import com.azure.search.documents.models.SearchResult; +import java.util.Arrays; +import java.util.List; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + +@Disabled +public final class SearchIndexSearchDocumentsGetTests extends SearchClientTestBase { + @Test + @Disabled + public void testSearchIndexSearchDocumentsGetTests() { + // method invocation + SearchDocumentsResult response = documentsClient.searchGet("myindex", "nice hotels", true, + Arrays.asList("category,count:10,sort:count"), "rating gt 10", Arrays.asList("title"), "", "", + 80.0D, Arrays.asList("search.score() desc", "rating desc"), QueryType.SIMPLE, null, "sp", + Arrays.asList("title", "description"), SearchMode.ANY, ScoringStatistics.GLOBAL, "mysessionid", + Arrays.asList("docId", "title", "description"), 100, 10, null, null, null, null, null, null, null, null, + null, null, null); + + // response assertion + Assertions.assertNotNull(response); + // verify property "count" + Assertions.assertEquals(25L, response.getCount()); + // verify property "coverage" + Assertions.assertEquals(80.0D, response.getCoverage()); + // verify property "facets" + Assertions.assertNotNull(response.getFacets()); + // verify property "results" + List responseResults = response.getResults(); + SearchResult responseResultsFirstItem = responseResults.iterator().next(); + Assertions.assertNotNull(responseResultsFirstItem); + Assertions.assertEquals(1.5, responseResultsFirstItem.getScore()); + Assertions.assertNotNull(responseResultsFirstItem.getHighlights()); + } +} diff --git a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/generated/SearchIndexSearchDocumentsPostTests.java b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/generated/SearchIndexSearchDocumentsPostTests.java new file mode 100644 index 000000000000..a61ff231e30e --- /dev/null +++ b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/generated/SearchIndexSearchDocumentsPostTests.java @@ -0,0 +1,108 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.search.documents.generated; + +import com.azure.search.documents.models.HybridCountAndFacetMode; +import com.azure.search.documents.models.HybridSearch; +import com.azure.search.documents.models.QueryAnswerResult; +import com.azure.search.documents.models.QueryAnswerType; +import com.azure.search.documents.models.QueryCaptionResult; +import com.azure.search.documents.models.QueryCaptionType; +import com.azure.search.documents.models.QueryLanguage; +import com.azure.search.documents.models.QueryRewritesType; +import com.azure.search.documents.models.QuerySpellerType; +import com.azure.search.documents.models.QueryType; +import com.azure.search.documents.models.ScoringStatistics; +import com.azure.search.documents.models.SearchDocumentsResult; +import com.azure.search.documents.models.SearchMode; +import com.azure.search.documents.models.SearchRequest; +import com.azure.search.documents.models.SearchResult; +import com.azure.search.documents.models.SemanticErrorMode; +import com.azure.search.documents.models.VectorFilterMode; +import com.azure.search.documents.models.VectorSimilarityThreshold; +import com.azure.search.documents.models.VectorizedQuery; +import java.util.Arrays; +import java.util.List; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + +@Disabled +public final class SearchIndexSearchDocumentsPostTests extends SearchClientTestBase { + @Test + @Disabled + public void testSearchIndexSearchDocumentsPostTests() { + // method invocation + SearchDocumentsResult response = documentsClient.searchPost("preview-test", + new SearchRequest().setIncludeTotalResultCount(true) + .setFacets(Arrays.asList("ownerId", "price,metric:sum,default:10")) + .setFilter("category eq 'purple' or category eq 'pink'") + .setHighlightFields("category") + .setHighlightPostTag("") + .setHighlightPreTag("") + .setMinimumCoverage(100.0D) + .setQueryType(QueryType.SEMANTIC) + .setScoringStatistics(ScoringStatistics.GLOBAL) + .setSessionId("mysessionid") + .setScoringParameters(Arrays.asList("categoryTag:desiredCategoryValue")) + .setScoringProfile("stringFieldBoost") + .setSearchText("purple") + .setSearchFields("id,name,description,category,ownerId") + .setSearchMode(SearchMode.ANY) + .setQueryLanguage(QueryLanguage.EN_US) + .setSpeller(QuerySpellerType.LEXICON) + .setSelect("id,name,description,category,ownerId") + .setSkip(0) + .setTop(10) + .setSemanticConfiguration("testconfig") + .setSemanticErrorHandling(SemanticErrorMode.PARTIAL) + .setSemanticMaxWaitInMilliseconds(5000) + .setSemanticQuery("find all purple") + .setAnswers(QueryAnswerType.EXTRACTIVE) + .setCaptions(QueryCaptionType.EXTRACTIVE) + .setQueryRewrites(QueryRewritesType.GENERATIVE) + .setVectorQueries( + Arrays.asList(new VectorizedQuery(Arrays.asList(0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0)) + .setKNearestNeighbors(50) + .setFields("vector22, vector1b") + .setOversampling(20.0D) + .setWeight(1.0D) + .setThreshold(new VectorSimilarityThreshold(0.984)) + .setFilterOverride("ownerId eq 'sam'"))) + .setVectorFilterMode(VectorFilterMode.PRE_FILTER) + .setHybridSearch(new HybridSearch().setMaxTextRecallSize(100) + .setCountAndFacetMode(HybridCountAndFacetMode.COUNT_ALL_RESULTS))); + + // response assertion + Assertions.assertNotNull(response); + // verify property "count" + Assertions.assertEquals(27L, response.getCount()); + // verify property "coverage" + Assertions.assertEquals(100.0D, response.getCoverage()); + // verify property "facets" + Assertions.assertNotNull(response.getFacets()); + // verify property "answers" + List responseAnswers = response.getAnswers(); + QueryAnswerResult responseAnswersFirstItem = responseAnswers.iterator().next(); + Assertions.assertNotNull(responseAnswersFirstItem); + Assertions.assertEquals(0.8240000009536743D, responseAnswersFirstItem.getScore()); + Assertions.assertEquals("empty-vectors", responseAnswersFirstItem.getKey()); + Assertions.assertEquals("no vector.", responseAnswersFirstItem.getText()); + Assertions.assertEquals("no vector.", responseAnswersFirstItem.getHighlights()); + // verify property "results" + List responseResults = response.getResults(); + SearchResult responseResultsFirstItem = responseResults.iterator().next(); + Assertions.assertNotNull(responseResultsFirstItem); + Assertions.assertEquals(0.012820512987673283, responseResultsFirstItem.getScore()); + Assertions.assertEquals(1.788736343383789D, responseResultsFirstItem.getRerankerScore()); + Assertions.assertNotNull(responseResultsFirstItem.getHighlights()); + List responseResultsFirstItemCaptions = responseResultsFirstItem.getCaptions(); + QueryCaptionResult responseResultsFirstItemCaptionsFirstItem + = responseResultsFirstItemCaptions.iterator().next(); + Assertions.assertNotNull(responseResultsFirstItemCaptionsFirstItem); + Assertions.assertEquals("no vector.", responseResultsFirstItemCaptionsFirstItem.getText()); + Assertions.assertEquals("no vector.", responseResultsFirstItemCaptionsFirstItem.getHighlights()); + } +} diff --git a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/generated/SearchIndexSearchDocumentsSemanticGetTests.java b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/generated/SearchIndexSearchDocumentsSemanticGetTests.java new file mode 100644 index 000000000000..a7f5afa51986 --- /dev/null +++ b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/generated/SearchIndexSearchDocumentsSemanticGetTests.java @@ -0,0 +1,64 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.search.documents.generated; + +import com.azure.search.documents.models.QueryAnswerResult; +import com.azure.search.documents.models.QueryAnswerType; +import com.azure.search.documents.models.QueryCaptionResult; +import com.azure.search.documents.models.QueryCaptionType; +import com.azure.search.documents.models.QueryType; +import com.azure.search.documents.models.SearchDocumentsResult; +import com.azure.search.documents.models.SearchResult; +import com.azure.search.documents.models.SemanticErrorMode; +import java.util.List; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + +@Disabled +public final class SearchIndexSearchDocumentsSemanticGetTests extends SearchClientTestBase { + @Test + @Disabled + public void testSearchIndexSearchDocumentsSemanticGetTests() { + // method invocation + SearchDocumentsResult response = documentsClient.searchGet("myindex", "how do clouds form", true, null, null, + null, "", "", null, null, QueryType.SEMANTIC, null, null, null, null, null, null, null, null, null, + "my-semantic-config", SemanticErrorMode.PARTIAL, 780, QueryAnswerType.fromString("extractive|count-3"), + QueryCaptionType.fromString("extractive|highlight-true"), null, null, null, null, null, null); + + // response assertion + Assertions.assertNotNull(response); + // verify property "count" + Assertions.assertEquals(25L, response.getCount()); + // verify property "answers" + List responseAnswers = response.getAnswers(); + QueryAnswerResult responseAnswersFirstItem = responseAnswers.iterator().next(); + Assertions.assertNotNull(responseAnswersFirstItem); + Assertions.assertEquals(0.94639826D, responseAnswersFirstItem.getScore()); + Assertions.assertEquals("4123", responseAnswersFirstItem.getKey()); + Assertions.assertEquals( + "Sunlight heats the land all day, warming that moist air and causing it to rise high into the atmosphere until it cools and condenses into water droplets. Clouds generally form where air is ascending (over land in this case), but not where it is descending (over the river).", + responseAnswersFirstItem.getText()); + Assertions.assertEquals( + "Sunlight heats the land all day, warming that moist air and causing it to rise high into the atmosphere until it cools and condenses into water droplets. Clouds generally form where air is ascending (over land in this case), but not where it is descending (over the river).", + responseAnswersFirstItem.getHighlights()); + // verify property "results" + List responseResults = response.getResults(); + SearchResult responseResultsFirstItem = responseResults.iterator().next(); + Assertions.assertNotNull(responseResultsFirstItem); + Assertions.assertEquals(0.5479723, responseResultsFirstItem.getScore()); + Assertions.assertEquals(1.0321671911515296D, responseResultsFirstItem.getRerankerScore()); + List responseResultsFirstItemCaptions = responseResultsFirstItem.getCaptions(); + QueryCaptionResult responseResultsFirstItemCaptionsFirstItem + = responseResultsFirstItemCaptions.iterator().next(); + Assertions.assertNotNull(responseResultsFirstItemCaptionsFirstItem); + Assertions.assertEquals( + "Like all clouds, it forms when the air reaches its dew point—the temperature at which an air mass is cool enough for its water vapor to condense into liquid droplets. This false-color image shows valley fog, which is common in the Pacific Northwest of North America.", + responseResultsFirstItemCaptionsFirstItem.getText()); + Assertions.assertEquals( + "Like all clouds, it forms when the air reaches its dew point—the temperature at which an air mass is cool enough for its water vapor to condense into liquid droplets. This false-color image shows valley fog, which is common in the Pacific Northwest of North America.", + responseResultsFirstItemCaptionsFirstItem.getHighlights()); + } +} diff --git a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/generated/SearchIndexSearchDocumentsSemanticPostTests.java b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/generated/SearchIndexSearchDocumentsSemanticPostTests.java new file mode 100644 index 000000000000..5c20bc4c29c5 --- /dev/null +++ b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/generated/SearchIndexSearchDocumentsSemanticPostTests.java @@ -0,0 +1,93 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.search.documents.generated; + +import com.azure.search.documents.models.QueryAnswerResult; +import com.azure.search.documents.models.QueryAnswerType; +import com.azure.search.documents.models.QueryCaptionResult; +import com.azure.search.documents.models.QueryCaptionType; +import com.azure.search.documents.models.QueryType; +import com.azure.search.documents.models.SearchDocumentsResult; +import com.azure.search.documents.models.SearchRequest; +import com.azure.search.documents.models.SearchResult; +import com.azure.search.documents.models.SemanticErrorMode; +import java.util.List; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + +@Disabled +public final class SearchIndexSearchDocumentsSemanticPostTests extends SearchClientTestBase { + @Test + @Disabled + public void testSearchIndexSearchDocumentsSemanticPostTests() { + // method invocation + SearchDocumentsResult response = documentsClient.searchPost("myindex", + new SearchRequest().setIncludeTotalResultCount(true) + .setHighlightPostTag("") + .setHighlightPreTag("") + .setQueryType(QueryType.SEMANTIC) + .setSearchText("how do clouds form") + .setSemanticConfiguration("my-semantic-config") + .setSemanticErrorHandling(SemanticErrorMode.PARTIAL) + .setSemanticMaxWaitInMilliseconds(780) + .setAnswers(QueryAnswerType.fromString("extractive|count-3")) + .setCaptions(QueryCaptionType.fromString("extractive|highlight-true"))); + + // response assertion + Assertions.assertNotNull(response); + // verify property "count" + Assertions.assertEquals(25L, response.getCount()); + // verify property "answers" + List responseAnswers = response.getAnswers(); + QueryAnswerResult responseAnswersFirstItem = responseAnswers.iterator().next(); + Assertions.assertNotNull(responseAnswersFirstItem); + Assertions.assertEquals(0.94639826D, responseAnswersFirstItem.getScore()); + Assertions.assertEquals("4123", responseAnswersFirstItem.getKey()); + Assertions.assertEquals( + "Sunlight heats the land all day, warming that moist air and causing it to rise high into the atmosphere until it cools and condenses into water droplets. Clouds generally form where air is ascending (over land in this case), but not where it is descending (over the river).", + responseAnswersFirstItem.getText()); + Assertions.assertEquals( + "Sunlight heats the land all day, warming that moist air and causing it to rise high into the atmosphere until it cools and condenses into water droplets. Clouds generally form where air is ascending (over land in this case), but not where it is descending (over the river).", + responseAnswersFirstItem.getHighlights()); + // verify property "nextPageParameters" + SearchRequest responseNextPageParameters = response.getNextPageParameters(); + Assertions.assertNotNull(responseNextPageParameters); + Assertions.assertEquals(true, responseNextPageParameters.isIncludeTotalResultCount()); + Assertions.assertEquals("", responseNextPageParameters.getHighlightPostTag()); + Assertions.assertEquals("", responseNextPageParameters.getHighlightPreTag()); + Assertions.assertEquals(QueryType.SEMANTIC, responseNextPageParameters.getQueryType()); + Assertions.assertEquals("how do clouds form", responseNextPageParameters.getSearchText()); + Assertions.assertEquals(2, responseNextPageParameters.getSkip()); + Assertions.assertEquals(8, responseNextPageParameters.getTop()); + Assertions.assertEquals("my-semantic-config", responseNextPageParameters.getSemanticConfiguration()); + Assertions.assertEquals(SemanticErrorMode.PARTIAL, responseNextPageParameters.getSemanticErrorHandling()); + Assertions.assertEquals(780, responseNextPageParameters.getSemanticMaxWaitInMilliseconds()); + Assertions.assertEquals(QueryAnswerType.fromString("extractive|count-3"), + responseNextPageParameters.getAnswers()); + Assertions.assertEquals(QueryCaptionType.fromString("extractive|highlight-true"), + responseNextPageParameters.getCaptions()); + // verify property "results" + List responseResults = response.getResults(); + SearchResult responseResultsFirstItem = responseResults.iterator().next(); + Assertions.assertNotNull(responseResultsFirstItem); + Assertions.assertEquals(0.5479723, responseResultsFirstItem.getScore()); + Assertions.assertEquals(1.0321671911515296D, responseResultsFirstItem.getRerankerScore()); + List responseResultsFirstItemCaptions = responseResultsFirstItem.getCaptions(); + QueryCaptionResult responseResultsFirstItemCaptionsFirstItem + = responseResultsFirstItemCaptions.iterator().next(); + Assertions.assertNotNull(responseResultsFirstItemCaptionsFirstItem); + Assertions.assertEquals( + "Like all clouds, it forms when the air reaches its dew point—the temperature at which an air mass is cool enough for its water vapor to condense into liquid droplets. This false-color image shows valley fog, which is common in the Pacific Northwest of North America.", + responseResultsFirstItemCaptionsFirstItem.getText()); + Assertions.assertEquals( + "Like all clouds, it forms when the air reaches its dew point—the temperature at which an air mass is cool enough for its water vapor to condense into liquid droplets. This false-color image shows valley fog, which is common in the Pacific Northwest of North America.", + responseResultsFirstItemCaptionsFirstItem.getHighlights()); + // verify property "nextLink" + Assertions.assertEquals( + "https://myservice.search.windows.net/indexes('myindex')/docs/search.post.search?api-version=2025-03-01-preview", + response.getNextLink()); + } +} diff --git a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/generated/SearchIndexSuggestDocumentsGetTests.java b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/generated/SearchIndexSuggestDocumentsGetTests.java new file mode 100644 index 000000000000..ca6911160457 --- /dev/null +++ b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/generated/SearchIndexSuggestDocumentsGetTests.java @@ -0,0 +1,33 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.search.documents.generated; + +import com.azure.search.documents.models.SuggestDocumentsResult; +import com.azure.search.documents.models.SuggestResult; +import java.util.Arrays; +import java.util.List; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + +@Disabled +public final class SearchIndexSuggestDocumentsGetTests extends SearchClientTestBase { + @Test + @Disabled + public void testSearchIndexSuggestDocumentsGetTests() { + // method invocation + SuggestDocumentsResult response = documentsClient.suggestGet("hote", "sg", "myindex", "rating gt 10", false, + "", "", 80.0D, Arrays.asList("search.score() desc", "rating desc"), Arrays.asList("title"), + Arrays.asList("docId", "title", "description"), 10); + + // response assertion + Assertions.assertNotNull(response); + // verify property "results" + List responseResults = response.getResults(); + SuggestResult responseResultsFirstItem = responseResults.iterator().next(); + Assertions.assertNotNull(responseResultsFirstItem); + Assertions.assertEquals("Nice Hotel", responseResultsFirstItem.getText()); + } +} diff --git a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/generated/SearchIndexSuggestDocumentsPostTests.java b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/generated/SearchIndexSuggestDocumentsPostTests.java new file mode 100644 index 000000000000..2a915cd5e089 --- /dev/null +++ b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/generated/SearchIndexSuggestDocumentsPostTests.java @@ -0,0 +1,42 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.search.documents.generated; + +import com.azure.search.documents.models.SuggestDocumentsResult; +import com.azure.search.documents.models.SuggestRequest; +import com.azure.search.documents.models.SuggestResult; +import java.util.List; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + +@Disabled +public final class SearchIndexSuggestDocumentsPostTests extends SearchClientTestBase { + @Test + @Disabled + public void testSearchIndexSuggestDocumentsPostTests() { + // method invocation + SuggestDocumentsResult response = documentsClient.suggestPost("preview-test", + new SuggestRequest("p", "sg").setFilter("ownerId eq 'sam' and id lt '15'") + .setUseFuzzyMatching(true) + .setHighlightPostTag("") + .setHighlightPreTag("") + .setMinimumCoverage(80.0D) + .setOrderBy("id desc") + .setSearchFields("category") + .setSelect("id,name,category,ownerId") + .setTop(10)); + + // response assertion + Assertions.assertNotNull(response); + // verify property "results" + List responseResults = response.getResults(); + SuggestResult responseResultsFirstItem = responseResults.iterator().next(); + Assertions.assertNotNull(responseResultsFirstItem); + Assertions.assertEquals("purple", responseResultsFirstItem.getText()); + // verify property "coverage" + Assertions.assertEquals(100.0D, response.getCoverage()); + } +} diff --git a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/generated/SearchServiceCreateAliasTests.java b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/generated/SearchServiceCreateAliasTests.java new file mode 100644 index 000000000000..9829b4534374 --- /dev/null +++ b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/generated/SearchServiceCreateAliasTests.java @@ -0,0 +1,30 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.search.documents.generated; + +import com.azure.search.documents.models.SearchAlias; +import java.util.Arrays; +import java.util.List; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + +@Disabled +public final class SearchServiceCreateAliasTests extends SearchClientTestBase { + @Test + @Disabled + public void testSearchServiceCreateAliasTests() { + // method invocation + SearchAlias response = aliasesClient.create(new SearchAlias("tempalias", Arrays.asList("preview-test"))); + + // response assertion + Assertions.assertNotNull(response); + // verify property "name" + Assertions.assertEquals("tempalias", response.getName()); + // verify property "indexes" + List responseIndexes = response.getIndexes(); + Assertions.assertEquals("preview-test", responseIndexes.iterator().next()); + } +} diff --git a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/generated/SearchServiceCreateDataSourceTests.java b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/generated/SearchServiceCreateDataSourceTests.java new file mode 100644 index 000000000000..ad3b6308664f --- /dev/null +++ b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/generated/SearchServiceCreateDataSourceTests.java @@ -0,0 +1,93 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.search.documents.generated; + +import com.azure.search.documents.models.AzureActiveDirectoryApplicationCredentials; +import com.azure.search.documents.models.DataChangeDetectionPolicy; +import com.azure.search.documents.models.DataDeletionDetectionPolicy; +import com.azure.search.documents.models.DataSourceCredentials; +import com.azure.search.documents.models.HighWaterMarkChangeDetectionPolicy; +import com.azure.search.documents.models.SearchIndexerDataContainer; +import com.azure.search.documents.models.SearchIndexerDataIdentity; +import com.azure.search.documents.models.SearchIndexerDataNoneIdentity; +import com.azure.search.documents.models.SearchIndexerDataSource; +import com.azure.search.documents.models.SearchIndexerDataSourceType; +import com.azure.search.documents.models.SearchResourceEncryptionKey; +import com.azure.search.documents.models.SoftDeleteColumnDeletionDetectionPolicy; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + +@Disabled +public final class SearchServiceCreateDataSourceTests extends SearchClientTestBase { + @Test + @Disabled + public void testSearchServiceCreateDataSourceTests() { + // method invocation + SearchIndexerDataSource response = dataSourcesClient.create(new SearchIndexerDataSource("tempdatasource", + SearchIndexerDataSourceType.AZURE_BLOB, + new DataSourceCredentials().setConnectionString( + "DefaultEndpointsProtocol=https;AccountName=myAccountName;AccountKey=myAccountKey;EndpointSuffix=core.windows.net "), + new SearchIndexerDataContainer("doc-extraction-skillset").setQuery("E2E_Dsat")) + .setDescription("My Azure Blob data source.") + .setIdentity(new SearchIndexerDataNoneIdentity()) + .setDataChangeDetectionPolicy(new HighWaterMarkChangeDetectionPolicy("metadata_storage_last_modified")) + .setDataDeletionDetectionPolicy( + new SoftDeleteColumnDeletionDetectionPolicy().setSoftDeleteColumnName("isDeleted") + .setSoftDeleteMarkerValue("true")) + .setEncryptionKey(new SearchResourceEncryptionKey("fakeTokenPlaceholder", "fakeTokenPlaceholder") + .setKeyVersion("fakeTokenPlaceholder") + .setAccessCredentials( + new AzureActiveDirectoryApplicationCredentials("00000000-0000-0000-0000-000000000000") + .setApplicationSecret("fakeTokenPlaceholder")))); + + // response assertion + Assertions.assertNotNull(response); + // verify property "name" + Assertions.assertEquals("tempdatasource", response.getName()); + // verify property "description" + Assertions.assertEquals("My Azure Blob data source.", response.getDescription()); + // verify property "type" + Assertions.assertEquals(SearchIndexerDataSourceType.AZURE_BLOB, response.getType()); + // verify property "credentials" + DataSourceCredentials responseCredentials = response.getCredentials(); + Assertions.assertNotNull(responseCredentials); + Assertions.assertEquals( + "DefaultEndpointsProtocol=https;AccountName=myAccountName;AccountKey=myAccountKey;EndpointSuffix=core.windows.net ", + responseCredentials.getConnectionString()); + // verify property "container" + SearchIndexerDataContainer responseContainer = response.getContainer(); + Assertions.assertNotNull(responseContainer); + Assertions.assertEquals("doc-extraction-skillset", responseContainer.getName()); + Assertions.assertEquals("E2E_Dsat", responseContainer.getQuery()); + // verify property "identity" + SearchIndexerDataIdentity responseIdentity = response.getIdentity(); + Assertions.assertNotNull(responseIdentity); + Assertions.assertEquals("#Microsoft.Azure.Search.DataNoneIdentity", responseIdentity.getOdataType()); + // verify property "dataChangeDetectionPolicy" + DataChangeDetectionPolicy responseDataChangeDetectionPolicy = response.getDataChangeDetectionPolicy(); + Assertions.assertNotNull(responseDataChangeDetectionPolicy); + Assertions.assertEquals("#Microsoft.Azure.Search.HighWaterMarkChangeDetectionPolicy", + responseDataChangeDetectionPolicy.getOdataType()); + // verify property "dataDeletionDetectionPolicy" + DataDeletionDetectionPolicy responseDataDeletionDetectionPolicy = response.getDataDeletionDetectionPolicy(); + Assertions.assertNotNull(responseDataDeletionDetectionPolicy); + Assertions.assertEquals("#Microsoft.Azure.Search.SoftDeleteColumnDeletionDetectionPolicy", + responseDataDeletionDetectionPolicy.getOdataType()); + // verify property "encryptionKey" + SearchResourceEncryptionKey responseEncryptionKey = response.getEncryptionKey(); + Assertions.assertNotNull(responseEncryptionKey); + Assertions.assertEquals("myUserManagedEncryptionKey-createdinAzureKeyVault", + responseEncryptionKey.getKeyName()); + Assertions.assertEquals("myKeyVersion-32charAlphaNumericString", responseEncryptionKey.getKeyVersion()); + Assertions.assertEquals("https://myKeyVault.vault.azure.net", responseEncryptionKey.getVaultUri()); + AzureActiveDirectoryApplicationCredentials responseEncryptionKeyAccessCredentials + = responseEncryptionKey.getAccessCredentials(); + Assertions.assertNotNull(responseEncryptionKeyAccessCredentials); + Assertions.assertEquals("00000000-0000-0000-0000-000000000000", + responseEncryptionKeyAccessCredentials.getApplicationId()); + Assertions.assertEquals("", responseEncryptionKeyAccessCredentials.getApplicationSecret()); + } +} diff --git a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/generated/SearchServiceCreateIndexTests.java b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/generated/SearchServiceCreateIndexTests.java new file mode 100644 index 000000000000..70676ef6205d --- /dev/null +++ b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/generated/SearchServiceCreateIndexTests.java @@ -0,0 +1,398 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.search.documents.generated; + +import com.azure.search.documents.models.AIFoundryModelCatalogName; +import com.azure.search.documents.models.AsciiFoldingTokenFilter; +import com.azure.search.documents.models.AzureMachineLearningParameters; +import com.azure.search.documents.models.AzureMachineLearningVectorizer; +import com.azure.search.documents.models.AzureOpenAIModelName; +import com.azure.search.documents.models.AzureOpenAIVectorizer; +import com.azure.search.documents.models.AzureOpenAIVectorizerParameters; +import com.azure.search.documents.models.BM25SimilarityAlgorithm; +import com.azure.search.documents.models.BinaryQuantizationCompression; +import com.azure.search.documents.models.CharFilter; +import com.azure.search.documents.models.CharFilterName; +import com.azure.search.documents.models.CorsOptions; +import com.azure.search.documents.models.CustomAnalyzer; +import com.azure.search.documents.models.CustomNormalizer; +import com.azure.search.documents.models.HnswAlgorithmConfiguration; +import com.azure.search.documents.models.HnswParameters; +import com.azure.search.documents.models.LexicalAnalyzer; +import com.azure.search.documents.models.LexicalAnalyzerName; +import com.azure.search.documents.models.LexicalNormalizer; +import com.azure.search.documents.models.LexicalTokenizer; +import com.azure.search.documents.models.LexicalTokenizerName; +import com.azure.search.documents.models.LuceneStandardTokenizerV2; +import com.azure.search.documents.models.MappingCharFilter; +import com.azure.search.documents.models.RescoringOptions; +import com.azure.search.documents.models.ScalarQuantizationCompression; +import com.azure.search.documents.models.ScalarQuantizationParameters; +import com.azure.search.documents.models.ScoringFunction; +import com.azure.search.documents.models.ScoringFunctionAggregation; +import com.azure.search.documents.models.ScoringFunctionInterpolation; +import com.azure.search.documents.models.ScoringProfile; +import com.azure.search.documents.models.SearchField; +import com.azure.search.documents.models.SearchFieldDataType; +import com.azure.search.documents.models.SearchIndex; +import com.azure.search.documents.models.SearchIndexerDataNoneIdentity; +import com.azure.search.documents.models.SearchSuggester; +import com.azure.search.documents.models.SemanticConfiguration; +import com.azure.search.documents.models.SemanticField; +import com.azure.search.documents.models.SemanticPrioritizedFields; +import com.azure.search.documents.models.SemanticSearch; +import com.azure.search.documents.models.SimilarityAlgorithm; +import com.azure.search.documents.models.TagScoringFunction; +import com.azure.search.documents.models.TagScoringParameters; +import com.azure.search.documents.models.TextWeights; +import com.azure.search.documents.models.TokenFilter; +import com.azure.search.documents.models.TokenFilterName; +import com.azure.search.documents.models.VectorSearch; +import com.azure.search.documents.models.VectorSearchAlgorithmConfiguration; +import com.azure.search.documents.models.VectorSearchAlgorithmKind; +import com.azure.search.documents.models.VectorSearchAlgorithmMetric; +import com.azure.search.documents.models.VectorSearchCompression; +import com.azure.search.documents.models.VectorSearchCompressionKind; +import com.azure.search.documents.models.VectorSearchCompressionRescoreStorageMethod; +import com.azure.search.documents.models.VectorSearchCompressionTarget; +import com.azure.search.documents.models.VectorSearchProfile; +import com.azure.search.documents.models.VectorSearchVectorizer; +import com.azure.search.documents.models.VectorSearchVectorizerKind; +import com.azure.search.documents.models.WebApiVectorizer; +import com.azure.search.documents.models.WebApiVectorizerParameters; +import java.time.Duration; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + +@Disabled +public final class SearchServiceCreateIndexTests extends SearchClientTestBase { + @Test + @Disabled + public void testSearchServiceCreateIndexTests() { + // method invocation + SearchIndex response = indexesClient.create(new SearchIndex("temp-preview-test", Arrays.asList( + new SearchField("id", SearchFieldDataType.STRING).setKey(true).setSortable(true), + new SearchField("vector1", SearchFieldDataType.fromString("Collection(Edm.Single)")).setRetrievable(true) + .setSearchable(true) + .setVectorSearchDimensions(20) + .setVectorSearchProfileName("config1"), + new SearchField("vector1b", SearchFieldDataType.fromString("Collection(Edm.Single)")).setRetrievable(true) + .setSearchable(true) + .setVectorSearchDimensions(10) + .setVectorSearchProfileName("config2"), + new SearchField("vector2", SearchFieldDataType.fromString("Collection(Edm.Single)")).setRetrievable(true) + .setSearchable(true) + .setVectorSearchDimensions(5) + .setVectorSearchProfileName("config3"), + new SearchField("vector3", SearchFieldDataType.fromString("Collection(Edm.Single)")).setRetrievable(true) + .setSearchable(true) + .setVectorSearchDimensions(5) + .setVectorSearchProfileName("config3"), + new SearchField("vector22", SearchFieldDataType.fromString("Collection(Edm.Single)")).setRetrievable(true) + .setSearchable(true) + .setVectorSearchDimensions(10) + .setVectorSearchProfileName("config2"), + new SearchField("vector4", SearchFieldDataType.fromString("Collection(Edm.Single)")).setRetrievable(true) + .setSearchable(true) + .setVectorSearchDimensions(32) + .setVectorSearchProfileName("config4"), + new SearchField("name", SearchFieldDataType.STRING).setRetrievable(true) + .setSearchable(true) + .setFilterable(true) + .setSortable(true) + .setFacetable(true) + .setAnalyzer(LexicalAnalyzerName.EN_LUCENE), + new SearchField("description", SearchFieldDataType.STRING).setRetrievable(true) + .setSearchable(true) + .setFilterable(true) + .setSortable(true) + .setFacetable(true) + .setAnalyzer(LexicalAnalyzerName.STANDARD_LUCENE), + new SearchField("category", SearchFieldDataType.STRING).setRetrievable(true) + .setSearchable(true) + .setFilterable(true) + .setSortable(true) + .setFacetable(true) + .setAnalyzer(LexicalAnalyzerName.EN_LUCENE), + new SearchField("ownerId", SearchFieldDataType.STRING).setRetrievable(true) + .setSearchable(true) + .setFilterable(true) + .setSortable(true) + .setFacetable(true) + .setAnalyzer(LexicalAnalyzerName.EN_LUCENE), + new SearchField("price", SearchFieldDataType.DOUBLE).setRetrievable(true) + .setFilterable(true) + .setSortable(true) + .setFacetable(true))) + .setScoringProfiles(Arrays.asList(new ScoringProfile("stringFieldBoost") + .setTextWeights( + new TextWeights(mapOf("name", 3.0, "description", 1.0, "category", 2.0, "ownerId", 1.0))) + .setFunctions(Arrays + .asList(new TagScoringFunction("category", 2.0, new TagScoringParameters("categoryTag")))))) + .setDefaultScoringProfile("stringFieldBoost") + .setCorsOptions( + new CorsOptions(Arrays.asList("https://www.example.com/foo")).setMaxAgeInSeconds(10L)) + .setSuggesters(Arrays.asList(new SearchSuggester("sg", Arrays.asList("category", "ownerId")))) + .setAnalyzers(Arrays.asList(new CustomAnalyzer("tagsAnalyzer", LexicalTokenizerName.STANDARD) + .setTokenFilters(Arrays.asList(TokenFilterName.COMMON_GRAM)) + .setCharFilters(Arrays.asList(CharFilterName.HTML_STRIP)))) + .setTokenizers(Arrays.asList(new LuceneStandardTokenizerV2("my_tokenizer").setMaxTokenLength(100))) + .setTokenFilters( + Arrays.asList(new AsciiFoldingTokenFilter("my_tokenFilter").setPreserveOriginal(false))) + .setCharFilters(Arrays.asList(new MappingCharFilter("my_mapping", Arrays.asList(".=>,", "_=>-")))) + .setNormalizers(Arrays.asList(new CustomNormalizer("my_normalizer") + .setTokenFilters(Arrays.asList(TokenFilterName.fromString("my_tokenFilter"))) + .setCharFilters(Arrays.asList(CharFilterName.fromString("my_mapping"))))) + .setSimilarity(new BM25SimilarityAlgorithm().setK1(10.0D).setB(0.1D)) + .setSemanticSearch(new SemanticSearch().setDefaultConfigurationName("testconfig") + .setConfigurations(Arrays.asList(new SemanticConfiguration("testconfig", + new SemanticPrioritizedFields().setTitleField(new SemanticField("category")) + .setContentFields(Arrays.asList(new SemanticField("description"))) + .setKeywordsFields(Arrays.asList(new SemanticField("ownerId")))) + .setFlightingOptIn(true)))) + .setVectorSearch(new VectorSearch() + .setProfiles(Arrays.asList( + new VectorSearchProfile("config1", "cosine").setVectorizerName("openai") + .setCompressionName("mySQ8"), + new VectorSearchProfile("config2", "euclidean").setVectorizerName("custom-web-api") + .setCompressionName("mySQ8"), + new VectorSearchProfile("config3", "dotProduct").setVectorizerName("custom-web-api") + .setCompressionName("myBQC"), + new VectorSearchProfile("config4", "dotProduct").setVectorizerName("custom-web-api") + .setCompressionName("myBQWithoutOriginals"))) + .setAlgorithms(Arrays.asList( + new HnswAlgorithmConfiguration("cosine") + .setParameters(new HnswParameters().setMetric(VectorSearchAlgorithmMetric.COSINE)), + new HnswAlgorithmConfiguration("euclidean") + .setParameters(new HnswParameters().setMetric(VectorSearchAlgorithmMetric.EUCLIDEAN)), + new HnswAlgorithmConfiguration("dotProduct").setParameters( + new HnswParameters().setMetric(VectorSearchAlgorithmMetric.DOT_PRODUCT)))) + .setVectorizers(Arrays.asList( + new AzureOpenAIVectorizer("openai").setParameters(new AzureOpenAIVectorizerParameters() + .setResourceUrl("https://test-sample.openai.azure.com/") + .setDeploymentName("model") + .setApiKey("fakeTokenPlaceholder") + .setModelName(AzureOpenAIModelName.TEXT_EMBEDDING3LARGE)), + new WebApiVectorizer("custom-web-api").setWebApiParameters( + new WebApiVectorizerParameters().setUrl("https://my-custom-endpoint.org/") + .setHttpHeaders(mapOf("header1", "value1", "header2", "value2")) + .setHttpMethod("POST") + .setTimeout(Duration.parse("PT1M")) + .setAuthResourceId("api://f89d1c93-58a7-4b07-9a5b-5f89048b927b") + .setAuthIdentity(new SearchIndexerDataNoneIdentity())), + new AzureMachineLearningVectorizer("aml") + .setAMLParameters(new AzureMachineLearningParameters("https://my-custom-endpoint.org/") + .setResourceId("aml resource id") + .setTimeout(Duration.parse("PT1M")) + .setRegion("aml region") + .setModelName( + AIFoundryModelCatalogName.OPEN_AICLIPIMAGE_TEXT_EMBEDDINGS_VIT_BASE_PATCH32)))) + .setCompressions(Arrays.asList( + new ScalarQuantizationCompression("mySQ8") + .setRescoringOptions(new RescoringOptions().setEnableRescoring(true) + .setDefaultOversampling(10.0D) + .setRescoreStorageMethod( + VectorSearchCompressionRescoreStorageMethod.PRESERVE_ORIGINALS)) + .setTruncationDimension(2) + .setParameters(new ScalarQuantizationParameters() + .setQuantizedDataType(VectorSearchCompressionTarget.INT8)), + new BinaryQuantizationCompression("myBQC") + .setRescoringOptions(new RescoringOptions().setEnableRescoring(true) + .setDefaultOversampling(10.0D) + .setRescoreStorageMethod( + VectorSearchCompressionRescoreStorageMethod.PRESERVE_ORIGINALS)) + .setTruncationDimension(2), + new BinaryQuantizationCompression("myBQWithoutOriginals") + .setRescoringOptions(new RescoringOptions().setEnableRescoring(true) + .setDefaultOversampling(10.0D) + .setRescoreStorageMethod( + VectorSearchCompressionRescoreStorageMethod.DISCARD_ORIGINALS)) + .setTruncationDimension(2))))); + + // response assertion + Assertions.assertNotNull(response); + // verify property "name" + Assertions.assertEquals("temp-preview-test", response.getName()); + // verify property "fields" + List responseFields = response.getFields(); + SearchField responseFieldsFirstItem = responseFields.iterator().next(); + Assertions.assertNotNull(responseFieldsFirstItem); + Assertions.assertEquals("id", responseFieldsFirstItem.getName()); + Assertions.assertEquals(SearchFieldDataType.STRING, responseFieldsFirstItem.getType()); + Assertions.assertEquals(true, responseFieldsFirstItem.isKey()); + Assertions.assertEquals(true, responseFieldsFirstItem.isRetrievable()); + Assertions.assertEquals(true, responseFieldsFirstItem.isStored()); + Assertions.assertEquals(true, responseFieldsFirstItem.isSearchable()); + Assertions.assertEquals(true, responseFieldsFirstItem.isFilterable()); + Assertions.assertEquals(true, responseFieldsFirstItem.isSortable()); + Assertions.assertEquals(true, responseFieldsFirstItem.isFacetable()); + List responseFieldsFirstItemSynonymMaps = responseFieldsFirstItem.getSynonymMaps(); + Assertions.assertEquals(0, responseFieldsFirstItemSynonymMaps.size()); + // verify property "scoringProfiles" + List responseScoringProfiles = response.getScoringProfiles(); + ScoringProfile responseScoringProfilesFirstItem = responseScoringProfiles.iterator().next(); + Assertions.assertNotNull(responseScoringProfilesFirstItem); + Assertions.assertEquals("stringFieldBoost", responseScoringProfilesFirstItem.getName()); + TextWeights responseScoringProfilesFirstItemTextWeights = responseScoringProfilesFirstItem.getTextWeights(); + Assertions.assertNotNull(responseScoringProfilesFirstItemTextWeights); + Assertions.assertNotNull(responseScoringProfilesFirstItemTextWeights.getWeights()); + List responseScoringProfilesFirstItemFunctions + = responseScoringProfilesFirstItem.getFunctions(); + ScoringFunction responseScoringProfilesFirstItemFunctionsFirstItem + = responseScoringProfilesFirstItemFunctions.iterator().next(); + Assertions.assertNotNull(responseScoringProfilesFirstItemFunctionsFirstItem); + Assertions.assertEquals("tag", responseScoringProfilesFirstItemFunctionsFirstItem.getType()); + Assertions.assertEquals("category", responseScoringProfilesFirstItemFunctionsFirstItem.getFieldName()); + Assertions.assertEquals(2.0, responseScoringProfilesFirstItemFunctionsFirstItem.getBoost()); + Assertions.assertEquals(ScoringFunctionInterpolation.LINEAR, + responseScoringProfilesFirstItemFunctionsFirstItem.getInterpolation()); + Assertions.assertEquals(ScoringFunctionAggregation.SUM, + responseScoringProfilesFirstItem.getFunctionAggregation()); + // verify property "defaultScoringProfile" + Assertions.assertEquals("stringFieldBoost", response.getDefaultScoringProfile()); + // verify property "corsOptions" + CorsOptions responseCorsOptions = response.getCorsOptions(); + Assertions.assertNotNull(responseCorsOptions); + List responseCorsOptionsAllowedOrigins = responseCorsOptions.getAllowedOrigins(); + Assertions.assertEquals("https://www.example.com/foo", responseCorsOptionsAllowedOrigins.iterator().next()); + Assertions.assertEquals(10L, responseCorsOptions.getMaxAgeInSeconds()); + // verify property "suggesters" + List responseSuggesters = response.getSuggesters(); + SearchSuggester responseSuggestersFirstItem = responseSuggesters.iterator().next(); + Assertions.assertNotNull(responseSuggestersFirstItem); + Assertions.assertEquals("sg", responseSuggestersFirstItem.getName()); + Assertions.assertEquals("analyzingInfixMatching", responseSuggestersFirstItem.getSearchMode()); + List responseSuggestersFirstItemSourceFields = responseSuggestersFirstItem.getSourceFields(); + Assertions.assertEquals("category", responseSuggestersFirstItemSourceFields.iterator().next()); + // verify property "analyzers" + List responseAnalyzers = response.getAnalyzers(); + LexicalAnalyzer responseAnalyzersFirstItem = responseAnalyzers.iterator().next(); + Assertions.assertNotNull(responseAnalyzersFirstItem); + Assertions.assertEquals("#Microsoft.Azure.Search.CustomAnalyzer", responseAnalyzersFirstItem.getOdataType()); + Assertions.assertEquals("tagsAnalyzer", responseAnalyzersFirstItem.getName()); + // verify property "tokenizers" + List responseTokenizers = response.getTokenizers(); + LexicalTokenizer responseTokenizersFirstItem = responseTokenizers.iterator().next(); + Assertions.assertNotNull(responseTokenizersFirstItem); + Assertions.assertEquals("#Microsoft.Azure.Search.StandardTokenizerV2", + responseTokenizersFirstItem.getOdataType()); + Assertions.assertEquals("my_tokenizer", responseTokenizersFirstItem.getName()); + // verify property "tokenFilters" + List responseTokenFilters = response.getTokenFilters(); + TokenFilter responseTokenFiltersFirstItem = responseTokenFilters.iterator().next(); + Assertions.assertNotNull(responseTokenFiltersFirstItem); + Assertions.assertEquals("#Microsoft.Azure.Search.AsciiFoldingTokenFilter", + responseTokenFiltersFirstItem.getOdataType()); + Assertions.assertEquals("my_tokenFilter", responseTokenFiltersFirstItem.getName()); + // verify property "charFilters" + List responseCharFilters = response.getCharFilters(); + CharFilter responseCharFiltersFirstItem = responseCharFilters.iterator().next(); + Assertions.assertNotNull(responseCharFiltersFirstItem); + Assertions.assertEquals("#Microsoft.Azure.Search.MappingCharFilter", + responseCharFiltersFirstItem.getOdataType()); + Assertions.assertEquals("my_mapping", responseCharFiltersFirstItem.getName()); + // verify property "normalizers" + List responseNormalizers = response.getNormalizers(); + LexicalNormalizer responseNormalizersFirstItem = responseNormalizers.iterator().next(); + Assertions.assertNotNull(responseNormalizersFirstItem); + Assertions.assertEquals("#Microsoft.Azure.Search.CustomNormalizer", + responseNormalizersFirstItem.getOdataType()); + Assertions.assertEquals("my_normalizer", responseNormalizersFirstItem.getName()); + // verify property "similarity" + SimilarityAlgorithm responseSimilarity = response.getSimilarity(); + Assertions.assertNotNull(responseSimilarity); + Assertions.assertEquals("#Microsoft.Azure.Search.BM25Similarity", responseSimilarity.getOdataType()); + // verify property "semanticSearch" + SemanticSearch responseSemanticSearch = response.getSemanticSearch(); + Assertions.assertNotNull(responseSemanticSearch); + Assertions.assertEquals("testconfig", responseSemanticSearch.getDefaultConfigurationName()); + List responseSemanticSearchConfigurations = responseSemanticSearch.getConfigurations(); + SemanticConfiguration responseSemanticSearchConfigurationsFirstItem + = responseSemanticSearchConfigurations.iterator().next(); + Assertions.assertNotNull(responseSemanticSearchConfigurationsFirstItem); + Assertions.assertEquals("testconfig", responseSemanticSearchConfigurationsFirstItem.getName()); + SemanticPrioritizedFields responseSemanticSearchConfigurationsFirstItemPrioritizedFields + = responseSemanticSearchConfigurationsFirstItem.getPrioritizedFields(); + Assertions.assertNotNull(responseSemanticSearchConfigurationsFirstItemPrioritizedFields); + SemanticField responseSemanticSearchConfigurationsFirstItemPrioritizedFieldsTitleField + = responseSemanticSearchConfigurationsFirstItemPrioritizedFields.getTitleField(); + Assertions.assertNotNull(responseSemanticSearchConfigurationsFirstItemPrioritizedFieldsTitleField); + Assertions.assertEquals("category", + responseSemanticSearchConfigurationsFirstItemPrioritizedFieldsTitleField.getFieldName()); + List responseSemanticSearchConfigurationsFirstItemPrioritizedFieldsContentFields + = responseSemanticSearchConfigurationsFirstItemPrioritizedFields.getContentFields(); + SemanticField responseSemanticSearchConfigurationsFirstItemPrioritizedFieldsContentFieldsFirstItem + = responseSemanticSearchConfigurationsFirstItemPrioritizedFieldsContentFields.iterator().next(); + Assertions.assertNotNull(responseSemanticSearchConfigurationsFirstItemPrioritizedFieldsContentFieldsFirstItem); + Assertions.assertEquals("description", + responseSemanticSearchConfigurationsFirstItemPrioritizedFieldsContentFieldsFirstItem.getFieldName()); + List responseSemanticSearchConfigurationsFirstItemPrioritizedFieldsKeywordsFields + = responseSemanticSearchConfigurationsFirstItemPrioritizedFields.getKeywordsFields(); + SemanticField responseSemanticSearchConfigurationsFirstItemPrioritizedFieldsKeywordsFieldsFirstItem + = responseSemanticSearchConfigurationsFirstItemPrioritizedFieldsKeywordsFields.iterator().next(); + Assertions.assertNotNull(responseSemanticSearchConfigurationsFirstItemPrioritizedFieldsKeywordsFieldsFirstItem); + Assertions.assertEquals("ownerId", + responseSemanticSearchConfigurationsFirstItemPrioritizedFieldsKeywordsFieldsFirstItem.getFieldName()); + Assertions.assertEquals(false, responseSemanticSearchConfigurationsFirstItem.isFlightingOptIn()); + // verify property "vectorSearch" + VectorSearch responseVectorSearch = response.getVectorSearch(); + Assertions.assertNotNull(responseVectorSearch); + List responseVectorSearchProfiles = responseVectorSearch.getProfiles(); + VectorSearchProfile responseVectorSearchProfilesFirstItem = responseVectorSearchProfiles.iterator().next(); + Assertions.assertNotNull(responseVectorSearchProfilesFirstItem); + Assertions.assertEquals("config1", responseVectorSearchProfilesFirstItem.getName()); + Assertions.assertEquals("cosine", responseVectorSearchProfilesFirstItem.getAlgorithmConfigurationName()); + Assertions.assertEquals("openai", responseVectorSearchProfilesFirstItem.getVectorizerName()); + Assertions.assertEquals("mySQ8", responseVectorSearchProfilesFirstItem.getCompressionName()); + List responseVectorSearchAlgorithms = responseVectorSearch.getAlgorithms(); + VectorSearchAlgorithmConfiguration responseVectorSearchAlgorithmsFirstItem + = responseVectorSearchAlgorithms.iterator().next(); + Assertions.assertNotNull(responseVectorSearchAlgorithmsFirstItem); + Assertions.assertEquals(VectorSearchAlgorithmKind.HNSW, responseVectorSearchAlgorithmsFirstItem.getKind()); + Assertions.assertEquals("cosine", responseVectorSearchAlgorithmsFirstItem.getName()); + List responseVectorSearchVectorizers = responseVectorSearch.getVectorizers(); + VectorSearchVectorizer responseVectorSearchVectorizersFirstItem + = responseVectorSearchVectorizers.iterator().next(); + Assertions.assertNotNull(responseVectorSearchVectorizersFirstItem); + Assertions.assertEquals(VectorSearchVectorizerKind.AZURE_OPEN_AI, + responseVectorSearchVectorizersFirstItem.getKind()); + Assertions.assertEquals("openai", responseVectorSearchVectorizersFirstItem.getVectorizerName()); + List responseVectorSearchCompressions = responseVectorSearch.getCompressions(); + VectorSearchCompression responseVectorSearchCompressionsFirstItem + = responseVectorSearchCompressions.iterator().next(); + Assertions.assertNotNull(responseVectorSearchCompressionsFirstItem); + Assertions.assertEquals(VectorSearchCompressionKind.SCALAR_QUANTIZATION, + responseVectorSearchCompressionsFirstItem.getKind()); + Assertions.assertEquals("mySQ8", responseVectorSearchCompressionsFirstItem.getCompressionName()); + RescoringOptions responseVectorSearchCompressionsFirstItemRescoringOptions + = responseVectorSearchCompressionsFirstItem.getRescoringOptions(); + Assertions.assertNotNull(responseVectorSearchCompressionsFirstItemRescoringOptions); + Assertions.assertEquals(true, responseVectorSearchCompressionsFirstItemRescoringOptions.isEnableRescoring()); + Assertions.assertEquals(10.0D, + responseVectorSearchCompressionsFirstItemRescoringOptions.getDefaultOversampling()); + Assertions.assertEquals(VectorSearchCompressionRescoreStorageMethod.PRESERVE_ORIGINALS, + responseVectorSearchCompressionsFirstItemRescoringOptions.getRescoreStorageMethod()); + Assertions.assertEquals(2, responseVectorSearchCompressionsFirstItem.getTruncationDimension()); + // verify property "eTag" + Assertions.assertEquals("0x1234568AE7E58A1", response.getETag()); + } + + // Use "Map.of" if available + @SuppressWarnings("unchecked") + private static Map mapOf(Object... inputs) { + Map map = new HashMap<>(); + for (int i = 0; i < inputs.length; i += 2) { + String key = (String) inputs[i]; + T value = (T) inputs[i + 1]; + map.put(key, value); + } + return map; + } +} diff --git a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/generated/SearchServiceCreateIndexerTests.java b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/generated/SearchServiceCreateIndexerTests.java new file mode 100644 index 000000000000..5262c175f66d --- /dev/null +++ b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/generated/SearchServiceCreateIndexerTests.java @@ -0,0 +1,195 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.search.documents.generated; + +import com.azure.search.documents.models.AzureActiveDirectoryApplicationCredentials; +import com.azure.search.documents.models.BlobIndexerDataToExtract; +import com.azure.search.documents.models.BlobIndexerImageAction; +import com.azure.search.documents.models.BlobIndexerPDFTextRotationAlgorithm; +import com.azure.search.documents.models.BlobIndexerParsingMode; +import com.azure.search.documents.models.FieldMapping; +import com.azure.search.documents.models.FieldMappingFunction; +import com.azure.search.documents.models.IndexerExecutionEnvironment; +import com.azure.search.documents.models.IndexingParameters; +import com.azure.search.documents.models.IndexingParametersConfiguration; +import com.azure.search.documents.models.IndexingSchedule; +import com.azure.search.documents.models.MarkdownHeaderDepth; +import com.azure.search.documents.models.MarkdownParsingSubmode; +import com.azure.search.documents.models.SearchIndexer; +import com.azure.search.documents.models.SearchIndexerCache; +import com.azure.search.documents.models.SearchIndexerDataIdentity; +import com.azure.search.documents.models.SearchIndexerDataNoneIdentity; +import com.azure.search.documents.models.SearchResourceEncryptionKey; +import java.time.Duration; +import java.time.OffsetDateTime; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + +@Disabled +public final class SearchServiceCreateIndexerTests extends SearchClientTestBase { + @Test + @Disabled + public void testSearchServiceCreateIndexerTests() { + // method invocation + SearchIndexer response + = indexersClient + .create( + new SearchIndexer("myindexer", "mydocdbdatasource", "preview-test") + .setDescription("Description of the indexer") + .setSkillsetName("myskillset") + .setSchedule(new IndexingSchedule(Duration.parse("P1D")) + .setStartTime(OffsetDateTime.parse("2025-01-07T19:30:00Z"))) + .setParameters( + new IndexingParameters().setBatchSize(10) + .setMaxFailedItems(10) + .setMaxFailedItemsPerBatch(5) + .setConfiguration(new IndexingParametersConfiguration() + .setParsingMode(BlobIndexerParsingMode.MARKDOWN) + .setExcludedFileNameExtensions(".png,.mp4") + .setIndexedFileNameExtensions(".docx,.pptx") + .setFailOnUnsupportedContentType(true) + .setFailOnUnprocessableDocument(false) + .setIndexStorageMetadataOnlyForOversizedDocuments(true) + .setDelimitedTextHeaders("Header1,Header2") + .setDelimitedTextDelimiter("|") + .setFirstLineContainsHeaders(true) + .setMarkdownParsingSubmode(MarkdownParsingSubmode.ONE_TO_MANY) + .setMarkdownHeaderDepth(MarkdownHeaderDepth.H6) + .setDocumentRoot("/root") + .setDataToExtract(BlobIndexerDataToExtract.STORAGE_METADATA) + .setImageAction(BlobIndexerImageAction.NONE) + .setAllowSkillsetToReadFileData(false) + .setPdfTextRotationAlgorithm(BlobIndexerPDFTextRotationAlgorithm.NONE) + .setExecutionEnvironment(IndexerExecutionEnvironment.STANDARD) + .setAdditionalProperties(mapOf()))) + .setFieldMappings(Arrays.asList(new FieldMapping("/document").setTargetFieldName("name") + .setMappingFunction(new FieldMappingFunction("base64Encode")))) + .setOutputFieldMappings(Arrays + .asList(new FieldMapping("/document").setTargetFieldName("name") + .setMappingFunction(new FieldMappingFunction("base64Encode")))) + .setIsDisabled(false) + .setEncryptionKey( + new SearchResourceEncryptionKey("fakeTokenPlaceholder", "fakeTokenPlaceholder") + .setKeyVersion("fakeTokenPlaceholder") + .setAccessCredentials(new AzureActiveDirectoryApplicationCredentials( + "00000000-0000-0000-0000-000000000000") + .setApplicationSecret("fakeTokenPlaceholder"))) + .setCache(new SearchIndexerCache().setStorageConnectionString( + "DefaultEndpointsProtocol=https;AccountName=myAccountName;AccountKey=myAccountKey;EndpointSuffix=core.windows.net ") + .setEnableReprocessing(true) + .setIdentity(new SearchIndexerDataNoneIdentity()))); + + // response assertion + Assertions.assertNotNull(response); + // verify property "name" + Assertions.assertEquals("myindexer", response.getName()); + // verify property "description" + Assertions.assertEquals("Description of the indexer", response.getDescription()); + // verify property "dataSourceName" + Assertions.assertEquals("mydocdbdatasource", response.getDataSourceName()); + // verify property "skillsetName" + Assertions.assertEquals("myskillset", response.getSkillsetName()); + // verify property "targetIndexName" + Assertions.assertEquals("preview-test", response.getTargetIndexName()); + // verify property "schedule" + IndexingSchedule responseSchedule = response.getSchedule(); + Assertions.assertNotNull(responseSchedule); + Assertions.assertNotNull(responseSchedule.getInterval()); + Assertions.assertNotNull(responseSchedule.getStartTime()); + // verify property "parameters" + IndexingParameters responseParameters = response.getParameters(); + Assertions.assertNotNull(responseParameters); + Assertions.assertEquals(10, responseParameters.getBatchSize()); + Assertions.assertEquals(10, responseParameters.getMaxFailedItems()); + Assertions.assertEquals(5, responseParameters.getMaxFailedItemsPerBatch()); + IndexingParametersConfiguration responseParametersConfiguration = responseParameters.getConfiguration(); + Assertions.assertNotNull(responseParametersConfiguration); + Assertions.assertEquals(BlobIndexerParsingMode.MARKDOWN, responseParametersConfiguration.getParsingMode()); + Assertions.assertEquals(".png,.mp4", responseParametersConfiguration.getExcludedFileNameExtensions()); + Assertions.assertEquals(".docx,.pptx", responseParametersConfiguration.getIndexedFileNameExtensions()); + Assertions.assertEquals(true, responseParametersConfiguration.isFailOnUnsupportedContentType()); + Assertions.assertEquals(false, responseParametersConfiguration.isFailOnUnprocessableDocument()); + Assertions.assertEquals(true, + responseParametersConfiguration.isIndexStorageMetadataOnlyForOversizedDocuments()); + Assertions.assertEquals("Header1,Header2", responseParametersConfiguration.getDelimitedTextHeaders()); + Assertions.assertEquals("|", responseParametersConfiguration.getDelimitedTextDelimiter()); + Assertions.assertEquals(true, responseParametersConfiguration.isFirstLineContainsHeaders()); + Assertions.assertEquals(MarkdownParsingSubmode.ONE_TO_MANY, + responseParametersConfiguration.getMarkdownParsingSubmode()); + Assertions.assertEquals(MarkdownHeaderDepth.H6, responseParametersConfiguration.getMarkdownHeaderDepth()); + Assertions.assertEquals("/root", responseParametersConfiguration.getDocumentRoot()); + Assertions.assertEquals(BlobIndexerDataToExtract.STORAGE_METADATA, + responseParametersConfiguration.getDataToExtract()); + Assertions.assertEquals(BlobIndexerImageAction.NONE, responseParametersConfiguration.getImageAction()); + Assertions.assertEquals(false, responseParametersConfiguration.isAllowSkillsetToReadFileData()); + Assertions.assertEquals(BlobIndexerPDFTextRotationAlgorithm.NONE, + responseParametersConfiguration.getPdfTextRotationAlgorithm()); + Assertions.assertEquals(IndexerExecutionEnvironment.STANDARD, + responseParametersConfiguration.getExecutionEnvironment()); + // verify property "fieldMappings" + List responseFieldMappings = response.getFieldMappings(); + FieldMapping responseFieldMappingsFirstItem = responseFieldMappings.iterator().next(); + Assertions.assertNotNull(responseFieldMappingsFirstItem); + Assertions.assertEquals("/document", responseFieldMappingsFirstItem.getSourceFieldName()); + Assertions.assertEquals("name", responseFieldMappingsFirstItem.getTargetFieldName()); + FieldMappingFunction responseFieldMappingsFirstItemMappingFunction + = responseFieldMappingsFirstItem.getMappingFunction(); + Assertions.assertNotNull(responseFieldMappingsFirstItemMappingFunction); + Assertions.assertEquals("base64Encode", responseFieldMappingsFirstItemMappingFunction.getName()); + // verify property "outputFieldMappings" + List responseOutputFieldMappings = response.getOutputFieldMappings(); + FieldMapping responseOutputFieldMappingsFirstItem = responseOutputFieldMappings.iterator().next(); + Assertions.assertNotNull(responseOutputFieldMappingsFirstItem); + Assertions.assertEquals("/document", responseOutputFieldMappingsFirstItem.getSourceFieldName()); + Assertions.assertEquals("name", responseOutputFieldMappingsFirstItem.getTargetFieldName()); + FieldMappingFunction responseOutputFieldMappingsFirstItemMappingFunction + = responseOutputFieldMappingsFirstItem.getMappingFunction(); + Assertions.assertNotNull(responseOutputFieldMappingsFirstItemMappingFunction); + Assertions.assertEquals("base64Encode", responseOutputFieldMappingsFirstItemMappingFunction.getName()); + // verify property "isDisabled" + Assertions.assertEquals(false, response.isDisabled()); + // verify property "encryptionKey" + SearchResourceEncryptionKey responseEncryptionKey = response.getEncryptionKey(); + Assertions.assertNotNull(responseEncryptionKey); + Assertions.assertEquals("myUserManagedEncryptionKey-createdinAzureKeyVault", + responseEncryptionKey.getKeyName()); + Assertions.assertEquals("myKeyVersion-32charAlphaNumericString", responseEncryptionKey.getKeyVersion()); + Assertions.assertEquals("https://myKeyVault.vault.azure.net", responseEncryptionKey.getVaultUri()); + AzureActiveDirectoryApplicationCredentials responseEncryptionKeyAccessCredentials + = responseEncryptionKey.getAccessCredentials(); + Assertions.assertNotNull(responseEncryptionKeyAccessCredentials); + Assertions.assertEquals("00000000-0000-0000-0000-000000000000", + responseEncryptionKeyAccessCredentials.getApplicationId()); + Assertions.assertEquals("", responseEncryptionKeyAccessCredentials.getApplicationSecret()); + // verify property "cache" + SearchIndexerCache responseCache = response.getCache(); + Assertions.assertNotNull(responseCache); + Assertions.assertEquals( + "DefaultEndpointsProtocol=https;AccountName=myAccountName;AccountKey=myAccountKey;EndpointSuffix=core.windows.net ", + responseCache.getStorageConnectionString()); + Assertions.assertEquals(true, responseCache.isEnableReprocessing()); + SearchIndexerDataIdentity responseCacheIdentity = responseCache.getIdentity(); + Assertions.assertNotNull(responseCacheIdentity); + Assertions.assertEquals("#Microsoft.Azure.Search.DataNoneIdentity", responseCacheIdentity.getOdataType()); + Assertions.assertEquals("00000000-0000-0000-0000-000000000000", responseCache.getId()); + } + + // Use "Map.of" if available + @SuppressWarnings("unchecked") + private static Map mapOf(Object... inputs) { + Map map = new HashMap<>(); + for (int i = 0; i < inputs.length; i += 2) { + String key = (String) inputs[i]; + T value = (T) inputs[i + 1]; + map.put(key, value); + } + return map; + } +} diff --git a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/generated/SearchServiceCreateOrUpdateAliasTests.java b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/generated/SearchServiceCreateOrUpdateAliasTests.java new file mode 100644 index 000000000000..4679dc54cdfa --- /dev/null +++ b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/generated/SearchServiceCreateOrUpdateAliasTests.java @@ -0,0 +1,32 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.search.documents.generated; + +import com.azure.core.http.MatchConditions; +import com.azure.search.documents.models.SearchAlias; +import java.util.Arrays; +import java.util.List; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + +@Disabled +public final class SearchServiceCreateOrUpdateAliasTests extends SearchClientTestBase { + @Test + @Disabled + public void testSearchServiceCreateOrUpdateAliasTests() { + // method invocation + SearchAlias response = aliasesClient.createOrUpdate("myalias", + new SearchAlias("myalias", Arrays.asList("preview-test")), new MatchConditions()); + + // response assertion + Assertions.assertNotNull(response); + // verify property "name" + Assertions.assertEquals("myalias", response.getName()); + // verify property "indexes" + List responseIndexes = response.getIndexes(); + Assertions.assertEquals("preview-test", responseIndexes.iterator().next()); + } +} diff --git a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/generated/SearchServiceCreateOrUpdateDataSourceTests.java b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/generated/SearchServiceCreateOrUpdateDataSourceTests.java new file mode 100644 index 000000000000..2264a4a7ec17 --- /dev/null +++ b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/generated/SearchServiceCreateOrUpdateDataSourceTests.java @@ -0,0 +1,98 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.search.documents.generated; + +import com.azure.core.http.MatchConditions; +import com.azure.search.documents.models.AzureActiveDirectoryApplicationCredentials; +import com.azure.search.documents.models.DataChangeDetectionPolicy; +import com.azure.search.documents.models.DataDeletionDetectionPolicy; +import com.azure.search.documents.models.DataSourceCredentials; +import com.azure.search.documents.models.HighWaterMarkChangeDetectionPolicy; +import com.azure.search.documents.models.SearchIndexerDataContainer; +import com.azure.search.documents.models.SearchIndexerDataIdentity; +import com.azure.search.documents.models.SearchIndexerDataNoneIdentity; +import com.azure.search.documents.models.SearchIndexerDataSource; +import com.azure.search.documents.models.SearchIndexerDataSourceType; +import com.azure.search.documents.models.SearchResourceEncryptionKey; +import com.azure.search.documents.models.SoftDeleteColumnDeletionDetectionPolicy; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + +@Disabled +public final class SearchServiceCreateOrUpdateDataSourceTests extends SearchClientTestBase { + @Test + @Disabled + public void testSearchServiceCreateOrUpdateDataSourceTests() { + // method invocation + SearchIndexerDataSource response = dataSourcesClient.createOrUpdate("tempdatasource", + new SearchIndexerDataSource("tempdatasource", SearchIndexerDataSourceType.AZURE_BLOB, + new DataSourceCredentials().setConnectionString( + "DefaultEndpointsProtocol=https;AccountName=myAccountName;AccountKey=myAccountKey;EndpointSuffix=core.windows.net "), + new SearchIndexerDataContainer("doc-extraction-skillset").setQuery("E2E_Dsat")) + .setDescription("My Azure Blob data source.") + .setIdentity(new SearchIndexerDataNoneIdentity()) + .setDataChangeDetectionPolicy( + new HighWaterMarkChangeDetectionPolicy("metadata_storage_last_modified")) + .setDataDeletionDetectionPolicy( + new SoftDeleteColumnDeletionDetectionPolicy().setSoftDeleteColumnName("isDeleted") + .setSoftDeleteMarkerValue("true")) + .setEncryptionKey(new SearchResourceEncryptionKey("fakeTokenPlaceholder", "fakeTokenPlaceholder") + .setKeyVersion("fakeTokenPlaceholder") + .setAccessCredentials( + new AzureActiveDirectoryApplicationCredentials("00000000-0000-0000-0000-000000000000") + .setApplicationSecret("fakeTokenPlaceholder"))), + null, new MatchConditions()); + + // response assertion + Assertions.assertNotNull(response); + // verify property "name" + Assertions.assertEquals("tempdatasource", response.getName()); + // verify property "description" + Assertions.assertEquals("My Azure Blob data source.", response.getDescription()); + // verify property "type" + Assertions.assertEquals(SearchIndexerDataSourceType.AZURE_BLOB, response.getType()); + // verify property "credentials" + DataSourceCredentials responseCredentials = response.getCredentials(); + Assertions.assertNotNull(responseCredentials); + Assertions.assertEquals( + "DefaultEndpointsProtocol=https;AccountName=myAccountName;AccountKey=myAccountKey;EndpointSuffix=core.windows.net ", + responseCredentials.getConnectionString()); + // verify property "container" + SearchIndexerDataContainer responseContainer = response.getContainer(); + Assertions.assertNotNull(responseContainer); + Assertions.assertEquals("doc-extraction-skillset", responseContainer.getName()); + Assertions.assertEquals("E2E_Dsat", responseContainer.getQuery()); + // verify property "identity" + SearchIndexerDataIdentity responseIdentity = response.getIdentity(); + Assertions.assertNotNull(responseIdentity); + Assertions.assertEquals("#Microsoft.Azure.Search.DataNoneIdentity", responseIdentity.getOdataType()); + // verify property "dataChangeDetectionPolicy" + DataChangeDetectionPolicy responseDataChangeDetectionPolicy = response.getDataChangeDetectionPolicy(); + Assertions.assertNotNull(responseDataChangeDetectionPolicy); + Assertions.assertEquals("#Microsoft.Azure.Search.HighWaterMarkChangeDetectionPolicy", + responseDataChangeDetectionPolicy.getOdataType()); + // verify property "dataDeletionDetectionPolicy" + DataDeletionDetectionPolicy responseDataDeletionDetectionPolicy = response.getDataDeletionDetectionPolicy(); + Assertions.assertNotNull(responseDataDeletionDetectionPolicy); + Assertions.assertEquals("#Microsoft.Azure.Search.SoftDeleteColumnDeletionDetectionPolicy", + responseDataDeletionDetectionPolicy.getOdataType()); + // verify property "eTag" + Assertions.assertEquals("0x1234568AE7E58A1", response.getETag()); + // verify property "encryptionKey" + SearchResourceEncryptionKey responseEncryptionKey = response.getEncryptionKey(); + Assertions.assertNotNull(responseEncryptionKey); + Assertions.assertEquals("myUserManagedEncryptionKey-createdinAzureKeyVault", + responseEncryptionKey.getKeyName()); + Assertions.assertEquals("myKeyVersion-32charAlphaNumericString", responseEncryptionKey.getKeyVersion()); + Assertions.assertEquals("https://myKeyVault.vault.azure.net", responseEncryptionKey.getVaultUri()); + AzureActiveDirectoryApplicationCredentials responseEncryptionKeyAccessCredentials + = responseEncryptionKey.getAccessCredentials(); + Assertions.assertNotNull(responseEncryptionKeyAccessCredentials); + Assertions.assertEquals("00000000-0000-0000-0000-000000000000", + responseEncryptionKeyAccessCredentials.getApplicationId()); + Assertions.assertEquals("", responseEncryptionKeyAccessCredentials.getApplicationSecret()); + } +} diff --git a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/generated/SearchServiceCreateOrUpdateIndexTests.java b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/generated/SearchServiceCreateOrUpdateIndexTests.java new file mode 100644 index 000000000000..93ff631e346c --- /dev/null +++ b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/generated/SearchServiceCreateOrUpdateIndexTests.java @@ -0,0 +1,411 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.search.documents.generated; + +import com.azure.core.http.MatchConditions; +import com.azure.search.documents.models.AIFoundryModelCatalogName; +import com.azure.search.documents.models.AsciiFoldingTokenFilter; +import com.azure.search.documents.models.AzureMachineLearningParameters; +import com.azure.search.documents.models.AzureMachineLearningVectorizer; +import com.azure.search.documents.models.AzureOpenAIModelName; +import com.azure.search.documents.models.AzureOpenAIVectorizer; +import com.azure.search.documents.models.AzureOpenAIVectorizerParameters; +import com.azure.search.documents.models.BM25SimilarityAlgorithm; +import com.azure.search.documents.models.BinaryQuantizationCompression; +import com.azure.search.documents.models.CharFilter; +import com.azure.search.documents.models.CharFilterName; +import com.azure.search.documents.models.CorsOptions; +import com.azure.search.documents.models.CustomAnalyzer; +import com.azure.search.documents.models.CustomNormalizer; +import com.azure.search.documents.models.HnswAlgorithmConfiguration; +import com.azure.search.documents.models.HnswParameters; +import com.azure.search.documents.models.LexicalAnalyzer; +import com.azure.search.documents.models.LexicalAnalyzerName; +import com.azure.search.documents.models.LexicalNormalizer; +import com.azure.search.documents.models.LexicalTokenizer; +import com.azure.search.documents.models.LexicalTokenizerName; +import com.azure.search.documents.models.LuceneStandardTokenizerV2; +import com.azure.search.documents.models.MappingCharFilter; +import com.azure.search.documents.models.RescoringOptions; +import com.azure.search.documents.models.ScalarQuantizationCompression; +import com.azure.search.documents.models.ScalarQuantizationParameters; +import com.azure.search.documents.models.ScoringFunction; +import com.azure.search.documents.models.ScoringFunctionAggregation; +import com.azure.search.documents.models.ScoringFunctionInterpolation; +import com.azure.search.documents.models.ScoringProfile; +import com.azure.search.documents.models.SearchField; +import com.azure.search.documents.models.SearchFieldDataType; +import com.azure.search.documents.models.SearchIndex; +import com.azure.search.documents.models.SearchIndexerDataNoneIdentity; +import com.azure.search.documents.models.SearchSuggester; +import com.azure.search.documents.models.SemanticConfiguration; +import com.azure.search.documents.models.SemanticField; +import com.azure.search.documents.models.SemanticPrioritizedFields; +import com.azure.search.documents.models.SemanticSearch; +import com.azure.search.documents.models.SimilarityAlgorithm; +import com.azure.search.documents.models.TagScoringFunction; +import com.azure.search.documents.models.TagScoringParameters; +import com.azure.search.documents.models.TextWeights; +import com.azure.search.documents.models.TokenFilter; +import com.azure.search.documents.models.TokenFilterName; +import com.azure.search.documents.models.VectorSearch; +import com.azure.search.documents.models.VectorSearchAlgorithmConfiguration; +import com.azure.search.documents.models.VectorSearchAlgorithmKind; +import com.azure.search.documents.models.VectorSearchAlgorithmMetric; +import com.azure.search.documents.models.VectorSearchCompression; +import com.azure.search.documents.models.VectorSearchCompressionKind; +import com.azure.search.documents.models.VectorSearchCompressionRescoreStorageMethod; +import com.azure.search.documents.models.VectorSearchCompressionTarget; +import com.azure.search.documents.models.VectorSearchProfile; +import com.azure.search.documents.models.VectorSearchVectorizer; +import com.azure.search.documents.models.VectorSearchVectorizerKind; +import com.azure.search.documents.models.WebApiVectorizer; +import com.azure.search.documents.models.WebApiVectorizerParameters; +import java.time.Duration; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + +@Disabled +public final class SearchServiceCreateOrUpdateIndexTests extends SearchClientTestBase { + @Test + @Disabled + public void testSearchServiceCreateOrUpdateIndexTests() { + // method invocation + SearchIndex response = indexesClient.createOrUpdate("temp-preview-test", + new SearchIndex("temp-preview-test", + Arrays.asList(new SearchField("id", SearchFieldDataType.STRING).setKey(true).setSortable(true), + new SearchField("vector1", SearchFieldDataType.fromString("Collection(Edm.Single)")) + .setRetrievable(true) + .setSearchable(true) + .setVectorSearchDimensions(20) + .setVectorSearchProfileName("config1"), + new SearchField("vector1b", SearchFieldDataType.fromString("Collection(Edm.Single)")) + .setRetrievable(true) + .setSearchable(true) + .setVectorSearchDimensions(10) + .setVectorSearchProfileName("config2"), + new SearchField("vector2", SearchFieldDataType.fromString("Collection(Edm.Single)")) + .setRetrievable(true) + .setSearchable(true) + .setVectorSearchDimensions(5) + .setVectorSearchProfileName("config3"), + new SearchField("vector3", SearchFieldDataType.fromString("Collection(Edm.Single)")) + .setRetrievable(true) + .setSearchable(true) + .setVectorSearchDimensions(5) + .setVectorSearchProfileName("config3"), + new SearchField("vector22", SearchFieldDataType.fromString("Collection(Edm.Single)")) + .setRetrievable(true) + .setSearchable(true) + .setVectorSearchDimensions(10) + .setVectorSearchProfileName("config2"), + new SearchField("vector4", SearchFieldDataType.fromString("Collection(Edm.Single)")) + .setRetrievable(true) + .setSearchable(true) + .setVectorSearchDimensions(32) + .setVectorSearchProfileName("config4"), + new SearchField("name", SearchFieldDataType.STRING).setRetrievable(true) + .setSearchable(true) + .setFilterable(true) + .setSortable(true) + .setFacetable(true) + .setAnalyzer(LexicalAnalyzerName.EN_LUCENE), + new SearchField("description", SearchFieldDataType.STRING).setRetrievable(true) + .setSearchable(true) + .setFilterable(true) + .setSortable(true) + .setFacetable(true) + .setAnalyzer(LexicalAnalyzerName.STANDARD_LUCENE), + new SearchField("category", SearchFieldDataType.STRING).setRetrievable(true) + .setSearchable(true) + .setFilterable(true) + .setSortable(true) + .setFacetable(true) + .setAnalyzer(LexicalAnalyzerName.EN_LUCENE), + new SearchField("ownerId", SearchFieldDataType.STRING).setRetrievable(true) + .setSearchable(true) + .setFilterable(true) + .setSortable(true) + .setFacetable(true) + .setAnalyzer(LexicalAnalyzerName.EN_LUCENE), + new SearchField("price", SearchFieldDataType.DOUBLE).setRetrievable(true) + .setFilterable(true) + .setSortable(true) + .setFacetable(true))) + .setScoringProfiles(Arrays.asList(new ScoringProfile("stringFieldBoost") + .setTextWeights(new TextWeights( + mapOf("name", 3.0, "description", 1.0, "category", 2.0, "ownerId", 1.0))) + .setFunctions(Arrays.asList( + new TagScoringFunction("category", 2.0, new TagScoringParameters("categoryTag")))))) + .setDefaultScoringProfile("stringFieldBoost") + .setCorsOptions( + new CorsOptions(Arrays.asList("https://www.example.com/foo")).setMaxAgeInSeconds(10L)) + .setSuggesters( + Arrays.asList(new SearchSuggester("sg", Arrays.asList("category", "ownerId")))) + .setAnalyzers( + Arrays.asList(new CustomAnalyzer("tagsAnalyzer", LexicalTokenizerName.STANDARD) + .setTokenFilters(Arrays.asList(TokenFilterName.COMMON_GRAM)) + .setCharFilters(Arrays.asList(CharFilterName.HTML_STRIP)))) + .setTokenizers( + Arrays.asList(new LuceneStandardTokenizerV2("my_tokenizer").setMaxTokenLength(100))) + .setTokenFilters( + Arrays.asList(new AsciiFoldingTokenFilter("my_tokenFilter").setPreserveOriginal(false))) + .setCharFilters( + Arrays.asList(new MappingCharFilter("my_mapping", Arrays.asList(".=>,", "_=>-")))) + .setNormalizers(Arrays.asList(new CustomNormalizer("my_normalizer") + .setTokenFilters(Arrays.asList(TokenFilterName.fromString("my_tokenFilter"))) + .setCharFilters(Arrays.asList(CharFilterName.fromString("my_mapping"))))) + .setSimilarity(new BM25SimilarityAlgorithm().setK1(10.0D).setB(0.1D)) + .setSemanticSearch(new SemanticSearch().setDefaultConfigurationName("testconfig") + .setConfigurations(Arrays.asList(new SemanticConfiguration("testconfig", + new SemanticPrioritizedFields().setTitleField(new SemanticField("category")) + .setContentFields(Arrays.asList(new SemanticField("description"))) + .setKeywordsFields(Arrays.asList(new SemanticField("ownerId")))) + .setFlightingOptIn(true)))) + .setVectorSearch(new VectorSearch() + .setProfiles(Arrays.asList( + new VectorSearchProfile("config1", "cosine").setVectorizerName("openai") + .setCompressionName("mySQ8"), + new VectorSearchProfile("config2", "euclidean").setVectorizerName("custom-web-api") + .setCompressionName("mySQ8"), + new VectorSearchProfile("config3", "dotProduct").setVectorizerName("custom-web-api") + .setCompressionName("myBQC"), + new VectorSearchProfile("config4", "dotProduct").setVectorizerName("custom-web-api") + .setCompressionName("myBQWithoutOriginals"))) + .setAlgorithms(Arrays.asList( + new HnswAlgorithmConfiguration("cosine").setParameters( + new HnswParameters().setMetric(VectorSearchAlgorithmMetric.COSINE)), + new HnswAlgorithmConfiguration("euclidean").setParameters( + new HnswParameters().setMetric(VectorSearchAlgorithmMetric.EUCLIDEAN)), + new HnswAlgorithmConfiguration("dotProduct").setParameters( + new HnswParameters().setMetric(VectorSearchAlgorithmMetric.DOT_PRODUCT)))) + .setVectorizers(Arrays.asList( + new AzureOpenAIVectorizer("openai") + .setParameters(new AzureOpenAIVectorizerParameters() + .setResourceUrl("https://test-sample.openai.azure.com/") + .setDeploymentName("model") + .setApiKey("fakeTokenPlaceholder") + .setModelName(AzureOpenAIModelName.TEXT_EMBEDDING3LARGE)), + new WebApiVectorizer("custom-web-api") + .setWebApiParameters(new WebApiVectorizerParameters() + .setUrl("https://my-custom-endpoint.org/") + .setHttpHeaders(mapOf("header1", "value1", "header2", "value2")) + .setHttpMethod("POST") + .setTimeout(Duration.parse("PT1M")) + .setAuthResourceId("api://f89d1c93-58a7-4b07-9a5b-5f89048b927b") + .setAuthIdentity(new SearchIndexerDataNoneIdentity())), + new AzureMachineLearningVectorizer("aml").setAMLParameters( + new AzureMachineLearningParameters("https://my-custom-endpoint.org/") + .setResourceId("aml resource id") + .setTimeout(Duration.parse("PT1M")) + .setRegion("aml region") + .setModelName( + AIFoundryModelCatalogName.OPEN_AICLIPIMAGE_TEXT_EMBEDDINGS_VIT_BASE_PATCH32)))) + .setCompressions(Arrays.asList( + new ScalarQuantizationCompression("mySQ8") + .setRescoringOptions(new RescoringOptions().setEnableRescoring(true) + .setDefaultOversampling(10.0D) + .setRescoreStorageMethod( + VectorSearchCompressionRescoreStorageMethod.PRESERVE_ORIGINALS)) + .setTruncationDimension(2) + .setParameters(new ScalarQuantizationParameters() + .setQuantizedDataType(VectorSearchCompressionTarget.INT8)), + new BinaryQuantizationCompression("myBQC") + .setRescoringOptions(new RescoringOptions().setEnableRescoring(true) + .setDefaultOversampling(10.0D) + .setRescoreStorageMethod( + VectorSearchCompressionRescoreStorageMethod.PRESERVE_ORIGINALS)) + .setTruncationDimension(2), + new BinaryQuantizationCompression("myBQWithoutOriginals") + .setRescoringOptions(new RescoringOptions().setEnableRescoring(true) + .setDefaultOversampling(10.0D) + .setRescoreStorageMethod( + VectorSearchCompressionRescoreStorageMethod.DISCARD_ORIGINALS)) + .setTruncationDimension(2)))), + null, new MatchConditions()); + + // response assertion + Assertions.assertNotNull(response); + // verify property "name" + Assertions.assertEquals("temp-preview-test", response.getName()); + // verify property "fields" + List responseFields = response.getFields(); + SearchField responseFieldsFirstItem = responseFields.iterator().next(); + Assertions.assertNotNull(responseFieldsFirstItem); + Assertions.assertEquals("id", responseFieldsFirstItem.getName()); + Assertions.assertEquals(SearchFieldDataType.STRING, responseFieldsFirstItem.getType()); + Assertions.assertEquals(true, responseFieldsFirstItem.isKey()); + Assertions.assertEquals(true, responseFieldsFirstItem.isRetrievable()); + Assertions.assertEquals(true, responseFieldsFirstItem.isStored()); + Assertions.assertEquals(true, responseFieldsFirstItem.isSearchable()); + Assertions.assertEquals(true, responseFieldsFirstItem.isFilterable()); + Assertions.assertEquals(true, responseFieldsFirstItem.isSortable()); + Assertions.assertEquals(true, responseFieldsFirstItem.isFacetable()); + List responseFieldsFirstItemSynonymMaps = responseFieldsFirstItem.getSynonymMaps(); + Assertions.assertEquals(0, responseFieldsFirstItemSynonymMaps.size()); + // verify property "scoringProfiles" + List responseScoringProfiles = response.getScoringProfiles(); + ScoringProfile responseScoringProfilesFirstItem = responseScoringProfiles.iterator().next(); + Assertions.assertNotNull(responseScoringProfilesFirstItem); + Assertions.assertEquals("stringFieldBoost", responseScoringProfilesFirstItem.getName()); + TextWeights responseScoringProfilesFirstItemTextWeights = responseScoringProfilesFirstItem.getTextWeights(); + Assertions.assertNotNull(responseScoringProfilesFirstItemTextWeights); + Assertions.assertNotNull(responseScoringProfilesFirstItemTextWeights.getWeights()); + List responseScoringProfilesFirstItemFunctions + = responseScoringProfilesFirstItem.getFunctions(); + ScoringFunction responseScoringProfilesFirstItemFunctionsFirstItem + = responseScoringProfilesFirstItemFunctions.iterator().next(); + Assertions.assertNotNull(responseScoringProfilesFirstItemFunctionsFirstItem); + Assertions.assertEquals("tag", responseScoringProfilesFirstItemFunctionsFirstItem.getType()); + Assertions.assertEquals("category", responseScoringProfilesFirstItemFunctionsFirstItem.getFieldName()); + Assertions.assertEquals(2.0, responseScoringProfilesFirstItemFunctionsFirstItem.getBoost()); + Assertions.assertEquals(ScoringFunctionInterpolation.LINEAR, + responseScoringProfilesFirstItemFunctionsFirstItem.getInterpolation()); + Assertions.assertEquals(ScoringFunctionAggregation.SUM, + responseScoringProfilesFirstItem.getFunctionAggregation()); + // verify property "defaultScoringProfile" + Assertions.assertEquals("stringFieldBoost", response.getDefaultScoringProfile()); + // verify property "corsOptions" + CorsOptions responseCorsOptions = response.getCorsOptions(); + Assertions.assertNotNull(responseCorsOptions); + List responseCorsOptionsAllowedOrigins = responseCorsOptions.getAllowedOrigins(); + Assertions.assertEquals("https://www.example.com/foo", responseCorsOptionsAllowedOrigins.iterator().next()); + Assertions.assertEquals(10L, responseCorsOptions.getMaxAgeInSeconds()); + // verify property "suggesters" + List responseSuggesters = response.getSuggesters(); + SearchSuggester responseSuggestersFirstItem = responseSuggesters.iterator().next(); + Assertions.assertNotNull(responseSuggestersFirstItem); + Assertions.assertEquals("sg", responseSuggestersFirstItem.getName()); + Assertions.assertEquals("analyzingInfixMatching", responseSuggestersFirstItem.getSearchMode()); + List responseSuggestersFirstItemSourceFields = responseSuggestersFirstItem.getSourceFields(); + Assertions.assertEquals("category", responseSuggestersFirstItemSourceFields.iterator().next()); + // verify property "analyzers" + List responseAnalyzers = response.getAnalyzers(); + LexicalAnalyzer responseAnalyzersFirstItem = responseAnalyzers.iterator().next(); + Assertions.assertNotNull(responseAnalyzersFirstItem); + Assertions.assertEquals("#Microsoft.Azure.Search.CustomAnalyzer", responseAnalyzersFirstItem.getOdataType()); + Assertions.assertEquals("tagsAnalyzer", responseAnalyzersFirstItem.getName()); + // verify property "tokenizers" + List responseTokenizers = response.getTokenizers(); + LexicalTokenizer responseTokenizersFirstItem = responseTokenizers.iterator().next(); + Assertions.assertNotNull(responseTokenizersFirstItem); + Assertions.assertEquals("#Microsoft.Azure.Search.StandardTokenizerV2", + responseTokenizersFirstItem.getOdataType()); + Assertions.assertEquals("my_tokenizer", responseTokenizersFirstItem.getName()); + // verify property "tokenFilters" + List responseTokenFilters = response.getTokenFilters(); + TokenFilter responseTokenFiltersFirstItem = responseTokenFilters.iterator().next(); + Assertions.assertNotNull(responseTokenFiltersFirstItem); + Assertions.assertEquals("#Microsoft.Azure.Search.AsciiFoldingTokenFilter", + responseTokenFiltersFirstItem.getOdataType()); + Assertions.assertEquals("my_tokenFilter", responseTokenFiltersFirstItem.getName()); + // verify property "charFilters" + List responseCharFilters = response.getCharFilters(); + CharFilter responseCharFiltersFirstItem = responseCharFilters.iterator().next(); + Assertions.assertNotNull(responseCharFiltersFirstItem); + Assertions.assertEquals("#Microsoft.Azure.Search.MappingCharFilter", + responseCharFiltersFirstItem.getOdataType()); + Assertions.assertEquals("my_mapping", responseCharFiltersFirstItem.getName()); + // verify property "normalizers" + List responseNormalizers = response.getNormalizers(); + LexicalNormalizer responseNormalizersFirstItem = responseNormalizers.iterator().next(); + Assertions.assertNotNull(responseNormalizersFirstItem); + Assertions.assertEquals("#Microsoft.Azure.Search.CustomNormalizer", + responseNormalizersFirstItem.getOdataType()); + Assertions.assertEquals("my_normalizer", responseNormalizersFirstItem.getName()); + // verify property "similarity" + SimilarityAlgorithm responseSimilarity = response.getSimilarity(); + Assertions.assertNotNull(responseSimilarity); + Assertions.assertEquals("#Microsoft.Azure.Search.BM25Similarity", responseSimilarity.getOdataType()); + // verify property "semanticSearch" + SemanticSearch responseSemanticSearch = response.getSemanticSearch(); + Assertions.assertNotNull(responseSemanticSearch); + Assertions.assertEquals("testconfig", responseSemanticSearch.getDefaultConfigurationName()); + List responseSemanticSearchConfigurations = responseSemanticSearch.getConfigurations(); + SemanticConfiguration responseSemanticSearchConfigurationsFirstItem + = responseSemanticSearchConfigurations.iterator().next(); + Assertions.assertNotNull(responseSemanticSearchConfigurationsFirstItem); + Assertions.assertEquals("testconfig", responseSemanticSearchConfigurationsFirstItem.getName()); + SemanticPrioritizedFields responseSemanticSearchConfigurationsFirstItemPrioritizedFields + = responseSemanticSearchConfigurationsFirstItem.getPrioritizedFields(); + Assertions.assertNotNull(responseSemanticSearchConfigurationsFirstItemPrioritizedFields); + SemanticField responseSemanticSearchConfigurationsFirstItemPrioritizedFieldsTitleField + = responseSemanticSearchConfigurationsFirstItemPrioritizedFields.getTitleField(); + Assertions.assertNotNull(responseSemanticSearchConfigurationsFirstItemPrioritizedFieldsTitleField); + Assertions.assertEquals("category", + responseSemanticSearchConfigurationsFirstItemPrioritizedFieldsTitleField.getFieldName()); + List responseSemanticSearchConfigurationsFirstItemPrioritizedFieldsContentFields + = responseSemanticSearchConfigurationsFirstItemPrioritizedFields.getContentFields(); + SemanticField responseSemanticSearchConfigurationsFirstItemPrioritizedFieldsContentFieldsFirstItem + = responseSemanticSearchConfigurationsFirstItemPrioritizedFieldsContentFields.iterator().next(); + Assertions.assertNotNull(responseSemanticSearchConfigurationsFirstItemPrioritizedFieldsContentFieldsFirstItem); + Assertions.assertEquals("description", + responseSemanticSearchConfigurationsFirstItemPrioritizedFieldsContentFieldsFirstItem.getFieldName()); + List responseSemanticSearchConfigurationsFirstItemPrioritizedFieldsKeywordsFields + = responseSemanticSearchConfigurationsFirstItemPrioritizedFields.getKeywordsFields(); + SemanticField responseSemanticSearchConfigurationsFirstItemPrioritizedFieldsKeywordsFieldsFirstItem + = responseSemanticSearchConfigurationsFirstItemPrioritizedFieldsKeywordsFields.iterator().next(); + Assertions.assertNotNull(responseSemanticSearchConfigurationsFirstItemPrioritizedFieldsKeywordsFieldsFirstItem); + Assertions.assertEquals("ownerId", + responseSemanticSearchConfigurationsFirstItemPrioritizedFieldsKeywordsFieldsFirstItem.getFieldName()); + Assertions.assertEquals(false, responseSemanticSearchConfigurationsFirstItem.isFlightingOptIn()); + // verify property "vectorSearch" + VectorSearch responseVectorSearch = response.getVectorSearch(); + Assertions.assertNotNull(responseVectorSearch); + List responseVectorSearchProfiles = responseVectorSearch.getProfiles(); + VectorSearchProfile responseVectorSearchProfilesFirstItem = responseVectorSearchProfiles.iterator().next(); + Assertions.assertNotNull(responseVectorSearchProfilesFirstItem); + Assertions.assertEquals("config1", responseVectorSearchProfilesFirstItem.getName()); + Assertions.assertEquals("cosine", responseVectorSearchProfilesFirstItem.getAlgorithmConfigurationName()); + Assertions.assertEquals("openai", responseVectorSearchProfilesFirstItem.getVectorizerName()); + Assertions.assertEquals("mySQ8", responseVectorSearchProfilesFirstItem.getCompressionName()); + List responseVectorSearchAlgorithms = responseVectorSearch.getAlgorithms(); + VectorSearchAlgorithmConfiguration responseVectorSearchAlgorithmsFirstItem + = responseVectorSearchAlgorithms.iterator().next(); + Assertions.assertNotNull(responseVectorSearchAlgorithmsFirstItem); + Assertions.assertEquals(VectorSearchAlgorithmKind.HNSW, responseVectorSearchAlgorithmsFirstItem.getKind()); + Assertions.assertEquals("cosine", responseVectorSearchAlgorithmsFirstItem.getName()); + List responseVectorSearchVectorizers = responseVectorSearch.getVectorizers(); + VectorSearchVectorizer responseVectorSearchVectorizersFirstItem + = responseVectorSearchVectorizers.iterator().next(); + Assertions.assertNotNull(responseVectorSearchVectorizersFirstItem); + Assertions.assertEquals(VectorSearchVectorizerKind.AZURE_OPEN_AI, + responseVectorSearchVectorizersFirstItem.getKind()); + Assertions.assertEquals("openai", responseVectorSearchVectorizersFirstItem.getVectorizerName()); + List responseVectorSearchCompressions = responseVectorSearch.getCompressions(); + VectorSearchCompression responseVectorSearchCompressionsFirstItem + = responseVectorSearchCompressions.iterator().next(); + Assertions.assertNotNull(responseVectorSearchCompressionsFirstItem); + Assertions.assertEquals(VectorSearchCompressionKind.SCALAR_QUANTIZATION, + responseVectorSearchCompressionsFirstItem.getKind()); + Assertions.assertEquals("mySQ8", responseVectorSearchCompressionsFirstItem.getCompressionName()); + RescoringOptions responseVectorSearchCompressionsFirstItemRescoringOptions + = responseVectorSearchCompressionsFirstItem.getRescoringOptions(); + Assertions.assertNotNull(responseVectorSearchCompressionsFirstItemRescoringOptions); + Assertions.assertEquals(true, responseVectorSearchCompressionsFirstItemRescoringOptions.isEnableRescoring()); + Assertions.assertEquals(10.0D, + responseVectorSearchCompressionsFirstItemRescoringOptions.getDefaultOversampling()); + Assertions.assertEquals(VectorSearchCompressionRescoreStorageMethod.PRESERVE_ORIGINALS, + responseVectorSearchCompressionsFirstItemRescoringOptions.getRescoreStorageMethod()); + Assertions.assertEquals(2, responseVectorSearchCompressionsFirstItem.getTruncationDimension()); + } + + // Use "Map.of" if available + @SuppressWarnings("unchecked") + private static Map mapOf(Object... inputs) { + Map map = new HashMap<>(); + for (int i = 0; i < inputs.length; i += 2) { + String key = (String) inputs[i]; + T value = (T) inputs[i + 1]; + map.put(key, value); + } + return map; + } +} diff --git a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/generated/SearchServiceCreateOrUpdateIndexerTests.java b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/generated/SearchServiceCreateOrUpdateIndexerTests.java new file mode 100644 index 000000000000..f7307e6b08cc --- /dev/null +++ b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/generated/SearchServiceCreateOrUpdateIndexerTests.java @@ -0,0 +1,180 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.search.documents.generated; + +import com.azure.core.http.MatchConditions; +import com.azure.search.documents.models.AzureActiveDirectoryApplicationCredentials; +import com.azure.search.documents.models.BlobIndexerDataToExtract; +import com.azure.search.documents.models.BlobIndexerImageAction; +import com.azure.search.documents.models.BlobIndexerPDFTextRotationAlgorithm; +import com.azure.search.documents.models.BlobIndexerParsingMode; +import com.azure.search.documents.models.FieldMapping; +import com.azure.search.documents.models.FieldMappingFunction; +import com.azure.search.documents.models.IndexerExecutionEnvironment; +import com.azure.search.documents.models.IndexingParameters; +import com.azure.search.documents.models.IndexingParametersConfiguration; +import com.azure.search.documents.models.IndexingSchedule; +import com.azure.search.documents.models.MarkdownHeaderDepth; +import com.azure.search.documents.models.MarkdownParsingSubmode; +import com.azure.search.documents.models.SearchIndexer; +import com.azure.search.documents.models.SearchResourceEncryptionKey; +import java.time.Duration; +import java.time.OffsetDateTime; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + +@Disabled +public final class SearchServiceCreateOrUpdateIndexerTests extends SearchClientTestBase { + @Test + @Disabled + public void testSearchServiceCreateOrUpdateIndexerTests() { + // method invocation + SearchIndexer response + = indexersClient + .createOrUpdate("myindexer", + new SearchIndexer("myindexer", "mydocdbdatasource", "preview-test") + .setDescription("Description of the indexer") + .setSkillsetName("myskillset") + .setSchedule(new IndexingSchedule(Duration.parse("P1D")) + .setStartTime(OffsetDateTime.parse("2025-01-07T19:30:00Z"))) + .setParameters( + new IndexingParameters().setBatchSize(10) + .setMaxFailedItems(10) + .setMaxFailedItemsPerBatch(5) + .setConfiguration(new IndexingParametersConfiguration() + .setParsingMode(BlobIndexerParsingMode.MARKDOWN) + .setExcludedFileNameExtensions(".png,.mp4") + .setIndexedFileNameExtensions(".docx,.pptx") + .setFailOnUnsupportedContentType(true) + .setFailOnUnprocessableDocument(false) + .setIndexStorageMetadataOnlyForOversizedDocuments(true) + .setDelimitedTextHeaders("Header1,Header2") + .setDelimitedTextDelimiter("|") + .setFirstLineContainsHeaders(true) + .setMarkdownParsingSubmode(MarkdownParsingSubmode.ONE_TO_ONE) + .setMarkdownHeaderDepth(MarkdownHeaderDepth.H6) + .setDocumentRoot("/root") + .setDataToExtract(BlobIndexerDataToExtract.STORAGE_METADATA) + .setImageAction(BlobIndexerImageAction.NONE) + .setAllowSkillsetToReadFileData(false) + .setPdfTextRotationAlgorithm(BlobIndexerPDFTextRotationAlgorithm.NONE) + .setExecutionEnvironment(IndexerExecutionEnvironment.STANDARD) + .setAdditionalProperties(mapOf()))) + .setFieldMappings(Arrays.asList(new FieldMapping("/document").setTargetFieldName("name") + .setMappingFunction(new FieldMappingFunction("base64Encode")))) + .setOutputFieldMappings(Arrays.asList(new FieldMapping("/document").setTargetFieldName("name") + .setMappingFunction(new FieldMappingFunction("base64Encode")))) + .setIsDisabled(false) + .setEncryptionKey( + new SearchResourceEncryptionKey("fakeTokenPlaceholder", "fakeTokenPlaceholder") + .setKeyVersion("fakeTokenPlaceholder") + .setAccessCredentials(new AzureActiveDirectoryApplicationCredentials( + "00000000-0000-0000-0000-000000000000") + .setApplicationSecret("fakeTokenPlaceholder"))), + null, null, new MatchConditions()); + + // response assertion + Assertions.assertNotNull(response); + // verify property "name" + Assertions.assertEquals("myindexer", response.getName()); + // verify property "description" + Assertions.assertEquals("Description of the indexer", response.getDescription()); + // verify property "dataSourceName" + Assertions.assertEquals("mydocdbdatasource", response.getDataSourceName()); + // verify property "skillsetName" + Assertions.assertEquals("myskillset", response.getSkillsetName()); + // verify property "targetIndexName" + Assertions.assertEquals("preview-test", response.getTargetIndexName()); + // verify property "schedule" + IndexingSchedule responseSchedule = response.getSchedule(); + Assertions.assertNotNull(responseSchedule); + Assertions.assertNotNull(responseSchedule.getInterval()); + Assertions.assertNotNull(responseSchedule.getStartTime()); + // verify property "parameters" + IndexingParameters responseParameters = response.getParameters(); + Assertions.assertNotNull(responseParameters); + Assertions.assertEquals(10, responseParameters.getBatchSize()); + Assertions.assertEquals(10, responseParameters.getMaxFailedItems()); + Assertions.assertEquals(5, responseParameters.getMaxFailedItemsPerBatch()); + IndexingParametersConfiguration responseParametersConfiguration = responseParameters.getConfiguration(); + Assertions.assertNotNull(responseParametersConfiguration); + Assertions.assertEquals(BlobIndexerParsingMode.MARKDOWN, responseParametersConfiguration.getParsingMode()); + Assertions.assertEquals(".png,.mp4", responseParametersConfiguration.getExcludedFileNameExtensions()); + Assertions.assertEquals(".docx,.pptx", responseParametersConfiguration.getIndexedFileNameExtensions()); + Assertions.assertEquals(true, responseParametersConfiguration.isFailOnUnsupportedContentType()); + Assertions.assertEquals(false, responseParametersConfiguration.isFailOnUnprocessableDocument()); + Assertions.assertEquals(true, + responseParametersConfiguration.isIndexStorageMetadataOnlyForOversizedDocuments()); + Assertions.assertEquals("Header1,Header2", responseParametersConfiguration.getDelimitedTextHeaders()); + Assertions.assertEquals("|", responseParametersConfiguration.getDelimitedTextDelimiter()); + Assertions.assertEquals(true, responseParametersConfiguration.isFirstLineContainsHeaders()); + Assertions.assertEquals(MarkdownParsingSubmode.ONE_TO_ONE, + responseParametersConfiguration.getMarkdownParsingSubmode()); + Assertions.assertEquals(MarkdownHeaderDepth.H6, responseParametersConfiguration.getMarkdownHeaderDepth()); + Assertions.assertEquals("/root", responseParametersConfiguration.getDocumentRoot()); + Assertions.assertEquals(BlobIndexerDataToExtract.STORAGE_METADATA, + responseParametersConfiguration.getDataToExtract()); + Assertions.assertEquals(BlobIndexerImageAction.NONE, responseParametersConfiguration.getImageAction()); + Assertions.assertEquals(false, responseParametersConfiguration.isAllowSkillsetToReadFileData()); + Assertions.assertEquals(BlobIndexerPDFTextRotationAlgorithm.NONE, + responseParametersConfiguration.getPdfTextRotationAlgorithm()); + Assertions.assertEquals(IndexerExecutionEnvironment.STANDARD, + responseParametersConfiguration.getExecutionEnvironment()); + // verify property "fieldMappings" + List responseFieldMappings = response.getFieldMappings(); + FieldMapping responseFieldMappingsFirstItem = responseFieldMappings.iterator().next(); + Assertions.assertNotNull(responseFieldMappingsFirstItem); + Assertions.assertEquals("/document", responseFieldMappingsFirstItem.getSourceFieldName()); + Assertions.assertEquals("name", responseFieldMappingsFirstItem.getTargetFieldName()); + FieldMappingFunction responseFieldMappingsFirstItemMappingFunction + = responseFieldMappingsFirstItem.getMappingFunction(); + Assertions.assertNotNull(responseFieldMappingsFirstItemMappingFunction); + Assertions.assertEquals("base64Encode", responseFieldMappingsFirstItemMappingFunction.getName()); + // verify property "outputFieldMappings" + List responseOutputFieldMappings = response.getOutputFieldMappings(); + FieldMapping responseOutputFieldMappingsFirstItem = responseOutputFieldMappings.iterator().next(); + Assertions.assertNotNull(responseOutputFieldMappingsFirstItem); + Assertions.assertEquals("/document", responseOutputFieldMappingsFirstItem.getSourceFieldName()); + Assertions.assertEquals("name", responseOutputFieldMappingsFirstItem.getTargetFieldName()); + FieldMappingFunction responseOutputFieldMappingsFirstItemMappingFunction + = responseOutputFieldMappingsFirstItem.getMappingFunction(); + Assertions.assertNotNull(responseOutputFieldMappingsFirstItemMappingFunction); + Assertions.assertEquals("base64Encode", responseOutputFieldMappingsFirstItemMappingFunction.getName()); + // verify property "isDisabled" + Assertions.assertEquals(false, response.isDisabled()); + // verify property "eTag" + Assertions.assertEquals("0x1234568AE7E58A1", response.getETag()); + // verify property "encryptionKey" + SearchResourceEncryptionKey responseEncryptionKey = response.getEncryptionKey(); + Assertions.assertNotNull(responseEncryptionKey); + Assertions.assertEquals("myUserManagedEncryptionKey-createdinAzureKeyVault", + responseEncryptionKey.getKeyName()); + Assertions.assertEquals("myKeyVersion-32charAlphaNumericString", responseEncryptionKey.getKeyVersion()); + Assertions.assertEquals("https://myKeyVault.vault.azure.net", responseEncryptionKey.getVaultUri()); + AzureActiveDirectoryApplicationCredentials responseEncryptionKeyAccessCredentials + = responseEncryptionKey.getAccessCredentials(); + Assertions.assertNotNull(responseEncryptionKeyAccessCredentials); + Assertions.assertEquals("00000000-0000-0000-0000-000000000000", + responseEncryptionKeyAccessCredentials.getApplicationId()); + Assertions.assertEquals("", responseEncryptionKeyAccessCredentials.getApplicationSecret()); + } + + // Use "Map.of" if available + @SuppressWarnings("unchecked") + private static Map mapOf(Object... inputs) { + Map map = new HashMap<>(); + for (int i = 0; i < inputs.length; i += 2) { + String key = (String) inputs[i]; + T value = (T) inputs[i + 1]; + map.put(key, value); + } + return map; + } +} diff --git a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/generated/SearchServiceCreateOrUpdateSkillsetTests.java b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/generated/SearchServiceCreateOrUpdateSkillsetTests.java new file mode 100644 index 000000000000..786dcb3aa6b6 --- /dev/null +++ b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/generated/SearchServiceCreateOrUpdateSkillsetTests.java @@ -0,0 +1,139 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.search.documents.generated; + +import com.azure.core.http.MatchConditions; +import com.azure.search.documents.models.AIServicesAccountKey; +import com.azure.search.documents.models.AzureActiveDirectoryApplicationCredentials; +import com.azure.search.documents.models.AzureOpenAITokenizerParameters; +import com.azure.search.documents.models.CognitiveServicesAccount; +import com.azure.search.documents.models.DocumentIntelligenceLayoutSkill; +import com.azure.search.documents.models.DocumentIntelligenceLayoutSkillMarkdownHeaderDepth; +import com.azure.search.documents.models.DocumentIntelligenceLayoutSkillOutputMode; +import com.azure.search.documents.models.InputFieldMappingEntry; +import com.azure.search.documents.models.KeyPhraseExtractionSkill; +import com.azure.search.documents.models.LanguageDetectionSkill; +import com.azure.search.documents.models.OutputFieldMappingEntry; +import com.azure.search.documents.models.SearchIndexerSkill; +import com.azure.search.documents.models.SearchIndexerSkillset; +import com.azure.search.documents.models.SearchResourceEncryptionKey; +import com.azure.search.documents.models.SplitSkill; +import com.azure.search.documents.models.SplitSkillEncoderModelName; +import com.azure.search.documents.models.SplitSkillUnit; +import com.azure.search.documents.models.TextSplitMode; +import com.azure.search.documents.models.WebApiSkill; +import java.time.Duration; +import java.util.Arrays; +import java.util.List; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + +@Disabled +public final class SearchServiceCreateOrUpdateSkillsetTests extends SearchClientTestBase { + @Test + @Disabled + public void testSearchServiceCreateOrUpdateSkillsetTests() { + // method invocation + SearchIndexerSkillset response = skillsetsClient.createOrUpdate("tempskillset", + new SearchIndexerSkillset("tempskillset", Arrays.asList( + new LanguageDetectionSkill( + Arrays.asList(new InputFieldMappingEntry("text").setSource("/document/content"), + new InputFieldMappingEntry("countryHint").setSource("/document/countryHint")), + Arrays.asList(new OutputFieldMappingEntry("languageCode").setTargetName("languageCode"))) + .setName("skill2"), + new SplitSkill( + Arrays.asList(new InputFieldMappingEntry("text").setSource("/document/content"), + new InputFieldMappingEntry("languageCode").setSource("/document/languageCode")), + Arrays.asList(new OutputFieldMappingEntry("textItems").setTargetName("pages"))).setName("skill3") + .setTextSplitMode(TextSplitMode.PAGES) + .setMaximumPageLength(4000) + .setUnit(SplitSkillUnit.AZURE_OPEN_AITOKENS) + .setAzureOpenAITokenizerParameters(new AzureOpenAITokenizerParameters() + .setEncoderModelName(SplitSkillEncoderModelName.CL100K_BASE) + .setAllowedSpecialTokens(Arrays.asList("[START]", "[END]"))), + new KeyPhraseExtractionSkill( + Arrays.asList(new InputFieldMappingEntry("text").setSource("/document/content"), + new InputFieldMappingEntry("languageCode").setSource("/document/languageCode")), + Arrays.asList(new OutputFieldMappingEntry("keyPhrases").setTargetName("keyPhrases"))) + .setName("skill4") + .setContext("/document/pages/*"), + new WebApiSkill( + Arrays.asList(new InputFieldMappingEntry("text").setSource("/document/content"), + new InputFieldMappingEntry("languageCode").setSource("/document/languageCode")), + Arrays.asList(new OutputFieldMappingEntry("customresult").setTargetName("result")), + "https://contoso.example.org/").setName("skill5") + .setHttpMethod("POST") + .setTimeout(Duration.parse("PT5S")), + new DocumentIntelligenceLayoutSkill( + Arrays.asList(new InputFieldMappingEntry("file_data").setSource("/document/content")), + Arrays.asList(new OutputFieldMappingEntry("markdown_document").setTargetName("markdown_document"))) + .setName("docIntelligenceLayoutSkill") + .setContext("/document") + .setOutputMode(DocumentIntelligenceLayoutSkillOutputMode.ONE_TO_MANY) + .setMarkdownHeaderDepth(DocumentIntelligenceLayoutSkillMarkdownHeaderDepth.H3))) + .setDescription("Skillset for extracting entities and more") + .setCognitiveServicesAccount(new AIServicesAccountKey("fakeTokenPlaceholder", + "https://mySubdomainName.cognitiveservices.azure.com").setDescription( + "Description of the Azure AI service resource attached to a skillset")) + .setEncryptionKey( + new SearchResourceEncryptionKey("fakeTokenPlaceholder", "fakeTokenPlaceholder") + .setKeyVersion("fakeTokenPlaceholder") + .setAccessCredentials(new AzureActiveDirectoryApplicationCredentials( + "00000000-0000-0000-0000-000000000000") + .setApplicationSecret("fakeTokenPlaceholder"))), + null, null, new MatchConditions()); + + // response assertion + Assertions.assertNotNull(response); + // verify property "name" + Assertions.assertEquals("tempskillset", response.getName()); + // verify property "description" + Assertions.assertEquals("Skillset for extracting entities and more", response.getDescription()); + // verify property "skills" + List responseSkills = response.getSkills(); + SearchIndexerSkill responseSkillsFirstItem = responseSkills.iterator().next(); + Assertions.assertNotNull(responseSkillsFirstItem); + Assertions.assertEquals("#Microsoft.Skills.Text.LanguageDetectionSkill", + responseSkillsFirstItem.getOdataType()); + Assertions.assertEquals("skill2", responseSkillsFirstItem.getName()); + List responseSkillsFirstItemInputs = responseSkillsFirstItem.getInputs(); + InputFieldMappingEntry responseSkillsFirstItemInputsFirstItem = responseSkillsFirstItemInputs.iterator().next(); + Assertions.assertNotNull(responseSkillsFirstItemInputsFirstItem); + Assertions.assertEquals("text", responseSkillsFirstItemInputsFirstItem.getName()); + Assertions.assertEquals("/document/content", responseSkillsFirstItemInputsFirstItem.getSource()); + List responseSkillsFirstItemInputsFirstItemInputs + = responseSkillsFirstItemInputsFirstItem.getInputs(); + Assertions.assertEquals(0, responseSkillsFirstItemInputsFirstItemInputs.size()); + List responseSkillsFirstItemOutputs = responseSkillsFirstItem.getOutputs(); + OutputFieldMappingEntry responseSkillsFirstItemOutputsFirstItem + = responseSkillsFirstItemOutputs.iterator().next(); + Assertions.assertNotNull(responseSkillsFirstItemOutputsFirstItem); + Assertions.assertEquals("languageCode", responseSkillsFirstItemOutputsFirstItem.getName()); + Assertions.assertEquals("languageCode", responseSkillsFirstItemOutputsFirstItem.getTargetName()); + // verify property "cognitiveServicesAccount" + CognitiveServicesAccount responseCognitiveServicesAccount = response.getCognitiveServicesAccount(); + Assertions.assertNotNull(responseCognitiveServicesAccount); + Assertions.assertEquals("#Microsoft.Azure.Search.AIServicesByKey", + responseCognitiveServicesAccount.getOdataType()); + Assertions.assertEquals("Description of the Azure AI service resource attached to a skillset", + responseCognitiveServicesAccount.getDescription()); + // verify property "eTag" + Assertions.assertEquals("0x1234568AE7E58A1", response.getETag()); + // verify property "encryptionKey" + SearchResourceEncryptionKey responseEncryptionKey = response.getEncryptionKey(); + Assertions.assertNotNull(responseEncryptionKey); + Assertions.assertEquals("myUserManagedEncryptionKey-createdinAzureKeyVault", + responseEncryptionKey.getKeyName()); + Assertions.assertEquals("myKeyVersion-32charAlphaNumericString", responseEncryptionKey.getKeyVersion()); + Assertions.assertEquals("https://myKeyVault.vault.azure.net", responseEncryptionKey.getVaultUri()); + AzureActiveDirectoryApplicationCredentials responseEncryptionKeyAccessCredentials + = responseEncryptionKey.getAccessCredentials(); + Assertions.assertNotNull(responseEncryptionKeyAccessCredentials); + Assertions.assertEquals("00000000-0000-0000-0000-000000000000", + responseEncryptionKeyAccessCredentials.getApplicationId()); + Assertions.assertEquals("", responseEncryptionKeyAccessCredentials.getApplicationSecret()); + } +} diff --git a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/generated/SearchServiceCreateOrUpdateSynonymMapTests.java b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/generated/SearchServiceCreateOrUpdateSynonymMapTests.java new file mode 100644 index 000000000000..4db02d07c8f8 --- /dev/null +++ b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/generated/SearchServiceCreateOrUpdateSynonymMapTests.java @@ -0,0 +1,55 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.search.documents.generated; + +import com.azure.core.http.MatchConditions; +import com.azure.search.documents.models.AzureActiveDirectoryApplicationCredentials; +import com.azure.search.documents.models.SearchResourceEncryptionKey; +import com.azure.search.documents.models.SynonymMap; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + +@Disabled +public final class SearchServiceCreateOrUpdateSynonymMapTests extends SearchClientTestBase { + @Test + @Disabled + public void testSearchServiceCreateOrUpdateSynonymMapTests() { + // method invocation + SynonymMap response = synonymMapsClient.createOrUpdate("mysynonymmap", + new SynonymMap("mysynonymmap", "United States, United States of America, USA\nWashington, Wash. => WA") + .setEncryptionKey(new SearchResourceEncryptionKey("fakeTokenPlaceholder", "fakeTokenPlaceholder") + .setKeyVersion("fakeTokenPlaceholder") + .setAccessCredentials( + new AzureActiveDirectoryApplicationCredentials("00000000-0000-0000-0000-000000000000") + .setApplicationSecret("fakeTokenPlaceholder"))), + new MatchConditions()); + + // response assertion + Assertions.assertNotNull(response); + // verify property "name" + Assertions.assertEquals("mysynonymmap", response.getName()); + // verify property "format" + Assertions.assertEquals("solr", response.getFormat()); + // verify property "synonyms" + Assertions.assertEquals("United States, United States of America, USA\nWashington, Wash. => WA", + response.getSynonyms()); + // verify property "encryptionKey" + SearchResourceEncryptionKey responseEncryptionKey = response.getEncryptionKey(); + Assertions.assertNotNull(responseEncryptionKey); + Assertions.assertEquals("myUserManagedEncryptionKey-createdinAzureKeyVault", + responseEncryptionKey.getKeyName()); + Assertions.assertEquals("myKeyVersion-32charAlphaNumericString", responseEncryptionKey.getKeyVersion()); + Assertions.assertEquals("https://myKeyVault.vault.azure.net", responseEncryptionKey.getVaultUri()); + AzureActiveDirectoryApplicationCredentials responseEncryptionKeyAccessCredentials + = responseEncryptionKey.getAccessCredentials(); + Assertions.assertNotNull(responseEncryptionKeyAccessCredentials); + Assertions.assertEquals("00000000-0000-0000-0000-000000000000", + responseEncryptionKeyAccessCredentials.getApplicationId()); + Assertions.assertEquals("", responseEncryptionKeyAccessCredentials.getApplicationSecret()); + // verify property "eTag" + Assertions.assertEquals("0x1234568AE7E58A1", response.getETag()); + } +} diff --git a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/generated/SearchServiceCreateSkillsetTests.java b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/generated/SearchServiceCreateSkillsetTests.java new file mode 100644 index 000000000000..717434f98ffd --- /dev/null +++ b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/generated/SearchServiceCreateSkillsetTests.java @@ -0,0 +1,135 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.search.documents.generated; + +import com.azure.search.documents.models.AIServicesAccountKey; +import com.azure.search.documents.models.AzureActiveDirectoryApplicationCredentials; +import com.azure.search.documents.models.AzureOpenAITokenizerParameters; +import com.azure.search.documents.models.CognitiveServicesAccount; +import com.azure.search.documents.models.DocumentIntelligenceLayoutSkill; +import com.azure.search.documents.models.DocumentIntelligenceLayoutSkillMarkdownHeaderDepth; +import com.azure.search.documents.models.DocumentIntelligenceLayoutSkillOutputMode; +import com.azure.search.documents.models.InputFieldMappingEntry; +import com.azure.search.documents.models.KeyPhraseExtractionSkill; +import com.azure.search.documents.models.LanguageDetectionSkill; +import com.azure.search.documents.models.OutputFieldMappingEntry; +import com.azure.search.documents.models.SearchIndexerSkill; +import com.azure.search.documents.models.SearchIndexerSkillset; +import com.azure.search.documents.models.SearchResourceEncryptionKey; +import com.azure.search.documents.models.SplitSkill; +import com.azure.search.documents.models.SplitSkillEncoderModelName; +import com.azure.search.documents.models.SplitSkillUnit; +import com.azure.search.documents.models.TextSplitMode; +import com.azure.search.documents.models.WebApiSkill; +import java.time.Duration; +import java.util.Arrays; +import java.util.List; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + +@Disabled +public final class SearchServiceCreateSkillsetTests extends SearchClientTestBase { + @Test + @Disabled + public void testSearchServiceCreateSkillsetTests() { + // method invocation + SearchIndexerSkillset response = skillsetsClient.create(new SearchIndexerSkillset("tempskillset", + Arrays.asList( + new LanguageDetectionSkill( + Arrays.asList(new InputFieldMappingEntry("text").setSource("/document/content"), + new InputFieldMappingEntry("countryHint").setSource("/document/countryHint")), + Arrays.asList(new OutputFieldMappingEntry("languageCode").setTargetName("languageCode"))) + .setName("skill2"), + new SplitSkill( + Arrays.asList(new InputFieldMappingEntry("text").setSource("/document/content"), + new InputFieldMappingEntry("languageCode").setSource("/document/languageCode")), + Arrays.asList(new OutputFieldMappingEntry("textItems").setTargetName("pages"))).setName("skill3") + .setTextSplitMode(TextSplitMode.PAGES) + .setMaximumPageLength(4000) + .setUnit(SplitSkillUnit.AZURE_OPEN_AITOKENS) + .setAzureOpenAITokenizerParameters(new AzureOpenAITokenizerParameters() + .setEncoderModelName(SplitSkillEncoderModelName.CL100K_BASE) + .setAllowedSpecialTokens(Arrays.asList("[START]", "[END]"))), + new KeyPhraseExtractionSkill( + Arrays.asList(new InputFieldMappingEntry("text").setSource("/document/content"), + new InputFieldMappingEntry("languageCode").setSource("/document/languageCode")), + Arrays.asList(new OutputFieldMappingEntry("keyPhrases").setTargetName("keyPhrases"))) + .setName("skill4") + .setContext("/document/pages/*"), + new WebApiSkill( + Arrays.asList(new InputFieldMappingEntry("text").setSource("/document/content"), + new InputFieldMappingEntry("languageCode").setSource("/document/languageCode")), + Arrays.asList(new OutputFieldMappingEntry("customresult").setTargetName("result")), + "https://contoso.example.org/").setName("skill5") + .setHttpMethod("POST") + .setTimeout(Duration.parse("PT5S")), + new DocumentIntelligenceLayoutSkill( + Arrays.asList(new InputFieldMappingEntry("file_data").setSource("/document/content")), + Arrays.asList(new OutputFieldMappingEntry("markdown_document").setTargetName("markdown_document"))) + .setName("docIntelligenceLayoutSkill") + .setContext("/document") + .setOutputMode(DocumentIntelligenceLayoutSkillOutputMode.ONE_TO_MANY) + .setMarkdownHeaderDepth(DocumentIntelligenceLayoutSkillMarkdownHeaderDepth.H3))) + .setDescription("Skillset for extracting entities and more") + .setCognitiveServicesAccount(new AIServicesAccountKey("fakeTokenPlaceholder", + "https://mySubdomainName.cognitiveservices.azure.com").setDescription( + "Description of the Azure AI service resource attached to a skillset")) + .setEncryptionKey( + new SearchResourceEncryptionKey("fakeTokenPlaceholder", "fakeTokenPlaceholder") + .setKeyVersion("fakeTokenPlaceholder") + .setAccessCredentials(new AzureActiveDirectoryApplicationCredentials( + "00000000-0000-0000-0000-000000000000") + .setApplicationSecret("fakeTokenPlaceholder")))); + + // response assertion + Assertions.assertNotNull(response); + // verify property "name" + Assertions.assertEquals("tempskillset", response.getName()); + // verify property "description" + Assertions.assertEquals("Skillset for extracting entities and more", response.getDescription()); + // verify property "skills" + List responseSkills = response.getSkills(); + SearchIndexerSkill responseSkillsFirstItem = responseSkills.iterator().next(); + Assertions.assertNotNull(responseSkillsFirstItem); + Assertions.assertEquals("#Microsoft.Skills.Text.LanguageDetectionSkill", + responseSkillsFirstItem.getOdataType()); + Assertions.assertEquals("skill2", responseSkillsFirstItem.getName()); + List responseSkillsFirstItemInputs = responseSkillsFirstItem.getInputs(); + InputFieldMappingEntry responseSkillsFirstItemInputsFirstItem = responseSkillsFirstItemInputs.iterator().next(); + Assertions.assertNotNull(responseSkillsFirstItemInputsFirstItem); + Assertions.assertEquals("text", responseSkillsFirstItemInputsFirstItem.getName()); + Assertions.assertEquals("/document/content", responseSkillsFirstItemInputsFirstItem.getSource()); + List responseSkillsFirstItemInputsFirstItemInputs + = responseSkillsFirstItemInputsFirstItem.getInputs(); + Assertions.assertEquals(0, responseSkillsFirstItemInputsFirstItemInputs.size()); + List responseSkillsFirstItemOutputs = responseSkillsFirstItem.getOutputs(); + OutputFieldMappingEntry responseSkillsFirstItemOutputsFirstItem + = responseSkillsFirstItemOutputs.iterator().next(); + Assertions.assertNotNull(responseSkillsFirstItemOutputsFirstItem); + Assertions.assertEquals("languageCode", responseSkillsFirstItemOutputsFirstItem.getName()); + Assertions.assertEquals("languageCode", responseSkillsFirstItemOutputsFirstItem.getTargetName()); + // verify property "cognitiveServicesAccount" + CognitiveServicesAccount responseCognitiveServicesAccount = response.getCognitiveServicesAccount(); + Assertions.assertNotNull(responseCognitiveServicesAccount); + Assertions.assertEquals("#Microsoft.Azure.Search.AIServicesByKey", + responseCognitiveServicesAccount.getOdataType()); + Assertions.assertEquals("Description of the Azure AI service resource attached to a skillset", + responseCognitiveServicesAccount.getDescription()); + // verify property "encryptionKey" + SearchResourceEncryptionKey responseEncryptionKey = response.getEncryptionKey(); + Assertions.assertNotNull(responseEncryptionKey); + Assertions.assertEquals("myUserManagedEncryptionKey-createdinAzureKeyVault", + responseEncryptionKey.getKeyName()); + Assertions.assertEquals("myKeyVersion-32charAlphaNumericString", responseEncryptionKey.getKeyVersion()); + Assertions.assertEquals("https://myKeyVault.vault.azure.net", responseEncryptionKey.getVaultUri()); + AzureActiveDirectoryApplicationCredentials responseEncryptionKeyAccessCredentials + = responseEncryptionKey.getAccessCredentials(); + Assertions.assertNotNull(responseEncryptionKeyAccessCredentials); + Assertions.assertEquals("00000000-0000-0000-0000-000000000000", + responseEncryptionKeyAccessCredentials.getApplicationId()); + Assertions.assertEquals("", responseEncryptionKeyAccessCredentials.getApplicationSecret()); + } +} diff --git a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/generated/SearchServiceCreateSynonymMapTests.java b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/generated/SearchServiceCreateSynonymMapTests.java new file mode 100644 index 000000000000..b5a2dcad9c54 --- /dev/null +++ b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/generated/SearchServiceCreateSynonymMapTests.java @@ -0,0 +1,53 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.search.documents.generated; + +import com.azure.search.documents.models.AzureActiveDirectoryApplicationCredentials; +import com.azure.search.documents.models.SearchResourceEncryptionKey; +import com.azure.search.documents.models.SynonymMap; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + +@Disabled +public final class SearchServiceCreateSynonymMapTests extends SearchClientTestBase { + @Test + @Disabled + public void testSearchServiceCreateSynonymMapTests() { + // method invocation + SynonymMap response = synonymMapsClient.create( + new SynonymMap("tempsynonymmap", "United States, United States of America, USA\nWashington, Wash. => WA") + .setEncryptionKey(new SearchResourceEncryptionKey("fakeTokenPlaceholder", "fakeTokenPlaceholder") + .setKeyVersion("fakeTokenPlaceholder") + .setAccessCredentials( + new AzureActiveDirectoryApplicationCredentials("00000000-0000-0000-0000-000000000000") + .setApplicationSecret("fakeTokenPlaceholder")))); + + // response assertion + Assertions.assertNotNull(response); + // verify property "name" + Assertions.assertEquals("tempsynonymmap", response.getName()); + // verify property "format" + Assertions.assertEquals("solr", response.getFormat()); + // verify property "synonyms" + Assertions.assertEquals("United States, United States of America, USA\nWashington, Wash. => WA", + response.getSynonyms()); + // verify property "encryptionKey" + SearchResourceEncryptionKey responseEncryptionKey = response.getEncryptionKey(); + Assertions.assertNotNull(responseEncryptionKey); + Assertions.assertEquals("myUserManagedEncryptionKey-createdinAzureKeyVault", + responseEncryptionKey.getKeyName()); + Assertions.assertEquals("myKeyVersion-32charAlphaNumericString", responseEncryptionKey.getKeyVersion()); + Assertions.assertEquals("https://myKeyVault.vault.azure.net", responseEncryptionKey.getVaultUri()); + AzureActiveDirectoryApplicationCredentials responseEncryptionKeyAccessCredentials + = responseEncryptionKey.getAccessCredentials(); + Assertions.assertNotNull(responseEncryptionKeyAccessCredentials); + Assertions.assertEquals("00000000-0000-0000-0000-000000000000", + responseEncryptionKeyAccessCredentials.getApplicationId()); + Assertions.assertEquals("", responseEncryptionKeyAccessCredentials.getApplicationSecret()); + // verify property "eTag" + Assertions.assertEquals("0x1234568AE7E58A1", response.getETag()); + } +} diff --git a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/generated/SearchServiceDeleteAliasTests.java b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/generated/SearchServiceDeleteAliasTests.java new file mode 100644 index 000000000000..014b174e4349 --- /dev/null +++ b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/generated/SearchServiceDeleteAliasTests.java @@ -0,0 +1,19 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.search.documents.generated; + +import com.azure.core.http.MatchConditions; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + +@Disabled +public final class SearchServiceDeleteAliasTests extends SearchClientTestBase { + @Test + @Disabled + public void testSearchServiceDeleteAliasTests() { + // method invocation + aliasesClient.delete("tempalias", new MatchConditions()); + } +} diff --git a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/generated/SearchServiceDeleteDataSourceTests.java b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/generated/SearchServiceDeleteDataSourceTests.java new file mode 100644 index 000000000000..3d966400ac39 --- /dev/null +++ b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/generated/SearchServiceDeleteDataSourceTests.java @@ -0,0 +1,19 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.search.documents.generated; + +import com.azure.core.http.MatchConditions; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + +@Disabled +public final class SearchServiceDeleteDataSourceTests extends SearchClientTestBase { + @Test + @Disabled + public void testSearchServiceDeleteDataSourceTests() { + // method invocation + dataSourcesClient.delete("tempdatasource", new MatchConditions()); + } +} diff --git a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/generated/SearchServiceDeleteIndexTests.java b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/generated/SearchServiceDeleteIndexTests.java new file mode 100644 index 000000000000..876825e0dd3e --- /dev/null +++ b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/generated/SearchServiceDeleteIndexTests.java @@ -0,0 +1,19 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.search.documents.generated; + +import com.azure.core.http.MatchConditions; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + +@Disabled +public final class SearchServiceDeleteIndexTests extends SearchClientTestBase { + @Test + @Disabled + public void testSearchServiceDeleteIndexTests() { + // method invocation + indexesClient.delete("temp-preview-test", new MatchConditions()); + } +} diff --git a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/generated/SearchServiceDeleteIndexerTests.java b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/generated/SearchServiceDeleteIndexerTests.java new file mode 100644 index 000000000000..c7a889b42f78 --- /dev/null +++ b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/generated/SearchServiceDeleteIndexerTests.java @@ -0,0 +1,19 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.search.documents.generated; + +import com.azure.core.http.MatchConditions; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + +@Disabled +public final class SearchServiceDeleteIndexerTests extends SearchClientTestBase { + @Test + @Disabled + public void testSearchServiceDeleteIndexerTests() { + // method invocation + indexersClient.delete("tempindexer", new MatchConditions()); + } +} diff --git a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/generated/SearchServiceDeleteSkillsetTests.java b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/generated/SearchServiceDeleteSkillsetTests.java new file mode 100644 index 000000000000..d68d6b0b6768 --- /dev/null +++ b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/generated/SearchServiceDeleteSkillsetTests.java @@ -0,0 +1,19 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.search.documents.generated; + +import com.azure.core.http.MatchConditions; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + +@Disabled +public final class SearchServiceDeleteSkillsetTests extends SearchClientTestBase { + @Test + @Disabled + public void testSearchServiceDeleteSkillsetTests() { + // method invocation + skillsetsClient.delete("tempskillset", new MatchConditions()); + } +} diff --git a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/generated/SearchServiceDeleteSynonymMapTests.java b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/generated/SearchServiceDeleteSynonymMapTests.java new file mode 100644 index 000000000000..0064c753f0e6 --- /dev/null +++ b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/generated/SearchServiceDeleteSynonymMapTests.java @@ -0,0 +1,19 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.search.documents.generated; + +import com.azure.core.http.MatchConditions; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + +@Disabled +public final class SearchServiceDeleteSynonymMapTests extends SearchClientTestBase { + @Test + @Disabled + public void testSearchServiceDeleteSynonymMapTests() { + // method invocation + synonymMapsClient.delete("tempsynonymmap", new MatchConditions()); + } +} diff --git a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/generated/SearchServiceGetAliasTests.java b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/generated/SearchServiceGetAliasTests.java new file mode 100644 index 000000000000..b267cbc1e862 --- /dev/null +++ b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/generated/SearchServiceGetAliasTests.java @@ -0,0 +1,29 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.search.documents.generated; + +import com.azure.search.documents.models.SearchAlias; +import java.util.List; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + +@Disabled +public final class SearchServiceGetAliasTests extends SearchClientTestBase { + @Test + @Disabled + public void testSearchServiceGetAliasTests() { + // method invocation + SearchAlias response = aliasesClient.get("myalias"); + + // response assertion + Assertions.assertNotNull(response); + // verify property "name" + Assertions.assertEquals("myalias", response.getName()); + // verify property "indexes" + List responseIndexes = response.getIndexes(); + Assertions.assertEquals("preview-test", responseIndexes.iterator().next()); + } +} diff --git a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/generated/SearchServiceGetDataSourceTests.java b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/generated/SearchServiceGetDataSourceTests.java new file mode 100644 index 000000000000..a14c4d90e792 --- /dev/null +++ b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/generated/SearchServiceGetDataSourceTests.java @@ -0,0 +1,72 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.search.documents.generated; + +import com.azure.search.documents.models.AzureActiveDirectoryApplicationCredentials; +import com.azure.search.documents.models.DataChangeDetectionPolicy; +import com.azure.search.documents.models.DataDeletionDetectionPolicy; +import com.azure.search.documents.models.DataSourceCredentials; +import com.azure.search.documents.models.SearchIndexerDataContainer; +import com.azure.search.documents.models.SearchIndexerDataSource; +import com.azure.search.documents.models.SearchIndexerDataSourceType; +import com.azure.search.documents.models.SearchResourceEncryptionKey; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + +@Disabled +public final class SearchServiceGetDataSourceTests extends SearchClientTestBase { + @Test + @Disabled + public void testSearchServiceGetDataSourceTests() { + // method invocation + SearchIndexerDataSource response = dataSourcesClient.get("mydocdbdatasource"); + + // response assertion + Assertions.assertNotNull(response); + // verify property "name" + Assertions.assertEquals("mydocdbdatasource", response.getName()); + // verify property "description" + Assertions.assertEquals("My Azure Blob data source.", response.getDescription()); + // verify property "type" + Assertions.assertEquals(SearchIndexerDataSourceType.AZURE_BLOB, response.getType()); + // verify property "credentials" + DataSourceCredentials responseCredentials = response.getCredentials(); + Assertions.assertNotNull(responseCredentials); + Assertions.assertEquals( + "DefaultEndpointsProtocol=https;AccountName=myAccountName;AccountKey=myAccountKey;EndpointSuffix=core.windows.net ", + responseCredentials.getConnectionString()); + // verify property "container" + SearchIndexerDataContainer responseContainer = response.getContainer(); + Assertions.assertNotNull(responseContainer); + Assertions.assertEquals("doc-extraction-skillset", responseContainer.getName()); + Assertions.assertEquals("E2E_Dsat", responseContainer.getQuery()); + // verify property "dataChangeDetectionPolicy" + DataChangeDetectionPolicy responseDataChangeDetectionPolicy = response.getDataChangeDetectionPolicy(); + Assertions.assertNotNull(responseDataChangeDetectionPolicy); + Assertions.assertEquals("#Microsoft.Azure.Search.HighWaterMarkChangeDetectionPolicy", + responseDataChangeDetectionPolicy.getOdataType()); + // verify property "dataDeletionDetectionPolicy" + DataDeletionDetectionPolicy responseDataDeletionDetectionPolicy = response.getDataDeletionDetectionPolicy(); + Assertions.assertNotNull(responseDataDeletionDetectionPolicy); + Assertions.assertEquals("#Microsoft.Azure.Search.SoftDeleteColumnDeletionDetectionPolicy", + responseDataDeletionDetectionPolicy.getOdataType()); + // verify property "eTag" + Assertions.assertEquals("0x1234568AE7E58A1", response.getETag()); + // verify property "encryptionKey" + SearchResourceEncryptionKey responseEncryptionKey = response.getEncryptionKey(); + Assertions.assertNotNull(responseEncryptionKey); + Assertions.assertEquals("myUserManagedEncryptionKey-createdinAzureKeyVault", + responseEncryptionKey.getKeyName()); + Assertions.assertEquals("myKeyVersion-32charAlphaNumericString", responseEncryptionKey.getKeyVersion()); + Assertions.assertEquals("https://myKeyVault.vault.azure.net", responseEncryptionKey.getVaultUri()); + AzureActiveDirectoryApplicationCredentials responseEncryptionKeyAccessCredentials + = responseEncryptionKey.getAccessCredentials(); + Assertions.assertNotNull(responseEncryptionKeyAccessCredentials); + Assertions.assertEquals("00000000-0000-0000-0000-000000000000", + responseEncryptionKeyAccessCredentials.getApplicationId()); + Assertions.assertEquals("", responseEncryptionKeyAccessCredentials.getApplicationSecret()); + } +} diff --git a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/generated/SearchServiceGetIndexStatisticsTests.java b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/generated/SearchServiceGetIndexStatisticsTests.java new file mode 100644 index 000000000000..e4f9b2e7928a --- /dev/null +++ b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/generated/SearchServiceGetIndexStatisticsTests.java @@ -0,0 +1,29 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.search.documents.generated; + +import com.azure.search.documents.models.GetIndexStatisticsResult; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + +@Disabled +public final class SearchServiceGetIndexStatisticsTests extends SearchClientTestBase { + @Test + @Disabled + public void testSearchServiceGetIndexStatisticsTests() { + // method invocation + GetIndexStatisticsResult response = indexesClient.getStatistics("preview-test"); + + // response assertion + Assertions.assertNotNull(response); + // verify property "documentCount" + Assertions.assertEquals(12L, response.getDocumentCount()); + // verify property "storageSize" + Assertions.assertEquals(123456L, response.getStorageSize()); + // verify property "vectorIndexSize" + Assertions.assertEquals(123456L, response.getVectorIndexSize()); + } +} diff --git a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/generated/SearchServiceGetIndexStatsSummaryTests.java b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/generated/SearchServiceGetIndexStatsSummaryTests.java new file mode 100644 index 000000000000..ac699f77fc39 --- /dev/null +++ b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/generated/SearchServiceGetIndexStatsSummaryTests.java @@ -0,0 +1,25 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.search.documents.generated; + +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.http.rest.RequestOptions; +import com.azure.core.util.BinaryData; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + +public final class SearchServiceGetIndexStatsSummaryTests extends SearchClientTestBase { + @Test + @Disabled + public void testSearchServiceGetIndexStatsSummaryTests() { + RequestOptions requestOptions = new RequestOptions(); + PagedIterable response = dataSourcesClient.getIndexStatsSummary(requestOptions); + Assertions.assertEquals(200, response.iterableByPage().iterator().next().getStatusCode()); + Assertions.assertEquals(BinaryData + .fromString("{\"name\":\"preview-test\",\"documentCount\":0,\"storageSize\":0,\"vectorIndexSize\":0}") + .toObject(Object.class), response.iterator().next().toObject(Object.class)); + } +} diff --git a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/generated/SearchServiceGetIndexTests.java b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/generated/SearchServiceGetIndexTests.java new file mode 100644 index 000000000000..381f21df60ea --- /dev/null +++ b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/generated/SearchServiceGetIndexTests.java @@ -0,0 +1,217 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.search.documents.generated; + +import com.azure.search.documents.models.CharFilter; +import com.azure.search.documents.models.CorsOptions; +import com.azure.search.documents.models.LexicalAnalyzer; +import com.azure.search.documents.models.LexicalNormalizer; +import com.azure.search.documents.models.LexicalTokenizer; +import com.azure.search.documents.models.RescoringOptions; +import com.azure.search.documents.models.ScoringFunction; +import com.azure.search.documents.models.ScoringFunctionAggregation; +import com.azure.search.documents.models.ScoringFunctionInterpolation; +import com.azure.search.documents.models.ScoringProfile; +import com.azure.search.documents.models.SearchField; +import com.azure.search.documents.models.SearchFieldDataType; +import com.azure.search.documents.models.SearchIndex; +import com.azure.search.documents.models.SearchSuggester; +import com.azure.search.documents.models.SemanticConfiguration; +import com.azure.search.documents.models.SemanticField; +import com.azure.search.documents.models.SemanticPrioritizedFields; +import com.azure.search.documents.models.SemanticSearch; +import com.azure.search.documents.models.SimilarityAlgorithm; +import com.azure.search.documents.models.TextWeights; +import com.azure.search.documents.models.TokenFilter; +import com.azure.search.documents.models.VectorSearch; +import com.azure.search.documents.models.VectorSearchAlgorithmConfiguration; +import com.azure.search.documents.models.VectorSearchAlgorithmKind; +import com.azure.search.documents.models.VectorSearchCompression; +import com.azure.search.documents.models.VectorSearchCompressionKind; +import com.azure.search.documents.models.VectorSearchCompressionRescoreStorageMethod; +import com.azure.search.documents.models.VectorSearchProfile; +import com.azure.search.documents.models.VectorSearchVectorizer; +import com.azure.search.documents.models.VectorSearchVectorizerKind; +import java.util.List; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + +@Disabled +public final class SearchServiceGetIndexTests extends SearchClientTestBase { + @Test + @Disabled + public void testSearchServiceGetIndexTests() { + // method invocation + SearchIndex response = indexesClient.get("preview-test"); + + // response assertion + Assertions.assertNotNull(response); + // verify property "name" + Assertions.assertEquals("preview-test", response.getName()); + // verify property "fields" + List responseFields = response.getFields(); + SearchField responseFieldsFirstItem = responseFields.iterator().next(); + Assertions.assertNotNull(responseFieldsFirstItem); + Assertions.assertEquals("id", responseFieldsFirstItem.getName()); + Assertions.assertEquals(SearchFieldDataType.STRING, responseFieldsFirstItem.getType()); + Assertions.assertEquals(true, responseFieldsFirstItem.isKey()); + Assertions.assertEquals(true, responseFieldsFirstItem.isRetrievable()); + Assertions.assertEquals(true, responseFieldsFirstItem.isStored()); + Assertions.assertEquals(true, responseFieldsFirstItem.isSearchable()); + Assertions.assertEquals(true, responseFieldsFirstItem.isFilterable()); + Assertions.assertEquals(true, responseFieldsFirstItem.isSortable()); + Assertions.assertEquals(true, responseFieldsFirstItem.isFacetable()); + List responseFieldsFirstItemSynonymMaps = responseFieldsFirstItem.getSynonymMaps(); + Assertions.assertEquals(0, responseFieldsFirstItemSynonymMaps.size()); + // verify property "scoringProfiles" + List responseScoringProfiles = response.getScoringProfiles(); + ScoringProfile responseScoringProfilesFirstItem = responseScoringProfiles.iterator().next(); + Assertions.assertNotNull(responseScoringProfilesFirstItem); + Assertions.assertEquals("stringFieldBoost", responseScoringProfilesFirstItem.getName()); + TextWeights responseScoringProfilesFirstItemTextWeights = responseScoringProfilesFirstItem.getTextWeights(); + Assertions.assertNotNull(responseScoringProfilesFirstItemTextWeights); + Assertions.assertNotNull(responseScoringProfilesFirstItemTextWeights.getWeights()); + List responseScoringProfilesFirstItemFunctions + = responseScoringProfilesFirstItem.getFunctions(); + ScoringFunction responseScoringProfilesFirstItemFunctionsFirstItem + = responseScoringProfilesFirstItemFunctions.iterator().next(); + Assertions.assertNotNull(responseScoringProfilesFirstItemFunctionsFirstItem); + Assertions.assertEquals("tag", responseScoringProfilesFirstItemFunctionsFirstItem.getType()); + Assertions.assertEquals("category", responseScoringProfilesFirstItemFunctionsFirstItem.getFieldName()); + Assertions.assertEquals(2.0, responseScoringProfilesFirstItemFunctionsFirstItem.getBoost()); + Assertions.assertEquals(ScoringFunctionInterpolation.LINEAR, + responseScoringProfilesFirstItemFunctionsFirstItem.getInterpolation()); + Assertions.assertEquals(ScoringFunctionAggregation.SUM, + responseScoringProfilesFirstItem.getFunctionAggregation()); + // verify property "defaultScoringProfile" + Assertions.assertEquals("stringFieldBoost", response.getDefaultScoringProfile()); + // verify property "corsOptions" + CorsOptions responseCorsOptions = response.getCorsOptions(); + Assertions.assertNotNull(responseCorsOptions); + List responseCorsOptionsAllowedOrigins = responseCorsOptions.getAllowedOrigins(); + Assertions.assertEquals("https://www.example.com/foo", responseCorsOptionsAllowedOrigins.iterator().next()); + Assertions.assertEquals(10L, responseCorsOptions.getMaxAgeInSeconds()); + // verify property "suggesters" + List responseSuggesters = response.getSuggesters(); + SearchSuggester responseSuggestersFirstItem = responseSuggesters.iterator().next(); + Assertions.assertNotNull(responseSuggestersFirstItem); + Assertions.assertEquals("sg", responseSuggestersFirstItem.getName()); + Assertions.assertEquals("analyzingInfixMatching", responseSuggestersFirstItem.getSearchMode()); + List responseSuggestersFirstItemSourceFields = responseSuggestersFirstItem.getSourceFields(); + Assertions.assertEquals("category", responseSuggestersFirstItemSourceFields.iterator().next()); + // verify property "analyzers" + List responseAnalyzers = response.getAnalyzers(); + LexicalAnalyzer responseAnalyzersFirstItem = responseAnalyzers.iterator().next(); + Assertions.assertNotNull(responseAnalyzersFirstItem); + Assertions.assertEquals("#Microsoft.Azure.Search.CustomAnalyzer", responseAnalyzersFirstItem.getOdataType()); + Assertions.assertEquals("tagsAnalyzer", responseAnalyzersFirstItem.getName()); + // verify property "tokenizers" + List responseTokenizers = response.getTokenizers(); + LexicalTokenizer responseTokenizersFirstItem = responseTokenizers.iterator().next(); + Assertions.assertNotNull(responseTokenizersFirstItem); + Assertions.assertEquals("#Microsoft.Azure.Search.StandardTokenizerV2", + responseTokenizersFirstItem.getOdataType()); + Assertions.assertEquals("my_tokenizer", responseTokenizersFirstItem.getName()); + // verify property "tokenFilters" + List responseTokenFilters = response.getTokenFilters(); + TokenFilter responseTokenFiltersFirstItem = responseTokenFilters.iterator().next(); + Assertions.assertNotNull(responseTokenFiltersFirstItem); + Assertions.assertEquals("#Microsoft.Azure.Search.AsciiFoldingTokenFilter", + responseTokenFiltersFirstItem.getOdataType()); + Assertions.assertEquals("my_tokenFilter", responseTokenFiltersFirstItem.getName()); + // verify property "charFilters" + List responseCharFilters = response.getCharFilters(); + CharFilter responseCharFiltersFirstItem = responseCharFilters.iterator().next(); + Assertions.assertNotNull(responseCharFiltersFirstItem); + Assertions.assertEquals("#Microsoft.Azure.Search.MappingCharFilter", + responseCharFiltersFirstItem.getOdataType()); + Assertions.assertEquals("my_mapping", responseCharFiltersFirstItem.getName()); + // verify property "normalizers" + List responseNormalizers = response.getNormalizers(); + LexicalNormalizer responseNormalizersFirstItem = responseNormalizers.iterator().next(); + Assertions.assertNotNull(responseNormalizersFirstItem); + Assertions.assertEquals("#Microsoft.Azure.Search.CustomNormalizer", + responseNormalizersFirstItem.getOdataType()); + Assertions.assertEquals("my_normalizer", responseNormalizersFirstItem.getName()); + // verify property "similarity" + SimilarityAlgorithm responseSimilarity = response.getSimilarity(); + Assertions.assertNotNull(responseSimilarity); + Assertions.assertEquals("#Microsoft.Azure.Search.BM25Similarity", responseSimilarity.getOdataType()); + // verify property "semanticSearch" + SemanticSearch responseSemanticSearch = response.getSemanticSearch(); + Assertions.assertNotNull(responseSemanticSearch); + Assertions.assertEquals("testconfig", responseSemanticSearch.getDefaultConfigurationName()); + List responseSemanticSearchConfigurations = responseSemanticSearch.getConfigurations(); + SemanticConfiguration responseSemanticSearchConfigurationsFirstItem + = responseSemanticSearchConfigurations.iterator().next(); + Assertions.assertNotNull(responseSemanticSearchConfigurationsFirstItem); + Assertions.assertEquals("testconfig", responseSemanticSearchConfigurationsFirstItem.getName()); + SemanticPrioritizedFields responseSemanticSearchConfigurationsFirstItemPrioritizedFields + = responseSemanticSearchConfigurationsFirstItem.getPrioritizedFields(); + Assertions.assertNotNull(responseSemanticSearchConfigurationsFirstItemPrioritizedFields); + SemanticField responseSemanticSearchConfigurationsFirstItemPrioritizedFieldsTitleField + = responseSemanticSearchConfigurationsFirstItemPrioritizedFields.getTitleField(); + Assertions.assertNotNull(responseSemanticSearchConfigurationsFirstItemPrioritizedFieldsTitleField); + Assertions.assertEquals("category", + responseSemanticSearchConfigurationsFirstItemPrioritizedFieldsTitleField.getFieldName()); + List responseSemanticSearchConfigurationsFirstItemPrioritizedFieldsContentFields + = responseSemanticSearchConfigurationsFirstItemPrioritizedFields.getContentFields(); + SemanticField responseSemanticSearchConfigurationsFirstItemPrioritizedFieldsContentFieldsFirstItem + = responseSemanticSearchConfigurationsFirstItemPrioritizedFieldsContentFields.iterator().next(); + Assertions.assertNotNull(responseSemanticSearchConfigurationsFirstItemPrioritizedFieldsContentFieldsFirstItem); + Assertions.assertEquals("description", + responseSemanticSearchConfigurationsFirstItemPrioritizedFieldsContentFieldsFirstItem.getFieldName()); + List responseSemanticSearchConfigurationsFirstItemPrioritizedFieldsKeywordsFields + = responseSemanticSearchConfigurationsFirstItemPrioritizedFields.getKeywordsFields(); + SemanticField responseSemanticSearchConfigurationsFirstItemPrioritizedFieldsKeywordsFieldsFirstItem + = responseSemanticSearchConfigurationsFirstItemPrioritizedFieldsKeywordsFields.iterator().next(); + Assertions.assertNotNull(responseSemanticSearchConfigurationsFirstItemPrioritizedFieldsKeywordsFieldsFirstItem); + Assertions.assertEquals("ownerId", + responseSemanticSearchConfigurationsFirstItemPrioritizedFieldsKeywordsFieldsFirstItem.getFieldName()); + Assertions.assertEquals(false, responseSemanticSearchConfigurationsFirstItem.isFlightingOptIn()); + // verify property "vectorSearch" + VectorSearch responseVectorSearch = response.getVectorSearch(); + Assertions.assertNotNull(responseVectorSearch); + List responseVectorSearchProfiles = responseVectorSearch.getProfiles(); + VectorSearchProfile responseVectorSearchProfilesFirstItem = responseVectorSearchProfiles.iterator().next(); + Assertions.assertNotNull(responseVectorSearchProfilesFirstItem); + Assertions.assertEquals("config1", responseVectorSearchProfilesFirstItem.getName()); + Assertions.assertEquals("cosine", responseVectorSearchProfilesFirstItem.getAlgorithmConfigurationName()); + Assertions.assertEquals("openai", responseVectorSearchProfilesFirstItem.getVectorizerName()); + Assertions.assertEquals("mySQ8", responseVectorSearchProfilesFirstItem.getCompressionName()); + List responseVectorSearchAlgorithms = responseVectorSearch.getAlgorithms(); + VectorSearchAlgorithmConfiguration responseVectorSearchAlgorithmsFirstItem + = responseVectorSearchAlgorithms.iterator().next(); + Assertions.assertNotNull(responseVectorSearchAlgorithmsFirstItem); + Assertions.assertEquals(VectorSearchAlgorithmKind.HNSW, responseVectorSearchAlgorithmsFirstItem.getKind()); + Assertions.assertEquals("cosine", responseVectorSearchAlgorithmsFirstItem.getName()); + List responseVectorSearchVectorizers = responseVectorSearch.getVectorizers(); + VectorSearchVectorizer responseVectorSearchVectorizersFirstItem + = responseVectorSearchVectorizers.iterator().next(); + Assertions.assertNotNull(responseVectorSearchVectorizersFirstItem); + Assertions.assertEquals(VectorSearchVectorizerKind.AZURE_OPEN_AI, + responseVectorSearchVectorizersFirstItem.getKind()); + Assertions.assertEquals("openai", responseVectorSearchVectorizersFirstItem.getVectorizerName()); + List responseVectorSearchCompressions = responseVectorSearch.getCompressions(); + VectorSearchCompression responseVectorSearchCompressionsFirstItem + = responseVectorSearchCompressions.iterator().next(); + Assertions.assertNotNull(responseVectorSearchCompressionsFirstItem); + Assertions.assertEquals(VectorSearchCompressionKind.SCALAR_QUANTIZATION, + responseVectorSearchCompressionsFirstItem.getKind()); + Assertions.assertEquals("mySQ8", responseVectorSearchCompressionsFirstItem.getCompressionName()); + RescoringOptions responseVectorSearchCompressionsFirstItemRescoringOptions + = responseVectorSearchCompressionsFirstItem.getRescoringOptions(); + Assertions.assertNotNull(responseVectorSearchCompressionsFirstItemRescoringOptions); + Assertions.assertEquals(true, responseVectorSearchCompressionsFirstItemRescoringOptions.isEnableRescoring()); + Assertions.assertEquals(10.0D, + responseVectorSearchCompressionsFirstItemRescoringOptions.getDefaultOversampling()); + Assertions.assertEquals(VectorSearchCompressionRescoreStorageMethod.PRESERVE_ORIGINALS, + responseVectorSearchCompressionsFirstItemRescoringOptions.getRescoreStorageMethod()); + Assertions.assertEquals(2, responseVectorSearchCompressionsFirstItem.getTruncationDimension()); + // verify property "eTag" + Assertions.assertEquals("0x1234568AE7E58A1", response.getETag()); + } +} diff --git a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/generated/SearchServiceGetIndexerStatusTests.java b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/generated/SearchServiceGetIndexerStatusTests.java new file mode 100644 index 000000000000..ad3a19f04c7d --- /dev/null +++ b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/generated/SearchServiceGetIndexerStatusTests.java @@ -0,0 +1,65 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.search.documents.generated; + +import com.azure.search.documents.models.IndexerExecutionResult; +import com.azure.search.documents.models.IndexerExecutionStatus; +import com.azure.search.documents.models.IndexerStatus; +import com.azure.search.documents.models.SearchIndexerError; +import com.azure.search.documents.models.SearchIndexerLimits; +import com.azure.search.documents.models.SearchIndexerStatus; +import com.azure.search.documents.models.SearchIndexerWarning; +import java.util.List; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + +@Disabled +public final class SearchServiceGetIndexerStatusTests extends SearchClientTestBase { + @Test + @Disabled + public void testSearchServiceGetIndexerStatusTests() { + // method invocation + SearchIndexerStatus response = indexersClient.getStatus("myindexer"); + + // response assertion + Assertions.assertNotNull(response); + // verify property "status" + Assertions.assertEquals(IndexerStatus.RUNNING, response.getStatus()); + // verify property "lastResult" + IndexerExecutionResult responseLastResult = response.getLastResult(); + Assertions.assertNotNull(responseLastResult); + Assertions.assertEquals(IndexerExecutionStatus.SUCCESS, responseLastResult.getStatus()); + Assertions.assertNotNull(responseLastResult.getStartTime()); + Assertions.assertNotNull(responseLastResult.getEndTime()); + List responseLastResultErrors = responseLastResult.getErrors(); + Assertions.assertEquals(0, responseLastResultErrors.size()); + List responseLastResultWarnings = responseLastResult.getWarnings(); + Assertions.assertEquals(0, responseLastResultWarnings.size()); + Assertions.assertEquals(11, responseLastResult.getItemCount()); + Assertions.assertEquals(0, responseLastResult.getFailedItemCount()); + // verify property "executionHistory" + List responseExecutionHistory = response.getExecutionHistory(); + IndexerExecutionResult responseExecutionHistoryFirstItem = responseExecutionHistory.iterator().next(); + Assertions.assertNotNull(responseExecutionHistoryFirstItem); + Assertions.assertEquals(IndexerExecutionStatus.SUCCESS, responseExecutionHistoryFirstItem.getStatus()); + Assertions.assertNotNull(responseExecutionHistoryFirstItem.getStartTime()); + Assertions.assertNotNull(responseExecutionHistoryFirstItem.getEndTime()); + List responseExecutionHistoryFirstItemErrors + = responseExecutionHistoryFirstItem.getErrors(); + Assertions.assertEquals(0, responseExecutionHistoryFirstItemErrors.size()); + List responseExecutionHistoryFirstItemWarnings + = responseExecutionHistoryFirstItem.getWarnings(); + Assertions.assertEquals(0, responseExecutionHistoryFirstItemWarnings.size()); + Assertions.assertEquals(11, responseExecutionHistoryFirstItem.getItemCount()); + Assertions.assertEquals(0, responseExecutionHistoryFirstItem.getFailedItemCount()); + // verify property "limits" + SearchIndexerLimits responseLimits = response.getLimits(); + Assertions.assertNotNull(responseLimits); + Assertions.assertNotNull(responseLimits.getMaxRunTime()); + Assertions.assertEquals(256000000L, responseLimits.getMaxDocumentExtractionSize()); + Assertions.assertEquals(4000000L, responseLimits.getMaxDocumentContentCharactersToExtract()); + } +} diff --git a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/generated/SearchServiceGetIndexerTests.java b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/generated/SearchServiceGetIndexerTests.java new file mode 100644 index 000000000000..75782b630f1e --- /dev/null +++ b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/generated/SearchServiceGetIndexerTests.java @@ -0,0 +1,91 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.search.documents.generated; + +import com.azure.search.documents.models.AzureActiveDirectoryApplicationCredentials; +import com.azure.search.documents.models.FieldMapping; +import com.azure.search.documents.models.FieldMappingFunction; +import com.azure.search.documents.models.IndexingParameters; +import com.azure.search.documents.models.IndexingParametersConfiguration; +import com.azure.search.documents.models.IndexingSchedule; +import com.azure.search.documents.models.SearchIndexer; +import com.azure.search.documents.models.SearchResourceEncryptionKey; +import java.util.List; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + +@Disabled +public final class SearchServiceGetIndexerTests extends SearchClientTestBase { + @Test + @Disabled + public void testSearchServiceGetIndexerTests() { + // method invocation + SearchIndexer response = indexersClient.get("myindexer"); + + // response assertion + Assertions.assertNotNull(response); + // verify property "name" + Assertions.assertEquals("myindexer", response.getName()); + // verify property "description" + Assertions.assertEquals("Description of the indexer", response.getDescription()); + // verify property "dataSourceName" + Assertions.assertEquals("mydocdbdatasource", response.getDataSourceName()); + // verify property "skillsetName" + Assertions.assertEquals("myskillset", response.getSkillsetName()); + // verify property "targetIndexName" + Assertions.assertEquals("preview-test", response.getTargetIndexName()); + // verify property "schedule" + IndexingSchedule responseSchedule = response.getSchedule(); + Assertions.assertNotNull(responseSchedule); + Assertions.assertNotNull(responseSchedule.getInterval()); + Assertions.assertNotNull(responseSchedule.getStartTime()); + // verify property "parameters" + IndexingParameters responseParameters = response.getParameters(); + Assertions.assertNotNull(responseParameters); + Assertions.assertEquals(10, responseParameters.getBatchSize()); + Assertions.assertEquals(10, responseParameters.getMaxFailedItems()); + Assertions.assertEquals(5, responseParameters.getMaxFailedItemsPerBatch()); + IndexingParametersConfiguration responseParametersConfiguration = responseParameters.getConfiguration(); + Assertions.assertNotNull(responseParametersConfiguration); + // verify property "fieldMappings" + List responseFieldMappings = response.getFieldMappings(); + FieldMapping responseFieldMappingsFirstItem = responseFieldMappings.iterator().next(); + Assertions.assertNotNull(responseFieldMappingsFirstItem); + Assertions.assertEquals("/document", responseFieldMappingsFirstItem.getSourceFieldName()); + Assertions.assertEquals("name", responseFieldMappingsFirstItem.getTargetFieldName()); + FieldMappingFunction responseFieldMappingsFirstItemMappingFunction + = responseFieldMappingsFirstItem.getMappingFunction(); + Assertions.assertNotNull(responseFieldMappingsFirstItemMappingFunction); + Assertions.assertEquals("base64Encode", responseFieldMappingsFirstItemMappingFunction.getName()); + // verify property "outputFieldMappings" + List responseOutputFieldMappings = response.getOutputFieldMappings(); + FieldMapping responseOutputFieldMappingsFirstItem = responseOutputFieldMappings.iterator().next(); + Assertions.assertNotNull(responseOutputFieldMappingsFirstItem); + Assertions.assertEquals("/document", responseOutputFieldMappingsFirstItem.getSourceFieldName()); + Assertions.assertEquals("name", responseOutputFieldMappingsFirstItem.getTargetFieldName()); + FieldMappingFunction responseOutputFieldMappingsFirstItemMappingFunction + = responseOutputFieldMappingsFirstItem.getMappingFunction(); + Assertions.assertNotNull(responseOutputFieldMappingsFirstItemMappingFunction); + Assertions.assertEquals("base64Encode", responseOutputFieldMappingsFirstItemMappingFunction.getName()); + // verify property "isDisabled" + Assertions.assertEquals(false, response.isDisabled()); + // verify property "eTag" + Assertions.assertEquals("0x1234568AE7E58A1", response.getETag()); + // verify property "encryptionKey" + SearchResourceEncryptionKey responseEncryptionKey = response.getEncryptionKey(); + Assertions.assertNotNull(responseEncryptionKey); + Assertions.assertEquals("myUserManagedEncryptionKey-createdinAzureKeyVault", + responseEncryptionKey.getKeyName()); + Assertions.assertEquals("myKeyVersion-32charAlphaNumericString", responseEncryptionKey.getKeyVersion()); + Assertions.assertEquals("https://myKeyVault.vault.azure.net", responseEncryptionKey.getVaultUri()); + AzureActiveDirectoryApplicationCredentials responseEncryptionKeyAccessCredentials + = responseEncryptionKey.getAccessCredentials(); + Assertions.assertNotNull(responseEncryptionKeyAccessCredentials); + Assertions.assertEquals("00000000-0000-0000-0000-000000000000", + responseEncryptionKeyAccessCredentials.getApplicationId()); + Assertions.assertEquals("", responseEncryptionKeyAccessCredentials.getApplicationSecret()); + } +} diff --git a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/generated/SearchServiceGetServiceStatisticsTests.java b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/generated/SearchServiceGetServiceStatisticsTests.java new file mode 100644 index 000000000000..5642d346e92c --- /dev/null +++ b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/generated/SearchServiceGetServiceStatisticsTests.java @@ -0,0 +1,25 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.search.documents.generated; + +import com.azure.core.http.rest.RequestOptions; +import com.azure.core.http.rest.Response; +import com.azure.core.util.BinaryData; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + +public final class SearchServiceGetServiceStatisticsTests extends SearchClientTestBase { + @Test + @Disabled + public void testSearchServiceGetServiceStatisticsTests() { + RequestOptions requestOptions = new RequestOptions(); + Response response = dataSourcesClient.getServiceStatisticsWithResponse(requestOptions); + Assertions.assertEquals(200, response.getStatusCode()); + Assertions.assertEquals(BinaryData.fromString( + "{\"counters\":{\"documentCount\":{\"usage\":12},\"indexesCount\":{\"usage\":2,\"quota\":2},\"indexersCount\":{\"usage\":2,\"quota\":2},\"dataSourcesCount\":{\"usage\":2,\"quota\":2},\"storageSize\":{\"usage\":123456,\"quota\":10485760},\"synonymMaps\":{\"usage\":3,\"quota\":3},\"skillsetCount\":{\"usage\":2,\"quota\":2},\"aliasesCount\":{\"usage\":4,\"quota\":4},\"vectorIndexSize\":{\"usage\":123456}},\"limits\":{\"maxStoragePerIndex\":10485760,\"maxFieldsPerIndex\":1000,\"maxFieldNestingDepthPerIndex\":10,\"maxComplexCollectionFieldsPerIndex\":40,\"maxComplexObjectsInCollectionsPerDocument\":3000}}") + .toObject(Object.class), response.getValue().toObject(Object.class)); + } +} diff --git a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/generated/SearchServiceGetSkillsetTests.java b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/generated/SearchServiceGetSkillsetTests.java new file mode 100644 index 000000000000..b112c38252af --- /dev/null +++ b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/generated/SearchServiceGetSkillsetTests.java @@ -0,0 +1,70 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.search.documents.generated; + +import com.azure.search.documents.models.AzureActiveDirectoryApplicationCredentials; +import com.azure.search.documents.models.InputFieldMappingEntry; +import com.azure.search.documents.models.OutputFieldMappingEntry; +import com.azure.search.documents.models.SearchIndexerSkill; +import com.azure.search.documents.models.SearchIndexerSkillset; +import com.azure.search.documents.models.SearchResourceEncryptionKey; +import java.util.List; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + +@Disabled +public final class SearchServiceGetSkillsetTests extends SearchClientTestBase { + @Test + @Disabled + public void testSearchServiceGetSkillsetTests() { + // method invocation + SearchIndexerSkillset response = skillsetsClient.get("myskillset"); + + // response assertion + Assertions.assertNotNull(response); + // verify property "name" + Assertions.assertEquals("myskillset", response.getName()); + // verify property "description" + Assertions.assertEquals("Skillset for extracting entities and more", response.getDescription()); + // verify property "skills" + List responseSkills = response.getSkills(); + SearchIndexerSkill responseSkillsFirstItem = responseSkills.iterator().next(); + Assertions.assertNotNull(responseSkillsFirstItem); + Assertions.assertEquals("#Microsoft.Skills.Text.LanguageDetectionSkill", + responseSkillsFirstItem.getOdataType()); + Assertions.assertEquals("skill2", responseSkillsFirstItem.getName()); + Assertions.assertEquals("/document", responseSkillsFirstItem.getContext()); + List responseSkillsFirstItemInputs = responseSkillsFirstItem.getInputs(); + InputFieldMappingEntry responseSkillsFirstItemInputsFirstItem = responseSkillsFirstItemInputs.iterator().next(); + Assertions.assertNotNull(responseSkillsFirstItemInputsFirstItem); + Assertions.assertEquals("text", responseSkillsFirstItemInputsFirstItem.getName()); + Assertions.assertEquals("/document/content", responseSkillsFirstItemInputsFirstItem.getSource()); + List responseSkillsFirstItemInputsFirstItemInputs + = responseSkillsFirstItemInputsFirstItem.getInputs(); + Assertions.assertEquals(0, responseSkillsFirstItemInputsFirstItemInputs.size()); + List responseSkillsFirstItemOutputs = responseSkillsFirstItem.getOutputs(); + OutputFieldMappingEntry responseSkillsFirstItemOutputsFirstItem + = responseSkillsFirstItemOutputs.iterator().next(); + Assertions.assertNotNull(responseSkillsFirstItemOutputsFirstItem); + Assertions.assertEquals("languageCode", responseSkillsFirstItemOutputsFirstItem.getName()); + Assertions.assertEquals("languageCode", responseSkillsFirstItemOutputsFirstItem.getTargetName()); + // verify property "eTag" + Assertions.assertEquals("0x1234568AE7E58A1", response.getETag()); + // verify property "encryptionKey" + SearchResourceEncryptionKey responseEncryptionKey = response.getEncryptionKey(); + Assertions.assertNotNull(responseEncryptionKey); + Assertions.assertEquals("myUserManagedEncryptionKey-createdinAzureKeyVault", + responseEncryptionKey.getKeyName()); + Assertions.assertEquals("myKeyVersion-32charAlphaNumericString", responseEncryptionKey.getKeyVersion()); + Assertions.assertEquals("https://myKeyVault.vault.azure.net", responseEncryptionKey.getVaultUri()); + AzureActiveDirectoryApplicationCredentials responseEncryptionKeyAccessCredentials + = responseEncryptionKey.getAccessCredentials(); + Assertions.assertNotNull(responseEncryptionKeyAccessCredentials); + Assertions.assertEquals("00000000-0000-0000-0000-000000000000", + responseEncryptionKeyAccessCredentials.getApplicationId()); + Assertions.assertEquals("", responseEncryptionKeyAccessCredentials.getApplicationSecret()); + } +} diff --git a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/generated/SearchServiceGetSynonymMapTests.java b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/generated/SearchServiceGetSynonymMapTests.java new file mode 100644 index 000000000000..e06af3769204 --- /dev/null +++ b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/generated/SearchServiceGetSynonymMapTests.java @@ -0,0 +1,47 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.search.documents.generated; + +import com.azure.search.documents.models.AzureActiveDirectoryApplicationCredentials; +import com.azure.search.documents.models.SearchResourceEncryptionKey; +import com.azure.search.documents.models.SynonymMap; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + +@Disabled +public final class SearchServiceGetSynonymMapTests extends SearchClientTestBase { + @Test + @Disabled + public void testSearchServiceGetSynonymMapTests() { + // method invocation + SynonymMap response = synonymMapsClient.get("mysynonymmap"); + + // response assertion + Assertions.assertNotNull(response); + // verify property "name" + Assertions.assertEquals("mysynonymmap", response.getName()); + // verify property "format" + Assertions.assertEquals("solr", response.getFormat()); + // verify property "synonyms" + Assertions.assertEquals("United States, United States of America, USA\nWashington, Wash. => WA", + response.getSynonyms()); + // verify property "encryptionKey" + SearchResourceEncryptionKey responseEncryptionKey = response.getEncryptionKey(); + Assertions.assertNotNull(responseEncryptionKey); + Assertions.assertEquals("myUserManagedEncryptionKey-createdinAzureKeyVault", + responseEncryptionKey.getKeyName()); + Assertions.assertEquals("myKeyVersion-32charAlphaNumericString", responseEncryptionKey.getKeyVersion()); + Assertions.assertEquals("https://myKeyVault.vault.azure.net", responseEncryptionKey.getVaultUri()); + AzureActiveDirectoryApplicationCredentials responseEncryptionKeyAccessCredentials + = responseEncryptionKey.getAccessCredentials(); + Assertions.assertNotNull(responseEncryptionKeyAccessCredentials); + Assertions.assertEquals("00000000-0000-0000-0000-000000000000", + responseEncryptionKeyAccessCredentials.getApplicationId()); + Assertions.assertEquals("", responseEncryptionKeyAccessCredentials.getApplicationSecret()); + // verify property "eTag" + Assertions.assertEquals("0x1234568AE7E58A1", response.getETag()); + } +} diff --git a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/generated/SearchServiceIndexAnalyzeTests.java b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/generated/SearchServiceIndexAnalyzeTests.java new file mode 100644 index 000000000000..eb4c9a5796b4 --- /dev/null +++ b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/generated/SearchServiceIndexAnalyzeTests.java @@ -0,0 +1,36 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.search.documents.generated; + +import com.azure.search.documents.models.AnalyzeRequest; +import com.azure.search.documents.models.AnalyzeResult; +import com.azure.search.documents.models.AnalyzedTokenInfo; +import com.azure.search.documents.models.LexicalAnalyzerName; +import java.util.List; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + +@Disabled +public final class SearchServiceIndexAnalyzeTests extends SearchClientTestBase { + @Test + @Disabled + public void testSearchServiceIndexAnalyzeTests() { + // method invocation + AnalyzeResult response = indexesClient.analyze("preview-test", + new AnalyzeRequest("Text to analyze").setAnalyzer(LexicalAnalyzerName.AR_LUCENE)); + + // response assertion + Assertions.assertNotNull(response); + // verify property "tokens" + List responseTokens = response.getTokens(); + AnalyzedTokenInfo responseTokensFirstItem = responseTokens.iterator().next(); + Assertions.assertNotNull(responseTokensFirstItem); + Assertions.assertEquals("text", responseTokensFirstItem.getToken()); + Assertions.assertEquals(0, responseTokensFirstItem.getStartOffset()); + Assertions.assertEquals(4, responseTokensFirstItem.getEndOffset()); + Assertions.assertEquals(0, responseTokensFirstItem.getPosition()); + } +} diff --git a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/generated/SearchServiceListAliasesTests.java b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/generated/SearchServiceListAliasesTests.java new file mode 100644 index 000000000000..b6cb855f323e --- /dev/null +++ b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/generated/SearchServiceListAliasesTests.java @@ -0,0 +1,32 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.search.documents.generated; + +import com.azure.core.http.rest.PagedIterable; +import com.azure.search.documents.models.SearchAlias; +import java.util.List; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + +@Disabled +public final class SearchServiceListAliasesTests extends SearchClientTestBase { + @Test + @Disabled + public void testSearchServiceListAliasesTests() { + // method invocation + PagedIterable response = aliasesClient.list(); + + // response assertion + Assertions.assertEquals(200, response.iterableByPage().iterator().next().getStatusCode()); + SearchAlias firstItem = response.iterator().next(); + Assertions.assertNotNull(firstItem); + // verify property "name" + Assertions.assertEquals("myalias", firstItem.getName()); + // verify property "indexes" + List firstItemIndexes = firstItem.getIndexes(); + Assertions.assertEquals("preview-test", firstItemIndexes.iterator().next()); + } +} diff --git a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/generated/SearchServiceListDataSourcesTests.java b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/generated/SearchServiceListDataSourcesTests.java new file mode 100644 index 000000000000..d4ddac92ad94 --- /dev/null +++ b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/generated/SearchServiceListDataSourcesTests.java @@ -0,0 +1,75 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.search.documents.generated; + +import com.azure.search.documents.models.AzureActiveDirectoryApplicationCredentials; +import com.azure.search.documents.models.DataChangeDetectionPolicy; +import com.azure.search.documents.models.DataDeletionDetectionPolicy; +import com.azure.search.documents.models.DataSourceCredentials; +import com.azure.search.documents.models.ListDataSourcesResult; +import com.azure.search.documents.models.SearchIndexerDataContainer; +import com.azure.search.documents.models.SearchIndexerDataSource; +import com.azure.search.documents.models.SearchIndexerDataSourceType; +import com.azure.search.documents.models.SearchResourceEncryptionKey; +import java.util.List; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + +@Disabled +public final class SearchServiceListDataSourcesTests extends SearchClientTestBase { + @Test + @Disabled + public void testSearchServiceListDataSourcesTests() { + // method invocation + ListDataSourcesResult response = dataSourcesClient.list(null); + + // response assertion + Assertions.assertNotNull(response); + // verify property "dataSources" + List responseDataSources = response.getDataSources(); + SearchIndexerDataSource responseDataSourcesFirstItem = responseDataSources.iterator().next(); + Assertions.assertNotNull(responseDataSourcesFirstItem); + Assertions.assertEquals("mydocdbdatasource", responseDataSourcesFirstItem.getName()); + Assertions.assertEquals("My Azure Blob data source.", responseDataSourcesFirstItem.getDescription()); + Assertions.assertEquals(SearchIndexerDataSourceType.AZURE_BLOB, responseDataSourcesFirstItem.getType()); + DataSourceCredentials responseDataSourcesFirstItemCredentials = responseDataSourcesFirstItem.getCredentials(); + Assertions.assertNotNull(responseDataSourcesFirstItemCredentials); + Assertions.assertEquals( + "DefaultEndpointsProtocol=https;AccountName=myAccountName;AccountKey=myAccountKey;EndpointSuffix=core.windows.net ", + responseDataSourcesFirstItemCredentials.getConnectionString()); + SearchIndexerDataContainer responseDataSourcesFirstItemContainer = responseDataSourcesFirstItem.getContainer(); + Assertions.assertNotNull(responseDataSourcesFirstItemContainer); + Assertions.assertEquals("doc-extraction-skillset", responseDataSourcesFirstItemContainer.getName()); + Assertions.assertEquals("E2E_Dsat", responseDataSourcesFirstItemContainer.getQuery()); + DataChangeDetectionPolicy responseDataSourcesFirstItemDataChangeDetectionPolicy + = responseDataSourcesFirstItem.getDataChangeDetectionPolicy(); + Assertions.assertNotNull(responseDataSourcesFirstItemDataChangeDetectionPolicy); + Assertions.assertEquals("#Microsoft.Azure.Search.HighWaterMarkChangeDetectionPolicy", + responseDataSourcesFirstItemDataChangeDetectionPolicy.getOdataType()); + DataDeletionDetectionPolicy responseDataSourcesFirstItemDataDeletionDetectionPolicy + = responseDataSourcesFirstItem.getDataDeletionDetectionPolicy(); + Assertions.assertNotNull(responseDataSourcesFirstItemDataDeletionDetectionPolicy); + Assertions.assertEquals("#Microsoft.Azure.Search.SoftDeleteColumnDeletionDetectionPolicy", + responseDataSourcesFirstItemDataDeletionDetectionPolicy.getOdataType()); + Assertions.assertEquals("0x1234568AE7E58A1", responseDataSourcesFirstItem.getETag()); + SearchResourceEncryptionKey responseDataSourcesFirstItemEncryptionKey + = responseDataSourcesFirstItem.getEncryptionKey(); + Assertions.assertNotNull(responseDataSourcesFirstItemEncryptionKey); + Assertions.assertEquals("myUserManagedEncryptionKey-createdinAzureKeyVault", + responseDataSourcesFirstItemEncryptionKey.getKeyName()); + Assertions.assertEquals("myKeyVersion-32charAlphaNumericString", + responseDataSourcesFirstItemEncryptionKey.getKeyVersion()); + Assertions.assertEquals("https://myKeyVault.vault.azure.net", + responseDataSourcesFirstItemEncryptionKey.getVaultUri()); + AzureActiveDirectoryApplicationCredentials responseDataSourcesFirstItemEncryptionKeyAccessCredentials + = responseDataSourcesFirstItemEncryptionKey.getAccessCredentials(); + Assertions.assertNotNull(responseDataSourcesFirstItemEncryptionKeyAccessCredentials); + Assertions.assertEquals("00000000-0000-0000-0000-000000000000", + responseDataSourcesFirstItemEncryptionKeyAccessCredentials.getApplicationId()); + Assertions.assertEquals("", + responseDataSourcesFirstItemEncryptionKeyAccessCredentials.getApplicationSecret()); + } +} diff --git a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/generated/SearchServiceListIndexersTests.java b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/generated/SearchServiceListIndexersTests.java new file mode 100644 index 000000000000..729e34a615ca --- /dev/null +++ b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/generated/SearchServiceListIndexersTests.java @@ -0,0 +1,94 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.search.documents.generated; + +import com.azure.search.documents.models.AzureActiveDirectoryApplicationCredentials; +import com.azure.search.documents.models.FieldMapping; +import com.azure.search.documents.models.FieldMappingFunction; +import com.azure.search.documents.models.IndexingParameters; +import com.azure.search.documents.models.IndexingParametersConfiguration; +import com.azure.search.documents.models.IndexingSchedule; +import com.azure.search.documents.models.ListIndexersResult; +import com.azure.search.documents.models.SearchIndexer; +import com.azure.search.documents.models.SearchResourceEncryptionKey; +import java.util.List; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + +@Disabled +public final class SearchServiceListIndexersTests extends SearchClientTestBase { + @Test + @Disabled + public void testSearchServiceListIndexersTests() { + // method invocation + ListIndexersResult response = indexersClient.list("*"); + + // response assertion + Assertions.assertNotNull(response); + // verify property "indexers" + List responseIndexers = response.getIndexers(); + SearchIndexer responseIndexersFirstItem = responseIndexers.iterator().next(); + Assertions.assertNotNull(responseIndexersFirstItem); + Assertions.assertEquals("myindexer", responseIndexersFirstItem.getName()); + Assertions.assertEquals("Description of the indexer", responseIndexersFirstItem.getDescription()); + Assertions.assertEquals("mydocdbdatasource", responseIndexersFirstItem.getDataSourceName()); + Assertions.assertEquals("myskillset", responseIndexersFirstItem.getSkillsetName()); + Assertions.assertEquals("preview-test", responseIndexersFirstItem.getTargetIndexName()); + IndexingSchedule responseIndexersFirstItemSchedule = responseIndexersFirstItem.getSchedule(); + Assertions.assertNotNull(responseIndexersFirstItemSchedule); + Assertions.assertNotNull(responseIndexersFirstItemSchedule.getInterval()); + Assertions.assertNotNull(responseIndexersFirstItemSchedule.getStartTime()); + IndexingParameters responseIndexersFirstItemParameters = responseIndexersFirstItem.getParameters(); + Assertions.assertNotNull(responseIndexersFirstItemParameters); + Assertions.assertEquals(10, responseIndexersFirstItemParameters.getBatchSize()); + Assertions.assertEquals(10, responseIndexersFirstItemParameters.getMaxFailedItems()); + Assertions.assertEquals(5, responseIndexersFirstItemParameters.getMaxFailedItemsPerBatch()); + IndexingParametersConfiguration responseIndexersFirstItemParametersConfiguration + = responseIndexersFirstItemParameters.getConfiguration(); + Assertions.assertNotNull(responseIndexersFirstItemParametersConfiguration); + List responseIndexersFirstItemFieldMappings = responseIndexersFirstItem.getFieldMappings(); + FieldMapping responseIndexersFirstItemFieldMappingsFirstItem + = responseIndexersFirstItemFieldMappings.iterator().next(); + Assertions.assertNotNull(responseIndexersFirstItemFieldMappingsFirstItem); + Assertions.assertEquals("/document", responseIndexersFirstItemFieldMappingsFirstItem.getSourceFieldName()); + Assertions.assertEquals("name", responseIndexersFirstItemFieldMappingsFirstItem.getTargetFieldName()); + FieldMappingFunction responseIndexersFirstItemFieldMappingsFirstItemMappingFunction + = responseIndexersFirstItemFieldMappingsFirstItem.getMappingFunction(); + Assertions.assertNotNull(responseIndexersFirstItemFieldMappingsFirstItemMappingFunction); + Assertions.assertEquals("base64Encode", + responseIndexersFirstItemFieldMappingsFirstItemMappingFunction.getName()); + List responseIndexersFirstItemOutputFieldMappings + = responseIndexersFirstItem.getOutputFieldMappings(); + FieldMapping responseIndexersFirstItemOutputFieldMappingsFirstItem + = responseIndexersFirstItemOutputFieldMappings.iterator().next(); + Assertions.assertNotNull(responseIndexersFirstItemOutputFieldMappingsFirstItem); + Assertions.assertEquals("/document", + responseIndexersFirstItemOutputFieldMappingsFirstItem.getSourceFieldName()); + Assertions.assertEquals("name", responseIndexersFirstItemOutputFieldMappingsFirstItem.getTargetFieldName()); + FieldMappingFunction responseIndexersFirstItemOutputFieldMappingsFirstItemMappingFunction + = responseIndexersFirstItemOutputFieldMappingsFirstItem.getMappingFunction(); + Assertions.assertNotNull(responseIndexersFirstItemOutputFieldMappingsFirstItemMappingFunction); + Assertions.assertEquals("base64Encode", + responseIndexersFirstItemOutputFieldMappingsFirstItemMappingFunction.getName()); + Assertions.assertEquals(false, responseIndexersFirstItem.isDisabled()); + SearchResourceEncryptionKey responseIndexersFirstItemEncryptionKey + = responseIndexersFirstItem.getEncryptionKey(); + Assertions.assertNotNull(responseIndexersFirstItemEncryptionKey); + Assertions.assertEquals("myUserManagedEncryptionKey-createdinAzureKeyVault", + responseIndexersFirstItemEncryptionKey.getKeyName()); + Assertions.assertEquals("myKeyVersion-32charAlphaNumericString", + responseIndexersFirstItemEncryptionKey.getKeyVersion()); + Assertions.assertEquals("https://myKeyVault.vault.azure.net", + responseIndexersFirstItemEncryptionKey.getVaultUri()); + AzureActiveDirectoryApplicationCredentials responseIndexersFirstItemEncryptionKeyAccessCredentials + = responseIndexersFirstItemEncryptionKey.getAccessCredentials(); + Assertions.assertNotNull(responseIndexersFirstItemEncryptionKeyAccessCredentials); + Assertions.assertEquals("00000000-0000-0000-0000-000000000000", + responseIndexersFirstItemEncryptionKeyAccessCredentials.getApplicationId()); + Assertions.assertEquals("", + responseIndexersFirstItemEncryptionKeyAccessCredentials.getApplicationSecret()); + } +} diff --git a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/generated/SearchServiceListIndexesTests.java b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/generated/SearchServiceListIndexesTests.java new file mode 100644 index 000000000000..ef7a3565e327 --- /dev/null +++ b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/generated/SearchServiceListIndexesTests.java @@ -0,0 +1,222 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.search.documents.generated; + +import com.azure.core.http.rest.PagedIterable; +import com.azure.search.documents.models.CharFilter; +import com.azure.search.documents.models.CorsOptions; +import com.azure.search.documents.models.LexicalAnalyzer; +import com.azure.search.documents.models.LexicalNormalizer; +import com.azure.search.documents.models.LexicalTokenizer; +import com.azure.search.documents.models.RescoringOptions; +import com.azure.search.documents.models.ScoringFunction; +import com.azure.search.documents.models.ScoringFunctionAggregation; +import com.azure.search.documents.models.ScoringFunctionInterpolation; +import com.azure.search.documents.models.ScoringProfile; +import com.azure.search.documents.models.SearchField; +import com.azure.search.documents.models.SearchFieldDataType; +import com.azure.search.documents.models.SearchIndex; +import com.azure.search.documents.models.SearchSuggester; +import com.azure.search.documents.models.SemanticConfiguration; +import com.azure.search.documents.models.SemanticField; +import com.azure.search.documents.models.SemanticPrioritizedFields; +import com.azure.search.documents.models.SemanticSearch; +import com.azure.search.documents.models.SimilarityAlgorithm; +import com.azure.search.documents.models.TextWeights; +import com.azure.search.documents.models.TokenFilter; +import com.azure.search.documents.models.VectorSearch; +import com.azure.search.documents.models.VectorSearchAlgorithmConfiguration; +import com.azure.search.documents.models.VectorSearchAlgorithmKind; +import com.azure.search.documents.models.VectorSearchCompression; +import com.azure.search.documents.models.VectorSearchCompressionKind; +import com.azure.search.documents.models.VectorSearchCompressionRescoreStorageMethod; +import com.azure.search.documents.models.VectorSearchProfile; +import com.azure.search.documents.models.VectorSearchVectorizer; +import com.azure.search.documents.models.VectorSearchVectorizerKind; +import java.util.List; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + +@Disabled +public final class SearchServiceListIndexesTests extends SearchClientTestBase { + @Test + @Disabled + public void testSearchServiceListIndexesTests() { + // method invocation + PagedIterable response = indexesClient.list(null); + + // response assertion + Assertions.assertEquals(200, response.iterableByPage().iterator().next().getStatusCode()); + SearchIndex firstItem = response.iterator().next(); + Assertions.assertNotNull(firstItem); + // verify property "name" + Assertions.assertEquals("preview-test", firstItem.getName()); + // verify property "fields" + List firstItemFields = firstItem.getFields(); + SearchField firstItemFieldsFirstItem = firstItemFields.iterator().next(); + Assertions.assertNotNull(firstItemFieldsFirstItem); + Assertions.assertEquals("id", firstItemFieldsFirstItem.getName()); + Assertions.assertEquals(SearchFieldDataType.STRING, firstItemFieldsFirstItem.getType()); + Assertions.assertEquals(true, firstItemFieldsFirstItem.isKey()); + Assertions.assertEquals(true, firstItemFieldsFirstItem.isRetrievable()); + Assertions.assertEquals(true, firstItemFieldsFirstItem.isStored()); + Assertions.assertEquals(true, firstItemFieldsFirstItem.isSearchable()); + Assertions.assertEquals(true, firstItemFieldsFirstItem.isFilterable()); + Assertions.assertEquals(true, firstItemFieldsFirstItem.isSortable()); + Assertions.assertEquals(true, firstItemFieldsFirstItem.isFacetable()); + List firstItemFieldsFirstItemSynonymMaps = firstItemFieldsFirstItem.getSynonymMaps(); + Assertions.assertEquals(0, firstItemFieldsFirstItemSynonymMaps.size()); + // verify property "scoringProfiles" + List firstItemScoringProfiles = firstItem.getScoringProfiles(); + ScoringProfile firstItemScoringProfilesFirstItem = firstItemScoringProfiles.iterator().next(); + Assertions.assertNotNull(firstItemScoringProfilesFirstItem); + Assertions.assertEquals("stringFieldBoost", firstItemScoringProfilesFirstItem.getName()); + TextWeights firstItemScoringProfilesFirstItemTextWeights = firstItemScoringProfilesFirstItem.getTextWeights(); + Assertions.assertNotNull(firstItemScoringProfilesFirstItemTextWeights); + Assertions.assertNotNull(firstItemScoringProfilesFirstItemTextWeights.getWeights()); + List firstItemScoringProfilesFirstItemFunctions + = firstItemScoringProfilesFirstItem.getFunctions(); + ScoringFunction firstItemScoringProfilesFirstItemFunctionsFirstItem + = firstItemScoringProfilesFirstItemFunctions.iterator().next(); + Assertions.assertNotNull(firstItemScoringProfilesFirstItemFunctionsFirstItem); + Assertions.assertEquals("tag", firstItemScoringProfilesFirstItemFunctionsFirstItem.getType()); + Assertions.assertEquals("category", firstItemScoringProfilesFirstItemFunctionsFirstItem.getFieldName()); + Assertions.assertEquals(2.0, firstItemScoringProfilesFirstItemFunctionsFirstItem.getBoost()); + Assertions.assertEquals(ScoringFunctionInterpolation.LINEAR, + firstItemScoringProfilesFirstItemFunctionsFirstItem.getInterpolation()); + Assertions.assertEquals(ScoringFunctionAggregation.SUM, + firstItemScoringProfilesFirstItem.getFunctionAggregation()); + // verify property "defaultScoringProfile" + Assertions.assertEquals("stringFieldBoost", firstItem.getDefaultScoringProfile()); + // verify property "corsOptions" + CorsOptions firstItemCorsOptions = firstItem.getCorsOptions(); + Assertions.assertNotNull(firstItemCorsOptions); + List firstItemCorsOptionsAllowedOrigins = firstItemCorsOptions.getAllowedOrigins(); + Assertions.assertEquals("https://www.example.com/foo", firstItemCorsOptionsAllowedOrigins.iterator().next()); + Assertions.assertEquals(10L, firstItemCorsOptions.getMaxAgeInSeconds()); + // verify property "suggesters" + List firstItemSuggesters = firstItem.getSuggesters(); + SearchSuggester firstItemSuggestersFirstItem = firstItemSuggesters.iterator().next(); + Assertions.assertNotNull(firstItemSuggestersFirstItem); + Assertions.assertEquals("sg", firstItemSuggestersFirstItem.getName()); + Assertions.assertEquals("analyzingInfixMatching", firstItemSuggestersFirstItem.getSearchMode()); + List firstItemSuggestersFirstItemSourceFields = firstItemSuggestersFirstItem.getSourceFields(); + Assertions.assertEquals("category", firstItemSuggestersFirstItemSourceFields.iterator().next()); + // verify property "analyzers" + List firstItemAnalyzers = firstItem.getAnalyzers(); + LexicalAnalyzer firstItemAnalyzersFirstItem = firstItemAnalyzers.iterator().next(); + Assertions.assertNotNull(firstItemAnalyzersFirstItem); + Assertions.assertEquals("#Microsoft.Azure.Search.CustomAnalyzer", firstItemAnalyzersFirstItem.getOdataType()); + Assertions.assertEquals("tagsAnalyzer", firstItemAnalyzersFirstItem.getName()); + // verify property "tokenizers" + List firstItemTokenizers = firstItem.getTokenizers(); + LexicalTokenizer firstItemTokenizersFirstItem = firstItemTokenizers.iterator().next(); + Assertions.assertNotNull(firstItemTokenizersFirstItem); + Assertions.assertEquals("#Microsoft.Azure.Search.StandardTokenizerV2", + firstItemTokenizersFirstItem.getOdataType()); + Assertions.assertEquals("my_tokenizer", firstItemTokenizersFirstItem.getName()); + // verify property "tokenFilters" + List firstItemTokenFilters = firstItem.getTokenFilters(); + TokenFilter firstItemTokenFiltersFirstItem = firstItemTokenFilters.iterator().next(); + Assertions.assertNotNull(firstItemTokenFiltersFirstItem); + Assertions.assertEquals("#Microsoft.Azure.Search.AsciiFoldingTokenFilter", + firstItemTokenFiltersFirstItem.getOdataType()); + Assertions.assertEquals("my_tokenFilter", firstItemTokenFiltersFirstItem.getName()); + // verify property "charFilters" + List firstItemCharFilters = firstItem.getCharFilters(); + CharFilter firstItemCharFiltersFirstItem = firstItemCharFilters.iterator().next(); + Assertions.assertNotNull(firstItemCharFiltersFirstItem); + Assertions.assertEquals("#Microsoft.Azure.Search.MappingCharFilter", + firstItemCharFiltersFirstItem.getOdataType()); + Assertions.assertEquals("my_mapping", firstItemCharFiltersFirstItem.getName()); + // verify property "normalizers" + List firstItemNormalizers = firstItem.getNormalizers(); + LexicalNormalizer firstItemNormalizersFirstItem = firstItemNormalizers.iterator().next(); + Assertions.assertNotNull(firstItemNormalizersFirstItem); + Assertions.assertEquals("#Microsoft.Azure.Search.CustomNormalizer", + firstItemNormalizersFirstItem.getOdataType()); + Assertions.assertEquals("my_normalizer", firstItemNormalizersFirstItem.getName()); + // verify property "similarity" + SimilarityAlgorithm firstItemSimilarity = firstItem.getSimilarity(); + Assertions.assertNotNull(firstItemSimilarity); + Assertions.assertEquals("#Microsoft.Azure.Search.BM25Similarity", firstItemSimilarity.getOdataType()); + // verify property "semanticSearch" + SemanticSearch firstItemSemanticSearch = firstItem.getSemanticSearch(); + Assertions.assertNotNull(firstItemSemanticSearch); + Assertions.assertEquals("testconfig", firstItemSemanticSearch.getDefaultConfigurationName()); + List firstItemSemanticSearchConfigurations = firstItemSemanticSearch.getConfigurations(); + SemanticConfiguration firstItemSemanticSearchConfigurationsFirstItem + = firstItemSemanticSearchConfigurations.iterator().next(); + Assertions.assertNotNull(firstItemSemanticSearchConfigurationsFirstItem); + Assertions.assertEquals("testconfig", firstItemSemanticSearchConfigurationsFirstItem.getName()); + SemanticPrioritizedFields firstItemSemanticSearchConfigurationsFirstItemPrioritizedFields + = firstItemSemanticSearchConfigurationsFirstItem.getPrioritizedFields(); + Assertions.assertNotNull(firstItemSemanticSearchConfigurationsFirstItemPrioritizedFields); + SemanticField firstItemSemanticSearchConfigurationsFirstItemPrioritizedFieldsTitleField + = firstItemSemanticSearchConfigurationsFirstItemPrioritizedFields.getTitleField(); + Assertions.assertNotNull(firstItemSemanticSearchConfigurationsFirstItemPrioritizedFieldsTitleField); + Assertions.assertEquals("category", + firstItemSemanticSearchConfigurationsFirstItemPrioritizedFieldsTitleField.getFieldName()); + List firstItemSemanticSearchConfigurationsFirstItemPrioritizedFieldsContentFields + = firstItemSemanticSearchConfigurationsFirstItemPrioritizedFields.getContentFields(); + SemanticField firstItemSemanticSearchConfigurationsFirstItemPrioritizedFieldsContentFieldsFirstItem + = firstItemSemanticSearchConfigurationsFirstItemPrioritizedFieldsContentFields.iterator().next(); + Assertions.assertNotNull(firstItemSemanticSearchConfigurationsFirstItemPrioritizedFieldsContentFieldsFirstItem); + Assertions.assertEquals("description", + firstItemSemanticSearchConfigurationsFirstItemPrioritizedFieldsContentFieldsFirstItem.getFieldName()); + List firstItemSemanticSearchConfigurationsFirstItemPrioritizedFieldsKeywordsFields + = firstItemSemanticSearchConfigurationsFirstItemPrioritizedFields.getKeywordsFields(); + SemanticField firstItemSemanticSearchConfigurationsFirstItemPrioritizedFieldsKeywordsFieldsFirstItem + = firstItemSemanticSearchConfigurationsFirstItemPrioritizedFieldsKeywordsFields.iterator().next(); + Assertions + .assertNotNull(firstItemSemanticSearchConfigurationsFirstItemPrioritizedFieldsKeywordsFieldsFirstItem); + Assertions.assertEquals("ownerId", + firstItemSemanticSearchConfigurationsFirstItemPrioritizedFieldsKeywordsFieldsFirstItem.getFieldName()); + Assertions.assertEquals(false, firstItemSemanticSearchConfigurationsFirstItem.isFlightingOptIn()); + // verify property "vectorSearch" + VectorSearch firstItemVectorSearch = firstItem.getVectorSearch(); + Assertions.assertNotNull(firstItemVectorSearch); + List firstItemVectorSearchProfiles = firstItemVectorSearch.getProfiles(); + VectorSearchProfile firstItemVectorSearchProfilesFirstItem = firstItemVectorSearchProfiles.iterator().next(); + Assertions.assertNotNull(firstItemVectorSearchProfilesFirstItem); + Assertions.assertEquals("config1", firstItemVectorSearchProfilesFirstItem.getName()); + Assertions.assertEquals("cosine", firstItemVectorSearchProfilesFirstItem.getAlgorithmConfigurationName()); + Assertions.assertEquals("openai", firstItemVectorSearchProfilesFirstItem.getVectorizerName()); + Assertions.assertEquals("mySQ8", firstItemVectorSearchProfilesFirstItem.getCompressionName()); + List firstItemVectorSearchAlgorithms + = firstItemVectorSearch.getAlgorithms(); + VectorSearchAlgorithmConfiguration firstItemVectorSearchAlgorithmsFirstItem + = firstItemVectorSearchAlgorithms.iterator().next(); + Assertions.assertNotNull(firstItemVectorSearchAlgorithmsFirstItem); + Assertions.assertEquals(VectorSearchAlgorithmKind.HNSW, firstItemVectorSearchAlgorithmsFirstItem.getKind()); + Assertions.assertEquals("cosine", firstItemVectorSearchAlgorithmsFirstItem.getName()); + List firstItemVectorSearchVectorizers = firstItemVectorSearch.getVectorizers(); + VectorSearchVectorizer firstItemVectorSearchVectorizersFirstItem + = firstItemVectorSearchVectorizers.iterator().next(); + Assertions.assertNotNull(firstItemVectorSearchVectorizersFirstItem); + Assertions.assertEquals(VectorSearchVectorizerKind.AZURE_OPEN_AI, + firstItemVectorSearchVectorizersFirstItem.getKind()); + Assertions.assertEquals("openai", firstItemVectorSearchVectorizersFirstItem.getVectorizerName()); + List firstItemVectorSearchCompressions = firstItemVectorSearch.getCompressions(); + VectorSearchCompression firstItemVectorSearchCompressionsFirstItem + = firstItemVectorSearchCompressions.iterator().next(); + Assertions.assertNotNull(firstItemVectorSearchCompressionsFirstItem); + Assertions.assertEquals(VectorSearchCompressionKind.SCALAR_QUANTIZATION, + firstItemVectorSearchCompressionsFirstItem.getKind()); + Assertions.assertEquals("mySQ8", firstItemVectorSearchCompressionsFirstItem.getCompressionName()); + RescoringOptions firstItemVectorSearchCompressionsFirstItemRescoringOptions + = firstItemVectorSearchCompressionsFirstItem.getRescoringOptions(); + Assertions.assertNotNull(firstItemVectorSearchCompressionsFirstItemRescoringOptions); + Assertions.assertEquals(true, firstItemVectorSearchCompressionsFirstItemRescoringOptions.isEnableRescoring()); + Assertions.assertEquals(10.0D, + firstItemVectorSearchCompressionsFirstItemRescoringOptions.getDefaultOversampling()); + Assertions.assertEquals(VectorSearchCompressionRescoreStorageMethod.PRESERVE_ORIGINALS, + firstItemVectorSearchCompressionsFirstItemRescoringOptions.getRescoreStorageMethod()); + Assertions.assertEquals(2, firstItemVectorSearchCompressionsFirstItem.getTruncationDimension()); + // verify property "eTag" + Assertions.assertEquals("0x1234568AE7E58A1", firstItem.getETag()); + } +} diff --git a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/generated/SearchServiceListSkillsetsTests.java b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/generated/SearchServiceListSkillsetsTests.java new file mode 100644 index 000000000000..0c2663769638 --- /dev/null +++ b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/generated/SearchServiceListSkillsetsTests.java @@ -0,0 +1,81 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.search.documents.generated; + +import com.azure.search.documents.models.AzureActiveDirectoryApplicationCredentials; +import com.azure.search.documents.models.InputFieldMappingEntry; +import com.azure.search.documents.models.ListSkillsetsResult; +import com.azure.search.documents.models.OutputFieldMappingEntry; +import com.azure.search.documents.models.SearchIndexerSkill; +import com.azure.search.documents.models.SearchIndexerSkillset; +import com.azure.search.documents.models.SearchResourceEncryptionKey; +import java.util.List; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + +@Disabled +public final class SearchServiceListSkillsetsTests extends SearchClientTestBase { + @Test + @Disabled + public void testSearchServiceListSkillsetsTests() { + // method invocation + ListSkillsetsResult response = skillsetsClient.list(null); + + // response assertion + Assertions.assertNotNull(response); + // verify property "skillsets" + List responseSkillsets = response.getSkillsets(); + SearchIndexerSkillset responseSkillsetsFirstItem = responseSkillsets.iterator().next(); + Assertions.assertNotNull(responseSkillsetsFirstItem); + Assertions.assertEquals("myskillset", responseSkillsetsFirstItem.getName()); + Assertions.assertEquals("Skillset for extracting entities and more", + responseSkillsetsFirstItem.getDescription()); + List responseSkillsetsFirstItemSkills = responseSkillsetsFirstItem.getSkills(); + SearchIndexerSkill responseSkillsetsFirstItemSkillsFirstItem + = responseSkillsetsFirstItemSkills.iterator().next(); + Assertions.assertNotNull(responseSkillsetsFirstItemSkillsFirstItem); + Assertions.assertEquals("#Microsoft.Skills.Text.LanguageDetectionSkill", + responseSkillsetsFirstItemSkillsFirstItem.getOdataType()); + Assertions.assertEquals("skill2", responseSkillsetsFirstItemSkillsFirstItem.getName()); + Assertions.assertEquals("/document", responseSkillsetsFirstItemSkillsFirstItem.getContext()); + List responseSkillsetsFirstItemSkillsFirstItemInputs + = responseSkillsetsFirstItemSkillsFirstItem.getInputs(); + InputFieldMappingEntry responseSkillsetsFirstItemSkillsFirstItemInputsFirstItem + = responseSkillsetsFirstItemSkillsFirstItemInputs.iterator().next(); + Assertions.assertNotNull(responseSkillsetsFirstItemSkillsFirstItemInputsFirstItem); + Assertions.assertEquals("text", responseSkillsetsFirstItemSkillsFirstItemInputsFirstItem.getName()); + Assertions.assertEquals("/document/content", + responseSkillsetsFirstItemSkillsFirstItemInputsFirstItem.getSource()); + List responseSkillsetsFirstItemSkillsFirstItemInputsFirstItemInputs + = responseSkillsetsFirstItemSkillsFirstItemInputsFirstItem.getInputs(); + Assertions.assertEquals(0, responseSkillsetsFirstItemSkillsFirstItemInputsFirstItemInputs.size()); + List responseSkillsetsFirstItemSkillsFirstItemOutputs + = responseSkillsetsFirstItemSkillsFirstItem.getOutputs(); + OutputFieldMappingEntry responseSkillsetsFirstItemSkillsFirstItemOutputsFirstItem + = responseSkillsetsFirstItemSkillsFirstItemOutputs.iterator().next(); + Assertions.assertNotNull(responseSkillsetsFirstItemSkillsFirstItemOutputsFirstItem); + Assertions.assertEquals("languageCode", responseSkillsetsFirstItemSkillsFirstItemOutputsFirstItem.getName()); + Assertions.assertEquals("languageCode", + responseSkillsetsFirstItemSkillsFirstItemOutputsFirstItem.getTargetName()); + Assertions.assertEquals("0x1234568AE7E58A1", responseSkillsetsFirstItem.getETag()); + SearchResourceEncryptionKey responseSkillsetsFirstItemEncryptionKey + = responseSkillsetsFirstItem.getEncryptionKey(); + Assertions.assertNotNull(responseSkillsetsFirstItemEncryptionKey); + Assertions.assertEquals("myUserManagedEncryptionKey-createdinAzureKeyVault", + responseSkillsetsFirstItemEncryptionKey.getKeyName()); + Assertions.assertEquals("myKeyVersion-32charAlphaNumericString", + responseSkillsetsFirstItemEncryptionKey.getKeyVersion()); + Assertions.assertEquals("https://myKeyVault.vault.azure.net", + responseSkillsetsFirstItemEncryptionKey.getVaultUri()); + AzureActiveDirectoryApplicationCredentials responseSkillsetsFirstItemEncryptionKeyAccessCredentials + = responseSkillsetsFirstItemEncryptionKey.getAccessCredentials(); + Assertions.assertNotNull(responseSkillsetsFirstItemEncryptionKeyAccessCredentials); + Assertions.assertEquals("00000000-0000-0000-0000-000000000000", + responseSkillsetsFirstItemEncryptionKeyAccessCredentials.getApplicationId()); + Assertions.assertEquals("", + responseSkillsetsFirstItemEncryptionKeyAccessCredentials.getApplicationSecret()); + } +} diff --git a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/generated/SearchServiceListSynonymMapsTests.java b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/generated/SearchServiceListSynonymMapsTests.java new file mode 100644 index 000000000000..6014d8b2d882 --- /dev/null +++ b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/generated/SearchServiceListSynonymMapsTests.java @@ -0,0 +1,52 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.search.documents.generated; + +import com.azure.search.documents.models.AzureActiveDirectoryApplicationCredentials; +import com.azure.search.documents.models.ListSynonymMapsResult; +import com.azure.search.documents.models.SearchResourceEncryptionKey; +import com.azure.search.documents.models.SynonymMap; +import java.util.List; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + +@Disabled +public final class SearchServiceListSynonymMapsTests extends SearchClientTestBase { + @Test + @Disabled + public void testSearchServiceListSynonymMapsTests() { + // method invocation + ListSynonymMapsResult response = synonymMapsClient.list(null); + + // response assertion + Assertions.assertNotNull(response); + // verify property "synonymMaps" + List responseSynonymMaps = response.getSynonymMaps(); + SynonymMap responseSynonymMapsFirstItem = responseSynonymMaps.iterator().next(); + Assertions.assertNotNull(responseSynonymMapsFirstItem); + Assertions.assertEquals("mysynonymmap", responseSynonymMapsFirstItem.getName()); + Assertions.assertEquals("solr", responseSynonymMapsFirstItem.getFormat()); + Assertions.assertEquals("United States, United States of America, USA\nWashington, Wash. => WA", + responseSynonymMapsFirstItem.getSynonyms()); + SearchResourceEncryptionKey responseSynonymMapsFirstItemEncryptionKey + = responseSynonymMapsFirstItem.getEncryptionKey(); + Assertions.assertNotNull(responseSynonymMapsFirstItemEncryptionKey); + Assertions.assertEquals("myUserManagedEncryptionKey-createdinAzureKeyVault", + responseSynonymMapsFirstItemEncryptionKey.getKeyName()); + Assertions.assertEquals("myKeyVersion-32charAlphaNumericString", + responseSynonymMapsFirstItemEncryptionKey.getKeyVersion()); + Assertions.assertEquals("https://myKeyVault.vault.azure.net", + responseSynonymMapsFirstItemEncryptionKey.getVaultUri()); + AzureActiveDirectoryApplicationCredentials responseSynonymMapsFirstItemEncryptionKeyAccessCredentials + = responseSynonymMapsFirstItemEncryptionKey.getAccessCredentials(); + Assertions.assertNotNull(responseSynonymMapsFirstItemEncryptionKeyAccessCredentials); + Assertions.assertEquals("00000000-0000-0000-0000-000000000000", + responseSynonymMapsFirstItemEncryptionKeyAccessCredentials.getApplicationId()); + Assertions.assertEquals("", + responseSynonymMapsFirstItemEncryptionKeyAccessCredentials.getApplicationSecret()); + Assertions.assertEquals("0x1234568AE7E58A1", responseSynonymMapsFirstItem.getETag()); + } +} diff --git a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/generated/SearchServiceResetDocsTests.java b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/generated/SearchServiceResetDocsTests.java new file mode 100644 index 000000000000..4d4581fb7b28 --- /dev/null +++ b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/generated/SearchServiceResetDocsTests.java @@ -0,0 +1,21 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.search.documents.generated; + +import com.azure.search.documents.models.DocumentKeysOrIds; +import java.util.Arrays; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + +@Disabled +public final class SearchServiceResetDocsTests extends SearchClientTestBase { + @Test + @Disabled + public void testSearchServiceResetDocsTests() { + // method invocation + indexersClient.resetDocs("myindexer", true, + new DocumentKeysOrIds().setDocumentKeys(Arrays.asList("1", "2", "3"))); + } +} diff --git a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/generated/SearchServiceResetIndexerTests.java b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/generated/SearchServiceResetIndexerTests.java new file mode 100644 index 000000000000..22ee18e8d601 --- /dev/null +++ b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/generated/SearchServiceResetIndexerTests.java @@ -0,0 +1,18 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.search.documents.generated; + +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + +@Disabled +public final class SearchServiceResetIndexerTests extends SearchClientTestBase { + @Test + @Disabled + public void testSearchServiceResetIndexerTests() { + // method invocation + indexersClient.reset("myindexer"); + } +} diff --git a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/generated/SearchServiceResetSkillsTests.java b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/generated/SearchServiceResetSkillsTests.java new file mode 100644 index 000000000000..96d646bb4e40 --- /dev/null +++ b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/generated/SearchServiceResetSkillsTests.java @@ -0,0 +1,21 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.search.documents.generated; + +import com.azure.search.documents.models.SkillNames; +import java.util.Arrays; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + +@Disabled +public final class SearchServiceResetSkillsTests extends SearchClientTestBase { + @Test + @Disabled + public void testSearchServiceResetSkillsTests() { + // method invocation + skillsetsClient.resetSkills("myskillset", + new SkillNames().setSkillNames(Arrays.asList("skill2", "skill3", "skill4"))); + } +} diff --git a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/generated/SearchServiceRunIndexerTests.java b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/generated/SearchServiceRunIndexerTests.java new file mode 100644 index 000000000000..c9da883e5008 --- /dev/null +++ b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/generated/SearchServiceRunIndexerTests.java @@ -0,0 +1,18 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.search.documents.generated; + +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + +@Disabled +public final class SearchServiceRunIndexerTests extends SearchClientTestBase { + @Test + @Disabled + public void testSearchServiceRunIndexerTests() { + // method invocation + indexersClient.run("myindexer"); + } +} diff --git a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/implementation/models/IndexActionTests.java b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/implementation/models/IndexActionTests.java deleted file mode 100644 index daaf16361351..000000000000 --- a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/implementation/models/IndexActionTests.java +++ /dev/null @@ -1,121 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.search.documents.implementation.models; - -import com.azure.core.serializer.json.jackson.JacksonJsonSerializerBuilder; -import com.azure.core.util.serializer.ObjectSerializer; -import com.azure.json.JsonProviders; -import com.azure.json.JsonSerializable; -import com.azure.json.JsonWriter; -import com.azure.search.documents.implementation.converters.IndexActionConverter; -import com.azure.search.documents.models.IndexActionType; -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.databind.ObjectMapper; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.parallel.Execution; -import org.junit.jupiter.api.parallel.ExecutionMode; - -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.nio.charset.StandardCharsets; -import java.util.Collections; -import java.util.Map; - -import static org.junit.jupiter.api.Assertions.assertEquals; - -/** - * Tests {@link IndexAction}. - */ -@Execution(ExecutionMode.CONCURRENT) -public class IndexActionTests { - @Test - public void nullIsIncludedInMapSerialization() { - ObjectSerializer nullIncludingSerializer = new JacksonJsonSerializerBuilder() - .serializer(new ObjectMapper().setSerializationInclusion(JsonInclude.Include.ALWAYS)) - .build(); - - com.azure.search.documents.models.IndexAction> action - = new com.azure.search.documents.models.IndexAction>() - .setActionType(IndexActionType.MERGE) - .setDocument(Collections.singletonMap("null", null)); - - String json = convertToJson(IndexActionConverter.map(action, nullIncludingSerializer)); - - assertEquals("{\"@search.action\":\"merge\",\"null\":null}", json); - } - - @Test - public void nullIsIncludedInTypedSerialization() { - ObjectSerializer nullIncludingSerializer = new JacksonJsonSerializerBuilder() - .serializer(new ObjectMapper().setSerializationInclusion(JsonInclude.Include.ALWAYS)) - .build(); - - com.azure.search.documents.models.IndexAction action - = new com.azure.search.documents.models.IndexAction() - .setActionType(IndexActionType.MERGE) - .setDocument(new ClassWithNullableField()); - - String json = convertToJson(IndexActionConverter.map(action, nullIncludingSerializer)); - - assertEquals("{\"@search.action\":\"merge\",\"null\":null}", json); - } - - @Test - public void nullIsExcludedInMapSerialization() { - ObjectSerializer nullExcludingSerializer = new JacksonJsonSerializerBuilder() - .serializer(new ObjectMapper().setSerializationInclusion(JsonInclude.Include.NON_NULL)) - .build(); - - com.azure.search.documents.models.IndexAction> action - = new com.azure.search.documents.models.IndexAction>() - .setActionType(IndexActionType.MERGE) - .setDocument(Collections.singletonMap("null", null)); - - String json = convertToJson(IndexActionConverter.map(action, nullExcludingSerializer)); - - assertEquals("{\"@search.action\":\"merge\"}", json); - } - - @Test - public void nullIsExcludedInTypedSerialization() { - ObjectSerializer nullExcludingSerializer = new JacksonJsonSerializerBuilder() - .serializer(new ObjectMapper().setSerializationInclusion(JsonInclude.Include.NON_NULL)) - .build(); - - com.azure.search.documents.models.IndexAction action - = new com.azure.search.documents.models.IndexAction() - .setActionType(IndexActionType.MERGE) - .setDocument(new ClassWithNullableField()); - - String json = convertToJson(IndexActionConverter.map(action, nullExcludingSerializer)); - - assertEquals("{\"@search.action\":\"merge\"}", json); - } - - private static String convertToJson(JsonSerializable jsonSerializable) { - ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); - - try (JsonWriter writer = JsonProviders.createWriter(outputStream)) { - writer.writeJson(jsonSerializable).flush(); - return outputStream.toString(StandardCharsets.UTF_8.name()); - } catch (IOException ex) { - throw new RuntimeException(ex); - } - } - - public static final class ClassWithNullableField { - @JsonProperty("null") - private String nullable; - - public String getNullable() { - return nullable; - } - - public ClassWithNullableField setNullable(String nullable) { - this.nullable = nullable; - return this; - } - } -} diff --git a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/indexes/CustomAnalyzerTests.java b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/indexes/CustomAnalyzerTests.java deleted file mode 100644 index 46b3483a666e..000000000000 --- a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/indexes/CustomAnalyzerTests.java +++ /dev/null @@ -1,939 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -package com.azure.search.documents.indexes; - -import com.azure.core.http.rest.PagedIterable; -import com.azure.core.util.Context; -import com.azure.core.util.CoreUtils; -import com.azure.core.util.ExpandableStringEnum; -import com.azure.search.documents.SearchAsyncClient; -import com.azure.search.documents.SearchClient; -import com.azure.search.documents.SearchDocument; -import com.azure.search.documents.SearchTestBase; -import com.azure.search.documents.indexes.models.AnalyzeTextOptions; -import com.azure.search.documents.indexes.models.AnalyzedTokenInfo; -import com.azure.search.documents.indexes.models.AsciiFoldingTokenFilter; -import com.azure.search.documents.indexes.models.CharFilter; -import com.azure.search.documents.indexes.models.CharFilterName; -import com.azure.search.documents.indexes.models.CjkBigramTokenFilter; -import com.azure.search.documents.indexes.models.CjkBigramTokenFilterScripts; -import com.azure.search.documents.indexes.models.ClassicTokenizer; -import com.azure.search.documents.indexes.models.CommonGramTokenFilter; -import com.azure.search.documents.indexes.models.CustomAnalyzer; -import com.azure.search.documents.indexes.models.DictionaryDecompounderTokenFilter; -import com.azure.search.documents.indexes.models.EdgeNGramTokenFilter; -import com.azure.search.documents.indexes.models.EdgeNGramTokenFilterSide; -import com.azure.search.documents.indexes.models.EdgeNGramTokenizer; -import com.azure.search.documents.indexes.models.ElisionTokenFilter; -import com.azure.search.documents.indexes.models.KeepTokenFilter; -import com.azure.search.documents.indexes.models.KeywordMarkerTokenFilter; -import com.azure.search.documents.indexes.models.KeywordTokenizer; -import com.azure.search.documents.indexes.models.LengthTokenFilter; -import com.azure.search.documents.indexes.models.LexicalAnalyzer; -import com.azure.search.documents.indexes.models.LexicalAnalyzerName; -import com.azure.search.documents.indexes.models.LexicalTokenizer; -import com.azure.search.documents.indexes.models.LexicalTokenizerName; -import com.azure.search.documents.indexes.models.LimitTokenFilter; -import com.azure.search.documents.indexes.models.LuceneStandardAnalyzer; -import com.azure.search.documents.indexes.models.LuceneStandardTokenizer; -import com.azure.search.documents.indexes.models.MappingCharFilter; -import com.azure.search.documents.indexes.models.MicrosoftLanguageStemmingTokenizer; -import com.azure.search.documents.indexes.models.MicrosoftLanguageTokenizer; -import com.azure.search.documents.indexes.models.MicrosoftStemmingTokenizerLanguage; -import com.azure.search.documents.indexes.models.MicrosoftTokenizerLanguage; -import com.azure.search.documents.indexes.models.NGramTokenFilter; -import com.azure.search.documents.indexes.models.NGramTokenizer; -import com.azure.search.documents.indexes.models.PathHierarchyTokenizer; -import com.azure.search.documents.indexes.models.PatternAnalyzer; -import com.azure.search.documents.indexes.models.PatternCaptureTokenFilter; -import com.azure.search.documents.indexes.models.PatternReplaceCharFilter; -import com.azure.search.documents.indexes.models.PatternReplaceTokenFilter; -import com.azure.search.documents.indexes.models.PatternTokenizer; -import com.azure.search.documents.indexes.models.PhoneticEncoder; -import com.azure.search.documents.indexes.models.PhoneticTokenFilter; -import com.azure.search.documents.indexes.models.RegexFlags; -import com.azure.search.documents.indexes.models.SearchField; -import com.azure.search.documents.indexes.models.SearchFieldDataType; -import com.azure.search.documents.indexes.models.SearchIndex; -import com.azure.search.documents.indexes.models.ShingleTokenFilter; -import com.azure.search.documents.indexes.models.SnowballTokenFilter; -import com.azure.search.documents.indexes.models.SnowballTokenFilterLanguage; -import com.azure.search.documents.indexes.models.StemmerOverrideTokenFilter; -import com.azure.search.documents.indexes.models.StemmerTokenFilter; -import com.azure.search.documents.indexes.models.StemmerTokenFilterLanguage; -import com.azure.search.documents.indexes.models.StopAnalyzer; -import com.azure.search.documents.indexes.models.StopwordsList; -import com.azure.search.documents.indexes.models.StopwordsTokenFilter; -import com.azure.search.documents.indexes.models.SynonymTokenFilter; -import com.azure.search.documents.indexes.models.TokenCharacterKind; -import com.azure.search.documents.indexes.models.TokenFilter; -import com.azure.search.documents.indexes.models.TokenFilterName; -import com.azure.search.documents.indexes.models.TruncateTokenFilter; -import com.azure.search.documents.indexes.models.UaxUrlEmailTokenizer; -import com.azure.search.documents.indexes.models.UniqueTokenFilter; -import com.azure.search.documents.indexes.models.WordDelimiterTokenFilter; -import com.azure.search.documents.models.SearchOptions; -import com.azure.search.documents.models.SearchResult; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.parallel.Execution; -import org.junit.jupiter.api.parallel.ExecutionMode; -import reactor.core.publisher.Flux; -import reactor.core.scheduler.Schedulers; -import reactor.test.StepVerifier; - -import java.lang.reflect.Field; -import java.net.HttpURLConnection; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.Comparator; -import java.util.Iterator; -import java.util.List; -import java.util.function.Function; -import java.util.stream.Collectors; - -import static com.azure.search.documents.TestHelpers.assertHttpResponseException; -import static com.azure.search.documents.TestHelpers.assertObjectEquals; -import static com.azure.search.documents.TestHelpers.verifyHttpResponseError; -import static com.azure.search.documents.TestHelpers.waitForIndexing; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; - -@Execution(ExecutionMode.CONCURRENT) -public class CustomAnalyzerTests extends SearchTestBase { - private static final String NAME_PREFIX = "azsmnet"; - - private static final List TOKEN_FILTER_NAMES = getExpandableEnumValues(TokenFilterName.class); - private static final List CHAR_FILTER_NAMES = getExpandableEnumValues(CharFilterName.class); - private static final List LEXICAL_ANALYZER_NAMES - = getExpandableEnumValues(LexicalAnalyzerName.class); - private static final List LEXICAL_TOKENIZER_NAMES - = getExpandableEnumValues(LexicalTokenizerName.class); - private static final List REGEX_FLAGS = getExpandableEnumValues(RegexFlags.class); - - private SearchIndexAsyncClient searchIndexAsyncClient; - private SearchIndexClient searchIndexClient; - private final List indexesToCleanup = new ArrayList<>(); - - @Override - protected void beforeTest() { - super.beforeTest(); - searchIndexAsyncClient = getSearchIndexClientBuilder(false).buildAsyncClient(); - searchIndexClient = getSearchIndexClientBuilder(true).buildClient(); - } - - @Override - protected void afterTest() { - super.afterTest(); - for (String index : indexesToCleanup) { - searchIndexClient.deleteIndex(index); - } - } - - @Test - public void canSearchWithCustomAnalyzerSyncAndAsync() { - SearchClient searchClient = setupSearchIndexForCustomAnalyzerSearch(searchIndexClient::getSearchClient); - SearchAsyncClient searchAsyncClient = searchIndexAsyncClient.getSearchAsyncClient(searchClient.getIndexName()); - - Iterator iterator - = searchClient.search("someone@somewhere.something", new SearchOptions(), Context.NONE).iterator(); - - assertEquals("1", iterator.next().getDocument(SearchDocument.class).get("id")); - assertFalse(iterator.hasNext()); - - StepVerifier.create(searchAsyncClient.search("someone@somewhere.something", new SearchOptions())) - .assertNext(searchResult -> assertEquals("1", searchResult.getDocument(SearchDocument.class).get("id"))) - .verifyComplete(); - } - - private T setupSearchIndexForCustomAnalyzerSearch(Function clientCreator) { - final LexicalAnalyzerName customLexicalAnalyzerName = LexicalAnalyzerName.fromString("my_email_analyzer"); - final CharFilterName customCharFilterName = CharFilterName.fromString("my_email_filter"); - - SearchIndex index = new SearchIndex(randomIndexName("testindex")) - .setFields(new SearchField("id", SearchFieldDataType.STRING).setKey(true), - new SearchField("message", SearchFieldDataType.STRING).setAnalyzerName(customLexicalAnalyzerName) - .setSearchable(true)) - .setAnalyzers(new CustomAnalyzer(customLexicalAnalyzerName.toString(), LexicalTokenizerName.STANDARD) - .setCharFilters(customCharFilterName)) - .setCharFilters(new PatternReplaceCharFilter(customCharFilterName.toString(), "@", "_")); - - searchIndexClient.createIndex(index); - indexesToCleanup.add(index.getName()); - SearchClient searchClient = searchIndexClient.getSearchClient(index.getName()); - - SearchDocument document1 = new SearchDocument(); - document1.put("id", "1"); - document1.put("message", "My email is someone@somewhere.something."); - SearchDocument document2 = new SearchDocument(); - document2.put("id", "2"); - document2.put("message", "His email is someone@nowhere.nothing."); - - List documents = Arrays.asList(document1, document2); - - searchClient.uploadDocuments(documents); - waitForIndexing(); - - return clientCreator.apply(index.getName()); - } - - @Test - public void canUseAllAnalyzerNamesInIndexDefinitionSync() { - SearchIndex index = prepareIndexWithAllLexicalAnalyzerNames(); - indexesToCleanup.add(index.getName()); - SearchIndex res = searchIndexClient.createIndex(index); - - assertObjectEquals(index, res, true, "etag"); - } - - @Test - public void canUseAllAnalyzerNamesInIndexDefinitionAsync() { - SearchIndex index = prepareIndexWithAllLexicalAnalyzerNames(); - indexesToCleanup.add(index.getName()); - - StepVerifier.create(searchIndexAsyncClient.createIndex(index)) - .assertNext(result -> assertObjectEquals(index, result, true, "etag")) - .verifyComplete(); - } - - @Test - public void canAnalyzeSyncAndAsync() { - SearchIndex index = createTestIndex(null); - searchIndexClient.createIndex(index); - indexesToCleanup.add(index.getName()); - - AnalyzeTextOptions request = new AnalyzeTextOptions("One two", LexicalAnalyzerName.WHITESPACE); - - // sync - PagedIterable results = searchIndexClient.analyzeText(index.getName(), request); - Iterator iterator = results.iterator(); - assertTokenInfoEqual("One", 0, 3, 0, iterator.next()); - assertTokenInfoEqual("two", 4, 7, 1, iterator.next()); - assertFalse(iterator.hasNext()); - - // async - StepVerifier.create(searchIndexAsyncClient.analyzeText(index.getName(), request)) - .assertNext(analyzedTokenInfo -> assertTokenInfoEqual("One", 0, 3, 0, analyzedTokenInfo)) - .assertNext(analyzedTokenInfo -> assertTokenInfoEqual("two", 4, 7, 1, analyzedTokenInfo)) - .verifyComplete(); - - request = new AnalyzeTextOptions("One's ", LexicalTokenizerName.WHITESPACE) - .setTokenFilters(TokenFilterName.APOSTROPHE) - .setCharFilters(CharFilterName.HTML_STRIP); - - // sync - results = searchIndexClient.analyzeText(index.getName(), request); - // End offset is based on the original token, not the one emitted by the filters. - iterator = results.iterator(); - assertTokenInfoEqual("One", 0, 5, 0, iterator.next()); - assertFalse(iterator.hasNext()); - - // async - StepVerifier.create(searchIndexAsyncClient.analyzeText(index.getName(), request)) - .assertNext(analyzedTokenInfo -> assertTokenInfoEqual("One", 0, 5, 0, analyzedTokenInfo)) - .verifyComplete(); - } - - @Test - public void canAnalyzeWithAllPossibleNamesSyncAndAsync() { - SearchIndex index = createTestIndex(null); - searchIndexClient.createIndex(index); - indexesToCleanup.add(index.getName()); - - // Since the tests in this class are ran in parallel the lists could be modified while iterating over them. - List threadSafeLexicalAnalyzerNames = new ArrayList<>(LEXICAL_ANALYZER_NAMES); - List threadSafeLexicalTokenizerNames = new ArrayList<>(LEXICAL_TOKENIZER_NAMES); - - threadSafeLexicalAnalyzerNames.parallelStream() - .map(an -> new AnalyzeTextOptions("One two", an)) - .forEach(r -> searchIndexClient.analyzeText(index.getName(), r).forEach(ignored -> { - })); - - Flux.fromIterable(threadSafeLexicalAnalyzerNames) - .parallel() - .runOn(Schedulers.boundedElastic()) - .flatMap(an -> searchIndexAsyncClient.analyzeText(index.getName(), new AnalyzeTextOptions("One two", an))) - .then() - .block(); - - threadSafeLexicalTokenizerNames.parallelStream() - .map(tn -> new AnalyzeTextOptions("One two", tn)) - .forEach(r -> searchIndexClient.analyzeText(index.getName(), r).forEach(ignored -> { - })); - - Flux.fromIterable(threadSafeLexicalTokenizerNames) - .parallel() - .runOn(Schedulers.boundedElastic()) - .flatMap(tn -> searchIndexAsyncClient.analyzeText(index.getName(), new AnalyzeTextOptions("One two", tn))) - .then() - .block(); - } - - @Test - public void addingCustomAnalyzerThrowsHttpExceptionByDefaultSyncAndAsync() { - SearchIndex index = createTestIndex(null).setAnalyzers(new StopAnalyzer("a1")); - searchIndexClient.createIndex(index); - indexesToCleanup.add(index.getName()); - - addAnalyzerToIndex(index, new StopAnalyzer("a2")); - - assertHttpResponseException(() -> searchIndexClient.createOrUpdateIndex(index), - HttpURLConnection.HTTP_BAD_REQUEST, "Index update not allowed because it would cause downtime."); - - StepVerifier.create(searchIndexAsyncClient.createOrUpdateIndex(index)) - .verifyErrorSatisfies(exception -> verifyHttpResponseError(exception, HttpURLConnection.HTTP_BAD_REQUEST, - "Index update not allowed because it would cause downtime.")); - } - - @Test - public void canAddCustomAnalyzerWithIndexDowntimeSync() { - SearchIndex index = createTestIndex(null).setAnalyzers(new StopAnalyzer("a1")); - searchIndexClient.createIndex(index); - indexesToCleanup.add(index.getName()); - - addAnalyzerToIndex(index, new StopAnalyzer("a2")); - SearchIndex updatedIndex - = searchIndexClient.createOrUpdateIndexWithResponse(index, true, false, Context.NONE).getValue(); - - assertAnalysisComponentsEqual(index, updatedIndex); - } - - @Test - public void canAddCustomAnalyzerWithIndexDowntimeAsync() { - SearchIndex index = createTestIndex(null).setAnalyzers(new StopAnalyzer("a1")); - searchIndexClient.createIndex(index); - indexesToCleanup.add(index.getName()); - - addAnalyzerToIndex(index, new StopAnalyzer("a2")); - - StepVerifier.create(searchIndexAsyncClient.createOrUpdateIndexWithResponse(index, true, false)) - .assertNext(response -> assertAnalysisComponentsEqual(index, response.getValue())) - .verifyComplete(); - } - - @Test - public void canCreateAllAnalysisComponentsSync() { - SearchIndex index = prepareIndexWithAllAnalysisComponentTypes(); - createAndValidateIndexSync(searchIndexClient, index); - searchIndexClient.deleteIndex(index.getName()); - - // We have to split up analysis components into two indexes, one where any components with optional properties - // have defaults that are zero or null, and another where we need to specify the default values we - // expect to get back from the REST API. - SearchIndex indexWithSpecialDefaults = createIndexWithSpecialDefaults(); - SearchIndex expectedIndexWithSpecialDefaults = createExpectedIndexWithSpecialDefaults(indexWithSpecialDefaults); - - List splitIndexWithSpecialDefaults = splitIndex(indexWithSpecialDefaults); - List splitExpectedIndexWithSpecialDefaults = splitIndex(expectedIndexWithSpecialDefaults); - for (int j = 0; j < splitIndexWithSpecialDefaults.size(); j++) { - index = splitExpectedIndexWithSpecialDefaults.get(j); - createAndValidateIndexSync(searchIndexClient, index); - searchIndexClient.deleteIndex(index.getName()); - } - } - - @Test - public void canCreateAllAnalysisComponentsAsync() { - SearchIndex index = prepareIndexWithAllAnalysisComponentTypes(); - createAndValidateIndexAsync(searchIndexAsyncClient, index); - searchIndexClient.deleteIndex(index.getName()); - - // We have to split up analysis components into two indexes, one where any components with optional properties - // have defaults that are zero or null, and another where we need to specify the default values we - // expect to get back from the REST API. - SearchIndex indexWithSpecialDefaults = createIndexWithSpecialDefaults(); - SearchIndex expectedIndexWithSpecialDefaults = createExpectedIndexWithSpecialDefaults(indexWithSpecialDefaults); - - List splitIndexWithSpecialDefaults = splitIndex(indexWithSpecialDefaults); - List splitExpectedIndexWithSpecialDefaults = splitIndex(expectedIndexWithSpecialDefaults); - for (int j = 0; j < splitIndexWithSpecialDefaults.size(); j++) { - index = splitExpectedIndexWithSpecialDefaults.get(j); - createAndValidateIndexAsync(searchIndexAsyncClient, index); - searchIndexClient.deleteIndex(index.getName()); - } - } - - @Test - public void canUseAllAnalysisComponentNamesSync() { - SearchIndex index = prepareIndexWithAllAnalysisComponentNames(); - - SearchIndex createdIndex = searchIndexClient.createIndex(index); - indexesToCleanup.add(index.getName()); - assertCustomAnalysisComponentsEqual(index, createdIndex); - } - - @Test - public void canUseAllAnalysisComponentNamesAsync() { - SearchIndex index = prepareIndexWithAllAnalysisComponentNames(); - - StepVerifier.create(searchIndexAsyncClient.createIndex(index)).assertNext(createdIndex -> { - indexesToCleanup.add(index.getName()); - assertCustomAnalysisComponentsEqual(index, createdIndex); - }).verifyComplete(); - } - - @Test - public void canUsePatternAnalyzerInManyWaysSync() { - SearchIndex expectedIndex - = createTestIndex(null).setAnalyzers(new PatternAnalyzer(generateName()).setStopwords("stop1", "stop2") - .setLowerCaseTerms(true) - .setPattern(".*") - .setFlags(REGEX_FLAGS), new PatternAnalyzer(generateName()).setPattern("")); - - createAndValidateIndexSync(searchIndexClient, expectedIndex); - } - - @Test - public void canUsePatternAnalyzerInManyWaysAsync() { - SearchIndex expectedIndex - = createTestIndex(null).setAnalyzers(new PatternAnalyzer(generateName()).setStopwords("stop1", "stop2") - .setLowerCaseTerms(true) - .setPattern(".*") - .setFlags(REGEX_FLAGS), new PatternAnalyzer(generateName()).setPattern("")); - - createAndValidateIndexAsync(searchIndexAsyncClient, expectedIndex); - } - - @Test - public void canUseAllRegexFlagsEmptyFlagsAnalyzerSyncAndAsync() { - SearchIndex index = createTestIndex(null).setAnalyzers(new PatternAnalyzer(generateName()).setFlags()); - - assertHttpResponseException(() -> searchIndexClient.createIndex(index), HttpURLConnection.HTTP_BAD_REQUEST, - "Values of property \\\"flags\\\" must belong to the set of allowed values"); - - StepVerifier.create(searchIndexAsyncClient.createIndex(index)) - .verifyErrorSatisfies(exception -> verifyHttpResponseError(exception, HttpURLConnection.HTTP_BAD_REQUEST, - "Values of property \\\"flags\\\" must belong to the set of allowed values")); - } - - @Test - public void canUseAllRegexFlagsTokenizerSync() { - createAndValidateIndexSync(searchIndexClient, createTestIndex(null).setTokenizers( - new PatternTokenizer(generateName()).setPattern(".*").setFlags(REGEX_FLAGS).setGroup(0), - new PatternTokenizer(generateName()).setPattern(""), new PatternTokenizer(generateName()).setGroup(null))); - } - - @Test - public void canUseAllRegexFlagsTokenizerAsync() { - createAndValidateIndexAsync(searchIndexAsyncClient, createTestIndex(null).setTokenizers( - new PatternTokenizer(generateName()).setPattern(".*").setFlags(REGEX_FLAGS).setGroup(0), - new PatternTokenizer(generateName()).setPattern(""), new PatternTokenizer(generateName()).setGroup(null))); - } - - @Test - public void canUseAllRegexFlagsEmptyTokenizerSync() { - createAndValidateIndexSync(searchIndexClient, createTestIndex(null).setTokenizers(new ArrayList<>())); - } - - @Test - public void canUseAllRegexFlagsEmptyTokenizerAsync() { - createAndValidateIndexAsync(searchIndexAsyncClient, createTestIndex(null).setTokenizers(new ArrayList<>())); - } - - @Test - public void canUseAllRegexFlagsEmptyFlagsTokenizerSyncAndAsync() { - SearchIndex index = createTestIndex(null).setTokenizers(new PatternTokenizer(generateName()).setFlags()); - - assertHttpResponseException(() -> searchIndexClient.createIndex(index), HttpURLConnection.HTTP_BAD_REQUEST, - "Values of property \\\"flags\\\" must belong to the set of allowed values"); - - StepVerifier.create(searchIndexAsyncClient.createIndex(index)) - .verifyErrorSatisfies(exception -> verifyHttpResponseError(exception, HttpURLConnection.HTTP_BAD_REQUEST, - "Values of property \\\"flags\\\" must belong to the set of allowed values")); - } - - @Test - public void canUseAllAnalysisComponentOptionsSync() { - List indexes = prepareIndexesWithAllAnalysisComponentOptions(); - - indexes.forEach(expectedIndex -> { - createAndValidateIndexSync(searchIndexClient, expectedIndex); - searchIndexClient.deleteIndex(expectedIndex.getName()); - }); - } - - @Test - public void canUseAllAnalysisComponentOptionsAsync() { - List indexes = prepareIndexesWithAllAnalysisComponentOptions(); - - indexes.forEach(expectedIndex -> { - createAndValidateIndexAsync(searchIndexAsyncClient, expectedIndex); - searchIndexClient.deleteIndex(expectedIndex.getName()); - }); - } - - private void createAndValidateIndexSync(SearchIndexClient searchIndexClient, SearchIndex index) { - SearchIndex createdIndex = searchIndexClient.createIndex(index); - indexesToCleanup.add(index.getName()); - - assertAnalysisComponentsEqual(index, createdIndex); - } - - private void createAndValidateIndexAsync(SearchIndexAsyncClient searchIndexAsyncClient, SearchIndex index) { - StepVerifier.create(searchIndexAsyncClient.createIndex(index)).assertNext(createdIndex -> { - indexesToCleanup.add(index.getName()); - assertAnalysisComponentsEqual(index, createdIndex); - }).verifyComplete(); - } - - static void addAnalyzerToIndex(SearchIndex index, LexicalAnalyzer analyzer) { - List analyzers = new ArrayList<>(index.getAnalyzers()); - analyzers.add(analyzer); - - index.setAnalyzers(analyzers); - } - - static void assertAnalysisComponentsEqual(SearchIndex expected, SearchIndex actual) { - // Compare analysis components directly so that test failures show better comparisons. - // Analyzers - assertAnalyzersEqual(expected.getAnalyzers(), actual.getAnalyzers()); - - // LexicalTokenizer - assertLexicalTokenizersEqual(expected.getTokenizers(), actual.getTokenizers()); - - // Char filter - assertCharFiltersEqual(expected.getCharFilters(), actual.getCharFilters()); - } - - void assertCustomAnalysisComponentsEqual(SearchIndex expected, SearchIndex actual) { - // Compare analysis components directly so that test failures show better comparisons. - // Analyzers - Sort according to their LexicalTokenizers before comparing: - List expectedAnalyzers = expected.getAnalyzers(); - List actualAnalyzers = actual.getAnalyzers(); - - if (expectedAnalyzers != null && actualAnalyzers != null) { - Comparator customAnalyzerComparator - = Comparator.comparing((LexicalAnalyzer a) -> ((CustomAnalyzer) a).getTokenizer().toString()); - - expectedAnalyzers.sort(customAnalyzerComparator); - actualAnalyzers.sort(customAnalyzerComparator); - - assertAnalyzersEqual(expectedAnalyzers, actualAnalyzers); - } - - // LexicalTokenizer - assertLexicalTokenizersEqual(expected.getTokenizers(), actual.getTokenizers()); - - // Char filter - assertCharFiltersEqual(expected.getCharFilters(), actual.getCharFilters()); - } - - private static void assertAnalyzersEqual(List expected, List actual) { - if (expected != null && actual != null) { - assertEquals(expected.size(), actual.size()); - for (int i = 0; i < expected.size(); i++) { - assertObjectEquals(expected.get(i), actual.get(i), true, "name"); - } - } - } - - private static void assertLexicalTokenizersEqual(List expected, List actual) { - if (expected != null && actual != null) { - assertEquals(expected.size(), actual.size()); - for (int i = 0; i < expected.size(); i++) { - assertObjectEquals(expected.get(i), actual.get(i), true, "name"); - } - } - } - - private static void assertCharFiltersEqual(List expected, List actual) { - if (expected != null && actual != null) { - assertEquals(expected.size(), actual.size()); - for (int i = 0; i < expected.size(); i++) { - assertObjectEquals(expected.get(i), actual.get(i), true, "name"); - } - } - } - - String generateName() { - return testResourceNamer.randomName(NAME_PREFIX, 24); - } - - List prepareIndexesWithAllAnalysisComponentOptions() { - SearchIndex index = createTestIndex(null); - - // Set tokenizers - List tokenizers = new ArrayList<>(); - tokenizers.add(new EdgeNGramTokenizer(generateName()).setMinGram(1) - .setMaxGram(2) - .setTokenChars(TokenCharacterKind.values())); - Arrays.stream(MicrosoftStemmingTokenizerLanguage.values()) - .map(mtl -> new MicrosoftLanguageStemmingTokenizer(generateName()).setMaxTokenLength(200) - .setIsSearchTokenizerUsed(false) - .setLanguage(mtl)) - .forEach(tokenizers::add); - index.setTokenizers(tokenizers); - - // Set token filters - List tokenFilters = new ArrayList<>(); - tokenFilters.add(new CjkBigramTokenFilter(generateName()).setIgnoreScripts(CjkBigramTokenFilterScripts.values()) - .setOutputUnigrams(true)); - - Arrays.stream(EdgeNGramTokenFilterSide.values()) - .map(s -> new EdgeNGramTokenFilter(generateName()).setMinGram(1).setMaxGram(2).setSide(s)) - .forEach(tokenFilters::add); - - Arrays.stream(PhoneticEncoder.values()) - .map(pe -> new PhoneticTokenFilter(generateName()).setEncoder(pe).setOriginalTokensReplaced(false)) - .forEach(tokenFilters::add); - - Arrays.stream(SnowballTokenFilterLanguage.values()) - .map(l -> new SnowballTokenFilter(generateName(), l)) - .forEach(tokenFilters::add); - - Arrays.stream(StemmerTokenFilterLanguage.values()) - .map(l -> new StemmerTokenFilter(generateName(), l)) - .forEach(tokenFilters::add); - - Arrays.stream(StopwordsList.values()) - .map(l -> new StopwordsTokenFilter(generateName()).setStopwordsList(l) - .setCaseIgnored(false) - .setTrailingStopWordsRemoved(true)) - .forEach(tokenFilters::add); - - index.setTokenFilters(tokenFilters); - - return splitIndex(index); - } - - SearchIndex prepareIndexWithAllLexicalAnalyzerNames() { - List allLexicalAnalyzerNames = LEXICAL_ANALYZER_NAMES; - allLexicalAnalyzerNames.sort(Comparator.comparing(LexicalAnalyzerName::toString)); - - List fields = new ArrayList<>(); - int fieldNumber = 0; - - // All analyzer names can be set on the analyzer property. - for (int i = 0; i < allLexicalAnalyzerNames.size(); i++) { - SearchFieldDataType fieldType = (i % 2 == 0) - ? SearchFieldDataType.STRING - : SearchFieldDataType.collection(SearchFieldDataType.STRING); - fields.add( - new SearchField("field" + (fieldNumber++), fieldType).setAnalyzerName(allLexicalAnalyzerNames.get(i))); - } - - List searchAnalyzersAndIndexAnalyzers - = getAnalyzersAllowedForSearchAnalyzerAndIndexAnalyzer(); - - for (int i = 0; i < searchAnalyzersAndIndexAnalyzers.size(); i++) { - SearchFieldDataType fieldType = (i % 2 == 0) - ? SearchFieldDataType.STRING - : SearchFieldDataType.collection(SearchFieldDataType.STRING); - fields.add(new SearchField("field" + (fieldNumber++), fieldType).setSearchable(true) - .setSearchAnalyzerName(searchAnalyzersAndIndexAnalyzers.get(i)) - .setIndexAnalyzerName(searchAnalyzersAndIndexAnalyzers.get(i))); - } - - fields.add(new SearchField("id", SearchFieldDataType.STRING).setKey(true)); - - return new SearchIndex(randomIndexName("hotel")).setFields(fields); - } - - SearchIndex prepareIndexWithAllAnalysisComponentNames() { - List tokenFilters = new ArrayList<>(TOKEN_FILTER_NAMES); - tokenFilters.sort(Comparator.comparing(TokenFilterName::toString)); - - List charFilters = new ArrayList<>(CHAR_FILTER_NAMES); - charFilters.sort(Comparator.comparing(CharFilterName::toString)); - - LexicalAnalyzer analyzerWithAllTokenFilterAndCharFilters - = new CustomAnalyzer("abc", LexicalTokenizerName.LOWERCASE).setTokenFilters(tokenFilters) - .setCharFilters(charFilters); - - SearchIndex index = createTestIndex(null); - List analyzers = new ArrayList<>(); - analyzers.add(analyzerWithAllTokenFilterAndCharFilters); - String nameBase = generateName(); - - List analyzerNames = LEXICAL_TOKENIZER_NAMES; - analyzerNames.sort(Comparator.comparing(LexicalTokenizerName::toString)); - - analyzerNames.stream().map(tn -> new CustomAnalyzer(nameBase + tn, tn)).forEach(analyzers::add); - - analyzers.sort(Comparator.comparing(LexicalAnalyzer::getName)); - index.setAnalyzers(analyzers); - - return index; - } - - /** - * Custom analysis components (analyzer/tokenzier/tokenFilter/charFilter) count in index must be between 0 and 50. - * Split an Index into indexes, each of which has a total analysis components count within the limit. - */ - List splitIndex(SearchIndex index) { - List indices = new ArrayList<>(); - - for (List analyzerList : splitAnalysisComponents(index.getAnalyzers())) { - indices.add(createTestIndex(null).setAnalyzers(analyzerList)); - } - - for (List tokenizerList : splitAnalysisComponents(index.getTokenizers())) { - indices.add(createTestIndex(null).setTokenizers(tokenizerList)); - } - - for (List tokenFilterList : splitAnalysisComponents(index.getTokenFilters())) { - indices.add(createTestIndex(null).setTokenFilters(tokenFilterList)); - } - - for (List charFilterList : splitAnalysisComponents(index.getCharFilters())) { - indices.add(createTestIndex(null).setCharFilters(charFilterList)); - } - - return indices; - } - - /** - * Custom analysis components (analyzer/tokenzier/tokenFilter/charFilter) count in index must be between 0 and 50. - * Split a list of analysis components into lists within the limit. - */ - private List> splitAnalysisComponents(List list) { - final int analysisComponentLimit = 50; - List> lists = new ArrayList<>(); - - if (CoreUtils.isNullOrEmpty(list)) { - return lists; - } - - if (list.size() > analysisComponentLimit) { - int subLists = list.size() / analysisComponentLimit; - int remainder = list.size() % analysisComponentLimit; - - for (int i = 0; i < subLists; i++) { - lists.add(new ArrayList<>(list.subList(i * analysisComponentLimit, (i + 1) * analysisComponentLimit))); - } - - if (remainder > 0) { - lists.add(new ArrayList<>(list.subList(subLists * analysisComponentLimit, list.size()))); - } - } else { - lists.add(list); - } - - return lists; - } - - SearchIndex prepareIndexWithAllAnalysisComponentTypes() { - final LexicalTokenizerName customTokenizerName = LexicalTokenizerName.fromString("my_tokenizer"); - final TokenFilterName customTokenFilterName = TokenFilterName.fromString("my_tokenfilter"); - final CharFilterName customCharFilterName = CharFilterName.fromString("my_charfilter"); - - return createTestIndex(null) - .setAnalyzers( - new CustomAnalyzer(generateName(), customTokenizerName).setTokenFilters(customTokenFilterName) - .setCharFilters(customCharFilterName), - new CustomAnalyzer(generateName(), LexicalTokenizerName.EDGE_NGRAM), - new PatternAnalyzer(generateName()).setLowerCaseTerms(false) - .setPattern("abc") - .setFlags(RegexFlags.DOT_ALL) - .setStopwords("the"), - new LuceneStandardAnalyzer(generateName()).setMaxTokenLength(100).setStopwords("the"), - new StopAnalyzer(generateName()).setStopwords("the"), new StopAnalyzer(generateName())) - .setTokenizers(new EdgeNGramTokenizer(customTokenizerName.toString()).setMinGram(1).setMaxGram(2), - new EdgeNGramTokenizer(generateName()).setMinGram(2) - .setMaxGram(4) - .setTokenChars(TokenCharacterKind.LETTER), - new NGramTokenizer(generateName()).setMinGram(2).setMaxGram(4).setTokenChars(TokenCharacterKind.LETTER), - new ClassicTokenizer(generateName()).setMaxTokenLength(100), - new KeywordTokenizer(generateName()).setMaxTokenLength(100), - new MicrosoftLanguageStemmingTokenizer(generateName()).setMaxTokenLength(100) - .setIsSearchTokenizerUsed(true) - .setLanguage(MicrosoftStemmingTokenizerLanguage.CROATIAN), - new MicrosoftLanguageTokenizer(generateName()).setMaxTokenLength(100) - .setIsSearchTokenizer(true) - .setLanguage(MicrosoftTokenizerLanguage.THAI), - new PathHierarchyTokenizer(generateName()).setDelimiter(':') - .setReplacement('_') - .setMaxTokenLength(300) - .setTokenOrderReversed(true) - .setNumberOfTokensToSkip(2), - new PatternTokenizer(generateName()).setPattern(".*").setFlags(RegexFlags.MULTILINE).setGroup(0), - new LuceneStandardTokenizer(generateName()).setMaxTokenLength(100), - new UaxUrlEmailTokenizer(generateName()).setMaxTokenLength(100)) - .setTokenFilters(new CjkBigramTokenFilter(customTokenFilterName.toString()), // One custom token filter for CustomAnalyzer above. - new CjkBigramTokenFilter(generateName()).setIgnoreScripts(CjkBigramTokenFilterScripts.HAN) - .setOutputUnigrams(true), - new CjkBigramTokenFilter(generateName()), - new AsciiFoldingTokenFilter(generateName()).setPreserveOriginal(true), - new AsciiFoldingTokenFilter(generateName()), - new CommonGramTokenFilter(generateName(), Arrays.asList("hello", "goodbye")).setCaseIgnored(true) - .setQueryModeUsed(true), - new CommonGramTokenFilter(generateName(), Collections.singletonList("at")), - new DictionaryDecompounderTokenFilter(generateName(), Collections.singletonList("Schadenfreude")) - .setMinWordSize(10) - .setMinSubwordSize(5) - .setMaxSubwordSize(13) - .setOnlyLongestMatched(true), - new EdgeNGramTokenFilter(generateName()).setMinGram(2) - .setMaxGram(10) - .setSide(EdgeNGramTokenFilterSide.BACK), - new ElisionTokenFilter(generateName()).setArticles("a"), new ElisionTokenFilter(generateName()), - new KeepTokenFilter(generateName(), Collections.singletonList("aloha")), - new KeepTokenFilter(generateName(), Arrays.asList("e", "komo", "mai")), - new KeywordMarkerTokenFilter(generateName(), Arrays.asList("key", "words")), - new KeywordMarkerTokenFilter(generateName(), Collections.singletonList("essential")), - new LengthTokenFilter(generateName()).setMinLength(5).setMaxLength(10), - new LimitTokenFilter(generateName()).setMaxTokenCount(10).setAllTokensConsumed(true), - new NGramTokenFilter(generateName()).setMinGram(2).setMaxGram(3), - new PatternCaptureTokenFilter(generateName(), Collections.singletonList(".*")) - .setPreserveOriginal(false), - new PatternReplaceTokenFilter(generateName(), "abc", "123"), - new PhoneticTokenFilter(generateName()).setEncoder(PhoneticEncoder.SOUNDEX) - .setOriginalTokensReplaced(false), - new ShingleTokenFilter(generateName()).setMaxShingleSize(10) - .setMinShingleSize(5) - .setOutputUnigrams(false) - .setOutputUnigramsIfNoShingles(true) - .setTokenSeparator(" ") - .setFilterToken("|"), - new SnowballTokenFilter(generateName(), SnowballTokenFilterLanguage.ENGLISH), - new StemmerOverrideTokenFilter(generateName(), Collections.singletonList("ran => run")), - new StemmerTokenFilter(generateName(), StemmerTokenFilterLanguage.FRENCH), - new StopwordsTokenFilter(generateName()).setStopwords(Arrays.asList("a", "the")) - .setCaseIgnored(true) - .setTrailingStopWordsRemoved(false), - new StopwordsTokenFilter(generateName()).setStopwordsList(StopwordsList.ITALIAN) - .setCaseIgnored(true) - .setTrailingStopWordsRemoved(false), - new SynonymTokenFilter(generateName(), Collections.singletonList("great, good")).setCaseIgnored(true) - .setExpand(false), - new TruncateTokenFilter(generateName()).setLength(10), - new UniqueTokenFilter(generateName()).setOnlyOnSamePosition(true), - new UniqueTokenFilter(generateName()), - new WordDelimiterTokenFilter(generateName()).setGenerateWordParts(false) - .setGenerateNumberParts(false) - .setWordsCatenated(true) - .setNumbersCatenated(true) - .setCatenateAll(true) - .setSplitOnCaseChange(false) - .setPreserveOriginal(true) - .setSplitOnNumerics(false) - .setStemEnglishPossessive(false) - .setProtectedWords("protected")) - .setCharFilters(new MappingCharFilter(customCharFilterName.toString(), Collections.singletonList("a => b")), // One custom char filter for CustomeAnalyer above. - new MappingCharFilter(generateName(), Arrays.asList("s => $", "S => $")), - new PatternReplaceCharFilter(generateName(), "abc", "123")); - } - - SearchIndex createIndexWithSpecialDefaults() { - int i = 0; - - return createTestIndex(null) - .setAnalyzers(Arrays.asList(new PatternAnalyzer(generateSimpleName(i++)), - new LuceneStandardAnalyzer(generateSimpleName(i++)))) - .setTokenizers(Arrays.asList(new EdgeNGramTokenizer(generateSimpleName(i++)), - new NGramTokenizer(generateSimpleName(i++)), new ClassicTokenizer(generateSimpleName(i++)), - new KeywordTokenizer(generateSimpleName(i++)), - new MicrosoftLanguageStemmingTokenizer(generateSimpleName(i++)), - new MicrosoftLanguageTokenizer(generateSimpleName(i++)), - new PathHierarchyTokenizer(generateSimpleName(i++)), new PatternTokenizer(generateSimpleName(i++)), - new LuceneStandardTokenizer(generateSimpleName(i++)), - new UaxUrlEmailTokenizer(generateSimpleName(i++)))) - .setTokenFilters(Arrays.asList( - new DictionaryDecompounderTokenFilter(generateSimpleName(i++), Collections.singletonList("Bahnhof")), - new EdgeNGramTokenFilter(generateSimpleName(i++)), new LengthTokenFilter(generateSimpleName(i++)), - new LimitTokenFilter(generateSimpleName(i++)), new NGramTokenFilter(generateSimpleName(i++)), - new PatternCaptureTokenFilter(generateSimpleName(i++), Collections.singletonList("[a-z]*")), - new PhoneticTokenFilter(generateSimpleName(i++)), new ShingleTokenFilter(generateSimpleName(i++)), - new StopwordsTokenFilter(generateSimpleName(i++)), - new SynonymTokenFilter(generateSimpleName(i++), Collections.singletonList("mutt, canine => dog")), - new TruncateTokenFilter(generateSimpleName(i++)), new WordDelimiterTokenFilter(generateSimpleName(i)))); - } - - SearchIndex createExpectedIndexWithSpecialDefaults(SearchIndex index) { - int i = 0; - - return createTestIndex(index.getName()) - .setAnalyzers( - Arrays.asList(new PatternAnalyzer(generateSimpleName(i++)).setLowerCaseTerms(true).setPattern("\\W+"), - new LuceneStandardAnalyzer(generateSimpleName(i++)).setMaxTokenLength(255))) - .setTokenizers(Arrays.asList(new EdgeNGramTokenizer(generateSimpleName(i++)).setMinGram(1).setMaxGram(2), - new NGramTokenizer(generateSimpleName(i++)).setMinGram(1).setMaxGram(2), - new ClassicTokenizer(generateSimpleName(i++)).setMaxTokenLength(255), - new KeywordTokenizer(generateSimpleName(i++)).setMaxTokenLength(256), - new MicrosoftLanguageStemmingTokenizer(generateSimpleName(i++)).setMaxTokenLength(255) - .setIsSearchTokenizerUsed(false) - .setLanguage(MicrosoftStemmingTokenizerLanguage.ENGLISH), - new MicrosoftLanguageTokenizer(generateSimpleName(i++)).setMaxTokenLength(255) - .setIsSearchTokenizer(false) - .setLanguage(MicrosoftTokenizerLanguage.ENGLISH), - new PathHierarchyTokenizer(generateSimpleName(i++)).setDelimiter('/') - .setReplacement('/') - .setMaxTokenLength(300), - new PatternTokenizer(generateSimpleName(i++)).setPattern("\\W+").setGroup(-1), - new LuceneStandardTokenizer(generateSimpleName(i++)).setMaxTokenLength(255), - new UaxUrlEmailTokenizer(generateSimpleName(i++)).setMaxTokenLength(255))) - .setTokenFilters(Arrays.asList( - new DictionaryDecompounderTokenFilter(generateSimpleName(i++), Collections.singletonList("Bahnhof")) - .setMinWordSize(5) - .setMinSubwordSize(2) - .setMaxSubwordSize(15), - new EdgeNGramTokenFilter(generateSimpleName(i++)).setMinGram(1) - .setMaxGram(2) - .setSide(EdgeNGramTokenFilterSide.FRONT), - new LengthTokenFilter(generateSimpleName(i++)).setMaxLength(300), - new LimitTokenFilter(generateSimpleName(i++)).setMaxTokenCount(1), - new NGramTokenFilter(generateSimpleName(i++)).setMinGram(1).setMaxGram(2), - new PatternCaptureTokenFilter(generateSimpleName(i++), Collections.singletonList("[a-z]*")) - .setPreserveOriginal(true), - new PhoneticTokenFilter(generateSimpleName(i++)).setEncoder(PhoneticEncoder.METAPHONE) - .setOriginalTokensReplaced(true), - new ShingleTokenFilter(generateSimpleName(i++)).setMaxShingleSize(2) - .setMinShingleSize(2) - .setOutputUnigrams(true) - .setTokenSeparator(" ") - .setFilterToken("_"), - new StopwordsTokenFilter(generateSimpleName(i++)).setStopwordsList(StopwordsList.ENGLISH) - .setTrailingStopWordsRemoved(true), - new SynonymTokenFilter(generateSimpleName(i++), Collections.singletonList("mutt, canine => dog")) - .setExpand(true), - new TruncateTokenFilter(generateSimpleName(i++)).setLength(300), - new WordDelimiterTokenFilter(generateSimpleName(i)).setGenerateWordParts(true) - .setGenerateNumberParts(true) - .setSplitOnCaseChange(true) - .setSplitOnNumerics(true) - .setStemEnglishPossessive(true))); - } - - static void assertTokenInfoEqual(String expectedToken, Integer expectedStartOffset, Integer expectedEndOffset, - Integer expectedPosition, AnalyzedTokenInfo actual) { - assertEquals(expectedToken, actual.getToken()); - assertEquals(expectedStartOffset, actual.getStartOffset()); - assertEquals(expectedEndOffset, actual.getEndOffset()); - assertEquals(expectedPosition, actual.getPosition()); - } - - private static String generateSimpleName(int n) { - return "a" + n; - } - - private static List getAnalyzersAllowedForSearchAnalyzerAndIndexAnalyzer() { - // Only non-language analyzer names can be set on the searchAnalyzer and indexAnalyzer properties. - // ASSUMPTION: Only language analyzers end in .lucene or .microsoft. - return LEXICAL_ANALYZER_NAMES.stream() - .filter(an -> !an.toString().endsWith(".lucene") && !an.toString().endsWith(".microsoft")) - .collect(Collectors.toList()); - } - - /* - * This helper method is used when we want to retrieve all declared ExpandableStringEnum values. Using the - * '.values()' method isn't consistently safe as that would include any custom names that have been added into - * the enum during runtime. - */ - private static > List getExpandableEnumValues(Class clazz) { - List fieldValues = new ArrayList<>(); - - for (Field field : clazz.getDeclaredFields()) { - if (field.getType() != clazz) { - continue; - } - - try { - fieldValues.add(clazz.cast(field.get(null))); - } catch (IllegalAccessException ex) { - throw new RuntimeException(ex); - } - } - - return fieldValues; - } -} diff --git a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/indexes/DataSourceTests.java b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/indexes/DataSourceTests.java deleted file mode 100644 index b8aff6deaaa7..000000000000 --- a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/indexes/DataSourceTests.java +++ /dev/null @@ -1,654 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.search.documents.indexes; - -import com.azure.core.exception.HttpResponseException; -import com.azure.core.http.rest.Response; -import com.azure.core.util.Context; -import com.azure.search.documents.SearchTestBase; -import com.azure.search.documents.TestHelpers; -import com.azure.search.documents.indexes.models.DataDeletionDetectionPolicy; -import com.azure.search.documents.indexes.models.HighWaterMarkChangeDetectionPolicy; -import com.azure.search.documents.indexes.models.SearchIndexerDataContainer; -import com.azure.search.documents.indexes.models.SearchIndexerDataSourceConnection; -import com.azure.search.documents.indexes.models.SearchIndexerDataSourceType; -import com.azure.search.documents.indexes.models.SoftDeleteColumnDeletionDetectionPolicy; -import com.azure.search.documents.indexes.models.SqlIntegratedChangeTrackingPolicy; -import org.junit.jupiter.api.Test; -import reactor.core.publisher.Flux; -import reactor.core.publisher.Mono; -import reactor.test.StepVerifier; -import reactor.util.function.Tuple2; -import reactor.util.function.Tuples; - -import java.net.HttpURLConnection; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.stream.Collectors; - -import static com.azure.search.documents.TestHelpers.BLOB_DATASOURCE_TEST_NAME; -import static com.azure.search.documents.TestHelpers.assertHttpResponseException; -import static com.azure.search.documents.TestHelpers.assertObjectEquals; -import static com.azure.search.documents.TestHelpers.verifyHttpResponseError; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertInstanceOf; -import static org.junit.jupiter.api.Assertions.assertNotEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.junit.jupiter.api.Assertions.assertTrue; -import static org.junit.jupiter.api.Assertions.fail; - -public class DataSourceTests extends SearchTestBase { - private static final String FAKE_DESCRIPTION = "Some data source"; - private static final String FAKE_STORAGE_CONNECTION_STRING - = "DefaultEndpointsProtocol=https;AccountName=NotaRealAccount;AccountKey=fake;"; - private static final String FAKE_COSMOS_CONNECTION_STRING - = "AccountEndpoint=https://NotaRealAccount.documents.azure.com;AccountKey=fake;Database=someFakeDatabase"; - public static final String FAKE_AZURE_SQL_CONNECTION_STRING - = "Server=tcp:fakeUri,1433;Database=fakeDatabase;User ID=reader;Password=fakePassword;" - + "Trusted_Connection=False;Encrypt=True;Connection Timeout=30;"; - - private final List dataSourcesToDelete = new ArrayList<>(); - - private SearchIndexerAsyncClient asyncClient; - private SearchIndexerClient client; - - @Override - protected void beforeTest() { - super.beforeTest(); - - asyncClient = getSearchIndexerClientBuilder(false).buildAsyncClient(); - client = getSearchIndexerClientBuilder(true).buildClient(); - } - - @Override - protected void afterTest() { - super.afterTest(); - for (String dataSource : dataSourcesToDelete) { - client.deleteDataSourceConnection(dataSource); - } - - } - - @Test - public void canCreateAndListDataSourcesSync() { - SearchIndexerDataSourceConnection dataSource1 = createTestBlobDataSource(null); - SearchIndexerDataSourceConnection dataSource2 = createTestSqlDataSourceObject(); - - Map expectedDataSources = new HashMap<>(); - expectedDataSources.put(dataSource1.getName(), dataSource1); - expectedDataSources.put(dataSource2.getName(), dataSource2); - - client.createOrUpdateDataSourceConnection(dataSource1); - dataSourcesToDelete.add(dataSource1.getName()); - client.createOrUpdateDataSourceConnection(dataSource2); - dataSourcesToDelete.add(dataSource2.getName()); - - Map actualDataSources = client.listDataSourceConnections() - .stream() - .collect(Collectors.toMap(SearchIndexerDataSourceConnection::getName, ds -> ds)); - - compareMaps(expectedDataSources, actualDataSources, DataSourceTests::assertDataSourceEquals); - } - - @Test - public void canCreateAndListDataSourcesAsync() { - SearchIndexerDataSourceConnection dataSource1 = createTestBlobDataSource(null); - SearchIndexerDataSourceConnection dataSource2 = createTestSqlDataSourceObject(); - - Map expectedDataSources = new HashMap<>(); - expectedDataSources.put(dataSource1.getName(), dataSource1); - expectedDataSources.put(dataSource2.getName(), dataSource2); - - Mono> listMono - = Flux.fromIterable(Arrays.asList(dataSource1, dataSource2)) - .flatMap(asyncClient::createOrUpdateDataSourceConnection) - .doOnNext(ds -> dataSourcesToDelete.add(ds.getName())) - .thenMany(asyncClient.listDataSourceConnections()) - .collectMap(SearchIndexerDataSourceConnection::getName); - - StepVerifier.create(listMono) - .assertNext(actualDataSources -> compareMaps(expectedDataSources, actualDataSources, - DataSourceTests::assertDataSourceEquals)) - .verifyComplete(); - } - - @Test - public void canCreateAndListDataSourcesWithResponseSync() { - SearchIndexerDataSourceConnection dataSource1 = createTestBlobDataSource(null); - SearchIndexerDataSourceConnection dataSource2 = createTestSqlDataSourceObject(); - - Set expectedDataSources = new HashSet<>(); - expectedDataSources.add(dataSource1.getName()); - expectedDataSources.add(dataSource2.getName()); - - client.createOrUpdateDataSourceConnectionWithResponse(dataSource1, false, Context.NONE); - dataSourcesToDelete.add(dataSource1.getName()); - client.createOrUpdateDataSourceConnectionWithResponse(dataSource2, false, Context.NONE); - dataSourcesToDelete.add(dataSource2.getName()); - - Set actualDataSources - = client.listDataSourceConnectionNames(Context.NONE).stream().collect(Collectors.toSet()); - - assertEquals(expectedDataSources.size(), actualDataSources.size()); - expectedDataSources.forEach(ds -> assertTrue(actualDataSources.contains(ds), "Missing expected data source.")); - } - - @Test - public void canCreateAndListDataSourcesWithResponseAsync() { - SearchIndexerDataSourceConnection dataSource1 = createTestBlobDataSource(null); - SearchIndexerDataSourceConnection dataSource2 = createTestSqlDataSourceObject(); - - Set expectedDataSources = new HashSet<>(); - expectedDataSources.add(dataSource1.getName()); - expectedDataSources.add(dataSource2.getName()); - - Mono> listMono = Flux.fromIterable(Arrays.asList(dataSource1, dataSource2)) - .flatMap(ds -> asyncClient.createOrUpdateDataSourceConnectionWithResponse(ds, false)) - .doOnNext(ds -> dataSourcesToDelete.add(ds.getValue().getName())) - .thenMany(asyncClient.listDataSourceConnectionNames()) - .collect(Collectors.toSet()); - - StepVerifier.create(listMono).assertNext(actualDataSources -> { - assertEquals(expectedDataSources.size(), actualDataSources.size()); - expectedDataSources - .forEach(ds -> assertTrue(actualDataSources.contains(ds), "Missing expected data source.")); - }).verifyComplete(); - } - - @Test - public void canCreateAndDeleteDatasourceSync() { - SearchIndexerDataSourceConnection dataSource = createTestBlobDataSource(null); - client.deleteDataSourceConnection(dataSource.getName()); - - assertThrows(HttpResponseException.class, () -> client.getDataSourceConnection(dataSource.getName())); - } - - @Test - public void canCreateAndDeleteDatasourceAsync() { - SearchIndexerDataSourceConnection dataSource = createTestBlobDataSource(null); - client.deleteDataSourceConnection(dataSource.getName()); - - StepVerifier.create(asyncClient.getDataSourceConnection(dataSource.getName())) - .verifyError(HttpResponseException.class); - } - - @Test - public void deleteDataSourceIsIdempotentSync() { - SearchIndexerDataSourceConnection dataSource = createTestBlobDataSource(null); - - // Try to delete before the data source exists, expect a NOT FOUND return status code - Response result = client.deleteDataSourceConnectionWithResponse(dataSource, false, Context.NONE); - assertEquals(HttpURLConnection.HTTP_NOT_FOUND, result.getStatusCode()); - - // Create the data source - client.createOrUpdateDataSourceConnection(dataSource); - - // Delete twice, expect the first to succeed (with NO CONTENT status code) and the second to return NOT FOUND - result = client.deleteDataSourceConnectionWithResponse(dataSource, false, Context.NONE); - assertEquals(HttpURLConnection.HTTP_NO_CONTENT, result.getStatusCode()); - // Again, expect to fail - result = client.deleteDataSourceConnectionWithResponse(dataSource, false, Context.NONE); - assertEquals(HttpURLConnection.HTTP_NOT_FOUND, result.getStatusCode()); - } - - @Test - public void deleteDataSourceIsIdempotentAsync() { - SearchIndexerDataSourceConnection dataSource = createTestBlobDataSource(null); - - // Try to delete before the data source exists, expect a NOT FOUND return status code - StepVerifier.create(asyncClient.deleteDataSourceConnectionWithResponse(dataSource, false)) - .assertNext(response -> assertEquals(HttpURLConnection.HTTP_NOT_FOUND, response.getStatusCode())) - .verifyComplete(); - - // Create the data source - asyncClient.createOrUpdateDataSourceConnection(dataSource).block(); - - // Delete twice, expect the first to succeed (with NO CONTENT status code) and the second to return NOT FOUND - StepVerifier.create(asyncClient.deleteDataSourceConnectionWithResponse(dataSource, false)) - .assertNext(response -> assertEquals(HttpURLConnection.HTTP_NO_CONTENT, response.getStatusCode())) - .verifyComplete(); - - // Again, expect to fail - StepVerifier.create(asyncClient.deleteDataSourceConnectionWithResponse(dataSource, false)) - .assertNext(response -> assertEquals(HttpURLConnection.HTTP_NOT_FOUND, response.getStatusCode())) - .verifyComplete(); - } - - @Test - public void createDataSourceFailsWithUsefulMessageOnUserErrorSyncAndAsync() { - SearchIndexerDataSourceConnection dataSource = createTestSqlDataSourceObject(); - dataSource.setType(SearchIndexerDataSourceType.fromString("thistypedoesnotexist")); - - assertHttpResponseException(() -> client.createOrUpdateDataSourceConnection(dataSource), - HttpURLConnection.HTTP_BAD_REQUEST, "Data source type 'thistypedoesnotexist' is not supported"); - - StepVerifier.create(asyncClient.createOrUpdateDataSourceConnection(dataSource)) - .verifyErrorSatisfies(throwable -> verifyHttpResponseError(throwable, HttpURLConnection.HTTP_BAD_REQUEST, - "Data source type 'thistypedoesnotexist' is not supported")); - } - - @Test - public void canUpdateDataSourceSync() { - SearchIndexerDataSourceConnection initial = createTestSqlDataSourceObject(); - - // Create the data source - client.createOrUpdateDataSourceConnection(initial); - dataSourcesToDelete.add(initial.getName()); - SearchIndexerDataSourceConnection updatedExpected = createTestSqlDataSourceObject(initial.getName(), null, null) - .setContainer(new SearchIndexerDataContainer("somethingdifferent")) - .setDescription("somethingdifferent") - .setDataChangeDetectionPolicy(new HighWaterMarkChangeDetectionPolicy("rowversion")) - .setDataDeletionDetectionPolicy( - new SoftDeleteColumnDeletionDetectionPolicy().setSoftDeleteColumnName("isDeleted")); - - SearchIndexerDataSourceConnection updatedActual = client.createOrUpdateDataSourceConnection(updatedExpected); - - updatedExpected.setConnectionString(null); // Create doesn't return connection strings. - TestHelpers.assertObjectEquals(updatedExpected, updatedActual, false, "etag", "@odata.etag", "@odata.type"); - } - - @Test - public void canUpdateDataSourceAsync() { - SearchIndexerDataSourceConnection initial = createTestSqlDataSourceObject(); - - // Create the data source - asyncClient.createOrUpdateDataSourceConnection(initial).block(); - dataSourcesToDelete.add(initial.getName()); - - SearchIndexerDataSourceConnection updatedExpected = createTestSqlDataSourceObject(initial.getName(), null, null) - .setContainer(new SearchIndexerDataContainer("somethingdifferent")) - .setDescription("somethingdifferent") - .setDataChangeDetectionPolicy(new HighWaterMarkChangeDetectionPolicy("rowversion")) - .setDataDeletionDetectionPolicy( - new SoftDeleteColumnDeletionDetectionPolicy().setSoftDeleteColumnName("isDeleted")); - - StepVerifier.create(asyncClient.createOrUpdateDataSourceConnection(updatedExpected)).assertNext(actual -> - // Create doesn't return connection strings. - assertObjectEquals(updatedExpected.setConnectionString(null), actual, false, "etag", "@odata.etag", - "@odata.type")).verifyComplete(); - } - - @Test - public void createOrUpdateDatasourceIfNotExistsSucceedsOnNoResourceSync() { - SearchIndexerDataSourceConnection dataSource = createTestBlobDataSource(null); - dataSourcesToDelete.add(dataSource.getName()); - - SearchIndexerDataSourceConnection response - = client.createOrUpdateDataSourceConnectionWithResponse(dataSource, true, Context.NONE).getValue(); - - assertNotNull(response.getETag()); - } - - @Test - public void createOrUpdateDatasourceIfNotExistsSucceedsOnNoResourceAsync() { - SearchIndexerDataSourceConnection dataSource = createTestBlobDataSource(null); - dataSourcesToDelete.add(dataSource.getName()); - - StepVerifier.create(asyncClient.createOrUpdateDataSourceConnectionWithResponse(dataSource, true)) - .assertNext(response -> assertNotNull(response.getValue().getETag())) - .verifyComplete(); - } - - @Test - public void deleteDataSourceIfExistsWorksOnlyWhenResourceExistsSyncAndAsync() { - SearchIndexerDataSourceConnection dataSource = createTestBlobDataSource(null); - dataSourcesToDelete.add(dataSource.getName()); - - SearchIndexerDataSourceConnection response - = client.createOrUpdateDataSourceConnectionWithResponse(dataSource, false, Context.NONE).getValue(); - - client.deleteDataSourceConnectionWithResponse(response, true, Context.NONE); - - try { - client.deleteDataSourceConnectionWithResponse(response, true, Context.NONE); - fail("Second call to delete with specified ETag should have failed due to non existent data source."); - } catch (HttpResponseException ex) { - assertEquals(HttpURLConnection.HTTP_PRECON_FAILED, ex.getResponse().getStatusCode()); - } - - StepVerifier.create(asyncClient.deleteDataSourceConnectionWithResponse(response, true)) - .verifyErrorSatisfies(throwable -> { - HttpResponseException ex = assertInstanceOf(HttpResponseException.class, throwable); - assertEquals(HttpURLConnection.HTTP_PRECON_FAILED, ex.getResponse().getStatusCode()); - }); - } - - @Test - public void deleteDataSourceIfNotChangedWorksOnlyOnCurrentResourceSyncAndAsync() { - SearchIndexerDataSourceConnection dataSource = createTestBlobDataSource(null); - - SearchIndexerDataSourceConnection stale - = client.createOrUpdateDataSourceConnectionWithResponse(dataSource, false, Context.NONE).getValue(); - - SearchIndexerDataSourceConnection current - = client.createOrUpdateDataSourceConnectionWithResponse(stale, false, Context.NONE).getValue(); - - try { - client.deleteDataSourceConnectionWithResponse(stale, true, Context.NONE); - fail("Delete specifying a stale ETag should have failed due to precondition."); - } catch (HttpResponseException ex) { - assertEquals(HttpURLConnection.HTTP_PRECON_FAILED, ex.getResponse().getStatusCode()); - } - - StepVerifier.create(asyncClient.deleteDataSourceConnectionWithResponse(stale, true)) - .verifyErrorSatisfies(throwable -> { - HttpResponseException ex = assertInstanceOf(HttpResponseException.class, throwable); - assertEquals(HttpURLConnection.HTTP_PRECON_FAILED, ex.getResponse().getStatusCode()); - }); - - client.deleteDataSourceConnectionWithResponse(current, true, Context.NONE); - } - - @Test - public void updateDataSourceIfExistsSucceedsOnExistingResourceSync() { - SearchIndexerDataSourceConnection dataSource = createTestBlobDataSource(null); - dataSourcesToDelete.add(dataSource.getName()); - - SearchIndexerDataSourceConnection original - = client.createOrUpdateDataSourceConnectionWithResponse(dataSource, false, Context.NONE).getValue(); - - String originalETag = original.getETag(); - - SearchIndexerDataSourceConnection updated = client - .createOrUpdateDataSourceConnectionWithResponse(original.setDescription("an update"), false, Context.NONE) - .getValue(); - - String updatedETag = updated.getETag(); - - assertNotNull(updatedETag); - assertNotEquals(originalETag, updatedETag); - } - - @Test - public void updateDataSourceIfExistsSucceedsOnExistingResourceAsync() { - SearchIndexerDataSourceConnection dataSource = createTestBlobDataSource(null); - dataSourcesToDelete.add(dataSource.getName()); - - Mono> createThenUpdateMono - = asyncClient.createOrUpdateDataSourceConnectionWithResponse(dataSource, false).flatMap(response -> { - SearchIndexerDataSourceConnection original = response.getValue(); - String originalETag = original.getETag(); - - return asyncClient - .createOrUpdateDataSourceConnectionWithResponse(original.setDescription("an update"), false) - .map(updated -> Tuples.of(originalETag, updated.getValue().getETag())); - }); - - StepVerifier.create(createThenUpdateMono).assertNext(etags -> { - assertNotNull(etags.getT2()); - assertNotEquals(etags.getT1(), etags.getT2()); - }).verifyComplete(); - } - - @Test - public void updateDataSourceIfNotChangedFailsWhenResourceChangedSyncAndAsync() { - SearchIndexerDataSourceConnection dataSource = createTestBlobDataSource(null); - dataSourcesToDelete.add(dataSource.getName()); - - SearchIndexerDataSourceConnection original - = client.createOrUpdateDataSourceConnectionWithResponse(dataSource, false, Context.NONE).getValue(); - String originalETag = original.getETag(); - - SearchIndexerDataSourceConnection updated = client - .createOrUpdateDataSourceConnectionWithResponse(original.setDescription("an update"), false, Context.NONE) - .getValue(); - String updatedETag = updated.getETag(); - - try { - client.createOrUpdateDataSourceConnectionWithResponse(original, true, Context.NONE); - fail("createOrUpdateDefinition should have failed due to precondition."); - } catch (HttpResponseException ex) { - assertEquals(HttpURLConnection.HTTP_PRECON_FAILED, ex.getResponse().getStatusCode()); - } - - StepVerifier.create(asyncClient.createOrUpdateDataSourceConnectionWithResponse(original, true)) - .verifyErrorSatisfies(throwable -> { - HttpResponseException ex = assertInstanceOf(HttpResponseException.class, throwable); - assertEquals(HttpURLConnection.HTTP_PRECON_FAILED, ex.getResponse().getStatusCode()); - }); - - assertNotNull(originalETag); - assertNotNull(updatedETag); - assertNotEquals(originalETag, updatedETag); - } - - @Test - public void updateDataSourceIfNotChangedSucceedsWhenResourceUnchangedSync() { - SearchIndexerDataSourceConnection dataSource = createTestBlobDataSource(null); - dataSourcesToDelete.add(dataSource.getName()); - - SearchIndexerDataSourceConnection original - = client.createOrUpdateDataSourceConnectionWithResponse(dataSource, false, Context.NONE).getValue(); - String originalETag = original.getETag(); - - SearchIndexerDataSourceConnection updated = client - .createOrUpdateDataSourceConnectionWithResponse(original.setDescription("an update"), true, Context.NONE) - .getValue(); - String updatedETag = updated.getETag(); - - // Check eTags as expected - assertNotNull(originalETag); - assertNotNull(updatedETag); - assertNotEquals(originalETag, updatedETag); - } - - @Test - public void updateDataSourceIfNotChangedSucceedsWhenResourceUnchangedAsync() { - SearchIndexerDataSourceConnection dataSource = createTestBlobDataSource(null); - dataSourcesToDelete.add(dataSource.getName()); - - Mono> etagUpdatesOnChangeMono - = asyncClient.createOrUpdateDataSourceConnectionWithResponse(dataSource, false).flatMap(response -> { - SearchIndexerDataSourceConnection original = response.getValue(); - String originalETag = original.getETag(); - - return asyncClient - .createOrUpdateDataSourceConnectionWithResponse(original.setDescription("an update"), true) - .map(updated -> Tuples.of(originalETag, updated.getValue().getETag())); - }); - - StepVerifier.create(etagUpdatesOnChangeMono).assertNext(etags -> { - assertNotNull(etags.getT1()); - assertNotNull(etags.getT2()); - assertNotEquals(etags.getT1(), etags.getT2()); - }).verifyComplete(); - } - - // TODO (alzimmer): Re-enable this test once live resource deployment is configured. - //@Test - public void createDataSourceReturnsCorrectDefinition() { - SoftDeleteColumnDeletionDetectionPolicy deletionDetectionPolicy - = new SoftDeleteColumnDeletionDetectionPolicy().setSoftDeleteColumnName("isDeleted") - .setSoftDeleteMarkerValue("1"); - - HighWaterMarkChangeDetectionPolicy changeDetectionPolicy = new HighWaterMarkChangeDetectionPolicy("fakecolumn"); - - // AzureSql - createAndValidateDataSource(createTestSqlDataSourceObject(null, null)); - createAndValidateDataSource(createTestSqlDataSourceObject(deletionDetectionPolicy, null)); - createAndValidateDataSource(createTestSqlDataSourceObject(null, new SqlIntegratedChangeTrackingPolicy())); - createAndValidateDataSource(createTestSqlDataSourceObject(deletionDetectionPolicy, changeDetectionPolicy)); - - // Cosmos - createAndValidateDataSource(createTestCosmosDataSource(null, false)); - createAndValidateDataSource(createTestCosmosDataSource(null, true)); - createAndValidateDataSource(createTestCosmosDataSource(deletionDetectionPolicy, false)); - createAndValidateDataSource(createTestCosmosDataSource(deletionDetectionPolicy, false)); - - // Azure Blob Storage - createAndValidateDataSource(createTestBlobDataSource(null)); - createAndValidateDataSource(createTestBlobDataSource(deletionDetectionPolicy)); - - // Azure Table Storage - createAndValidateDataSource(createTestTableStorageDataSource()); - createAndValidateDataSource(createTestBlobDataSource(deletionDetectionPolicy)); - } - - private void createAndValidateDataSource(SearchIndexerDataSourceConnection expectedDataSource) { - SearchIndexerDataSourceConnection actualDataSource - = client.createOrUpdateDataSourceConnection(expectedDataSource); - - expectedDataSource.setConnectionString(null); - TestHelpers.assertObjectEquals(expectedDataSource, actualDataSource, false, "etag", "@odata.etag"); - // we delete the data source because otherwise we will hit the quota limits during the tests - client.deleteDataSourceConnection(actualDataSource.getName()); - - } - - @Test - public void getDataSourceReturnsCorrectDefinitionSync() { - createGetAndValidateDataSourceSync(createTestBlobDataSource(null)); - createGetAndValidateDataSourceSync(createTestTableStorageDataSource()); - createGetAndValidateDataSourceSync(createTestSqlDataSourceObject()); - createGetAndValidateDataSourceSync(createTestCosmosDataSource(null, false)); - } - - private void createGetAndValidateDataSourceSync(SearchIndexerDataSourceConnection expectedDataSource) { - client.createOrUpdateDataSourceConnection(expectedDataSource); - String dataSourceName = expectedDataSource.getName(); - - // Get doesn't return connection strings. - expectedDataSource.setConnectionString(null); - - SearchIndexerDataSourceConnection actualDataSource = client.getDataSourceConnection(dataSourceName); - TestHelpers.assertObjectEquals(expectedDataSource, actualDataSource, false, "etag", "@odata.etag"); - - actualDataSource = client.getDataSourceConnectionWithResponse(dataSourceName, Context.NONE).getValue(); - TestHelpers.assertObjectEquals(expectedDataSource, actualDataSource, false, "etag", "@odata.etag"); - - client.deleteDataSourceConnection(dataSourceName); - } - - @Test - public void getDataSourceReturnsCorrectDefinitionAsync() { - createGetAndValidateDataSourceAsync(createTestBlobDataSource(null)); - createGetAndValidateDataSourceAsync(createTestTableStorageDataSource()); - createGetAndValidateDataSourceAsync(createTestSqlDataSourceObject()); - createGetAndValidateDataSourceAsync(createTestCosmosDataSource(null, false)); - } - - private void createGetAndValidateDataSourceAsync(SearchIndexerDataSourceConnection expectedDataSource) { - asyncClient.createOrUpdateDataSourceConnection(expectedDataSource).block(); - String dataSourceName = expectedDataSource.getName(); - - // Get doesn't return connection strings. - expectedDataSource.setConnectionString(null); - - StepVerifier.create(asyncClient.getDataSourceConnection(dataSourceName)) - .assertNext(actualDataSource -> assertObjectEquals(expectedDataSource, actualDataSource, false, "etag", - "@odata.etag")) - .verifyComplete(); - - StepVerifier.create(asyncClient.getDataSourceConnectionWithResponse(dataSourceName)) - .assertNext( - response -> assertObjectEquals(expectedDataSource, response.getValue(), false, "etag", "@odata.etag")) - .verifyComplete(); - - asyncClient.deleteDataSourceConnection(dataSourceName).block(); - } - - @Test - public void getDataSourceThrowsOnNotFoundSyncAndAsync() { - assertHttpResponseException(() -> client.getDataSourceConnection("thisdatasourcedoesnotexist"), - HttpURLConnection.HTTP_NOT_FOUND, - "No data source with the name 'thisdatasourcedoesnotexist' was found in service"); - - StepVerifier.create(asyncClient.getDataSourceConnection("thisdatasourcedoesnotexist")) - .verifyErrorSatisfies(exception -> verifyHttpResponseError(exception, HttpURLConnection.HTTP_NOT_FOUND, - "No data source with the name 'thisdatasourcedoesnotexist' was found in service")); - } - - @Test - public void canCreateDataSourceSync() { - SearchIndexerDataSourceConnection expectedDataSource = createTestBlobDataSource(null); - dataSourcesToDelete.add(expectedDataSource.getName()); - SearchIndexerDataSourceConnection actualDataSource = client.createDataSourceConnection(expectedDataSource); - - assertEquals(expectedDataSource.getName(), actualDataSource.getName()); - } - - @Test - public void canCreateDataSourceAsync() { - SearchIndexerDataSourceConnection expectedDataSource = createTestBlobDataSource(null); - dataSourcesToDelete.add(expectedDataSource.getName()); - - StepVerifier.create(asyncClient.createDataSourceConnection(expectedDataSource)) - .assertNext(actualDataSource -> assertEquals(expectedDataSource.getName(), actualDataSource.getName())) - .verifyComplete(); - } - - @Test - public void canCreateDataSourceWithResponseSync() { - SearchIndexerDataSourceConnection expectedDataSource = createTestBlobDataSource(null); - dataSourcesToDelete.add(expectedDataSource.getName()); - Response response - = client.createDataSourceConnectionWithResponse(expectedDataSource, Context.NONE); - - assertEquals(expectedDataSource.getName(), response.getValue().getName()); - assertEquals(HttpURLConnection.HTTP_CREATED, response.getStatusCode()); - } - - @Test - public void canCreateDataSourceWithResponseAsync() { - SearchIndexerDataSourceConnection expectedDataSource = createTestBlobDataSource(null); - dataSourcesToDelete.add(expectedDataSource.getName()); - - StepVerifier.create(asyncClient.createDataSourceConnectionWithResponse(expectedDataSource)) - .assertNext(response -> { - assertEquals(expectedDataSource.getName(), response.getValue().getName()); - assertEquals(HttpURLConnection.HTTP_CREATED, response.getStatusCode()); - }) - .verifyComplete(); - } - - @Test - public void canUpdateConnectionData() { - // Note: since connection string is not returned when queried from the service, actually saving the - // datasource, retrieving it and verifying the change, won't work. - // Hence, we only validate that the properties on the local items can change. - - // Create an initial dataSource - SearchIndexerDataSourceConnection initial = createTestBlobDataSource(null); - assertEquals(initial.getConnectionString(), FAKE_STORAGE_CONNECTION_STRING); - - // tweak the connection string and verify it was changed - String newConnString - = "DefaultEndpointsProtocol=https;AccountName=NotaRealYetDifferentAccount;AccountKey=AnotherFakeKey;"; - initial.setConnectionString(newConnString); - - assertEquals(initial.getConnectionString(), newConnString); - } - - SearchIndexerDataSourceConnection createTestBlobDataSource(DataDeletionDetectionPolicy deletionDetectionPolicy) { - return SearchIndexerDataSources.createFromAzureBlobStorage( - testResourceNamer.randomName(BLOB_DATASOURCE_TEST_NAME, 32), FAKE_STORAGE_CONNECTION_STRING, - "fakecontainer", "/fakefolder/", FAKE_DESCRIPTION, deletionDetectionPolicy); - } - - static SearchIndexerDataSourceConnection createTestTableStorageDataSource() { - return SearchIndexerDataSources.createFromAzureTableStorage("azs-java-test-tablestorage", - FAKE_STORAGE_CONNECTION_STRING, "faketable", "fake query", FAKE_DESCRIPTION, null); - } - - static SearchIndexerDataSourceConnection - createTestCosmosDataSource(DataDeletionDetectionPolicy deletionDetectionPolicy, boolean useChangeDetection) { - return SearchIndexerDataSources.createFromCosmos("azs-java-test-cosmos", FAKE_COSMOS_CONNECTION_STRING, - "faketable", "SELECT ... FROM x where x._ts > @HighWaterMark", useChangeDetection, FAKE_DESCRIPTION, - deletionDetectionPolicy); - } - - private static void assertDataSourceEquals(SearchIndexerDataSourceConnection expect, - SearchIndexerDataSourceConnection actual) { - assertEquals(expect.getName(), actual.getName()); - assertEquals(expect.getDescription(), actual.getDescription()); - assertEquals(expect.getType(), actual.getType()); - assertEquals(expect.getContainer().getName(), actual.getContainer().getName()); - } -} diff --git a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/indexes/DataSourcesTest.java b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/indexes/DataSourcesTest.java deleted file mode 100644 index f92e2ee5f6f3..000000000000 --- a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/indexes/DataSourcesTest.java +++ /dev/null @@ -1,78 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.search.documents.indexes; - -import com.azure.search.documents.TestHelpers; -import com.azure.search.documents.indexes.models.HighWaterMarkChangeDetectionPolicy; -import com.azure.search.documents.indexes.models.SearchIndexerDataContainer; -import com.azure.search.documents.indexes.models.SearchIndexerDataSourceConnection; -import com.azure.search.documents.indexes.models.SearchIndexerDataSourceType; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.parallel.Execution; -import org.junit.jupiter.api.parallel.ExecutionMode; - -/** - * Unit Test DataSources utility class - */ -@Execution(ExecutionMode.CONCURRENT) -public class DataSourcesTest { - - @Test - public void canCreateSqlDataSource() { - // check utility method with minimal overloads - SearchIndexerDataSourceConnection expected = new SearchIndexerDataSourceConnection("sql", - SearchIndexerDataSourceType.AZURE_SQL, "connectionString", new SearchIndexerDataContainer("table")); - SearchIndexerDataSourceConnection actual - = SearchIndexerDataSources.createFromAzureSql("sql", "connectionString", "table"); - - TestHelpers.assertObjectEquals(expected, actual, false, "etag"); - } - - @Test - public void canCreateStorageBlobDataSource() { - // check utility method with minimal overloads - SearchIndexerDataSourceConnection expected = new SearchIndexerDataSourceConnection("storageBlob", - SearchIndexerDataSourceType.AZURE_BLOB, "connectionString", new SearchIndexerDataContainer("container")); - SearchIndexerDataSourceConnection actual - = SearchIndexerDataSources.createFromAzureBlobStorage("storageBlob", "connectionString", "container"); - - TestHelpers.assertObjectEquals(expected, actual, false, "etag"); - } - - @Test - public void canCreateStorageTableDataSource() { - // check utility method with minimal overloads - SearchIndexerDataSourceConnection expected = new SearchIndexerDataSourceConnection("storageTable", - SearchIndexerDataSourceType.AZURE_TABLE, "connectionString", new SearchIndexerDataContainer("table")); - SearchIndexerDataSourceConnection actual - = SearchIndexerDataSources.createFromAzureTableStorage("storageTable", "connectionString", "table"); - - TestHelpers.assertObjectEquals(expected, actual, false, "etag"); - } - - @Test - public void canCreateCosmosDataSource() { - // check utility method overloads - SearchIndexerDataSourceConnection expected = new SearchIndexerDataSourceConnection("cosmos", - SearchIndexerDataSourceType.COSMOS_DB, "connectionString", new SearchIndexerDataContainer("collection")); - - SearchIndexerDataSourceConnection actual - = SearchIndexerDataSources.createFromCosmos("cosmos", "connectionString", "collection", false); - - TestHelpers.assertObjectEquals(expected, actual, false, "etag"); - } - - @Test - public void canCreateCosmosDataSourceWithMinimalOverload() { - // check utility method with minimal overloads - SearchIndexerDataSourceConnection expected = new SearchIndexerDataSourceConnection("cosmos", - SearchIndexerDataSourceType.COSMOS_DB, "connectionString", new SearchIndexerDataContainer("collection")) - .setDataChangeDetectionPolicy(new HighWaterMarkChangeDetectionPolicy("_ts")); - - SearchIndexerDataSourceConnection actual - = SearchIndexerDataSources.createFromCosmos("cosmos", "connectionString", "collection"); - - TestHelpers.assertObjectEquals(expected, actual, false, "etag"); - } -} diff --git a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/indexes/FieldBuilderServiceTests.java b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/indexes/FieldBuilderServiceTests.java deleted file mode 100644 index af83ccb9b5bf..000000000000 --- a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/indexes/FieldBuilderServiceTests.java +++ /dev/null @@ -1,85 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.search.documents.indexes; - -import com.azure.core.serializer.json.jackson.JacksonJsonSerializerBuilder; -import com.azure.search.documents.SearchTestBase; -import com.azure.search.documents.indexes.models.FieldBuilderOptions; -import com.azure.search.documents.indexes.models.SearchIndex; -import com.azure.search.documents.indexes.models.SynonymMap; -import com.azure.search.documents.test.environment.models.Hotel; -import com.fasterxml.jackson.annotation.JsonAutoDetect; -import com.fasterxml.jackson.annotation.PropertyAccessor; -import com.fasterxml.jackson.databind.ObjectMapper; -import org.junit.jupiter.api.Test; -import reactor.core.publisher.Mono; -import reactor.test.StepVerifier; - -import java.util.ArrayList; -import java.util.List; - -import static com.azure.search.documents.TestHelpers.assertObjectEquals; - -public class FieldBuilderServiceTests extends SearchTestBase { - private SearchIndexClient client; - private SearchIndexAsyncClient asyncClient; - private final List indexesToDelete = new ArrayList<>(); - String synonymMapName = "fieldbuilder"; - - @Override - protected void beforeTest() { - super.beforeTest(); - client = getSearchIndexClientBuilder(true).buildClient(); - asyncClient = getSearchIndexClientBuilder(false).buildAsyncClient(); - } - - @Override - protected void afterTest() { - super.afterTest(); - assert client != null; - - for (String index : indexesToDelete) { - client.deleteIndex(index); - } - - client.deleteSynonymMap(synonymMapName); - } - - @Test - public void createIndexWithFieldBuilderSync() { - SynonymMap synonymMap = new SynonymMap(synonymMapName).setSynonyms("hotel,motel"); - client.createSynonymMap(synonymMap); - - SearchIndex index = new SearchIndex(testResourceNamer.randomName("fieldbuilder", 32)); - index.setFields(SearchIndexClient.buildSearchFields(Hotel.class, - new FieldBuilderOptions().setJsonSerializer(new JacksonJsonSerializerBuilder() - .serializer(new ObjectMapper().setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY)) - .build()))); - - client.createIndex(index); - indexesToDelete.add(index.getName()); - assertObjectEquals(index, client.getIndex(index.getName()), true); - } - - @Test - public void createIndexWithFieldBuilderAsync() { - SynonymMap synonymMap = new SynonymMap(synonymMapName).setSynonyms("hotel,motel"); - asyncClient.createSynonymMap(synonymMap).block(); - - SearchIndex index = new SearchIndex(testResourceNamer.randomName("fieldbuilder", 32)); - index.setFields(SearchIndexClient.buildSearchFields(Hotel.class, - new FieldBuilderOptions().setJsonSerializer(new JacksonJsonSerializerBuilder() - .serializer(new ObjectMapper().setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY)) - .build()))); - - Mono createThenGetIndex = asyncClient.createIndex(index).flatMap(actual -> { - indexesToDelete.add(actual.getName()); - return asyncClient.getIndex(actual.getName()); - }); - - StepVerifier.create(createThenGetIndex) - .assertNext(actual -> assertObjectEquals(index, actual, true)) - .verifyComplete(); - } -} diff --git a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/indexes/FieldBuilderTests.java b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/indexes/FieldBuilderTests.java deleted file mode 100644 index 0db4f8045f47..000000000000 --- a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/indexes/FieldBuilderTests.java +++ /dev/null @@ -1,466 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.search.documents.indexes; - -import com.azure.core.models.GeoPoint; -import com.azure.search.documents.TestHelpers; -import com.azure.search.documents.indexes.models.SearchField; -import com.azure.search.documents.indexes.models.SearchFieldDataType; -import com.azure.search.documents.test.environment.models.HotelAnalyzerException; -import com.azure.search.documents.test.environment.models.HotelCircularDependencies; -import com.azure.search.documents.test.environment.models.HotelRenameProperty; -import com.azure.search.documents.test.environment.models.HotelSearchException; -import com.azure.search.documents.test.environment.models.HotelSearchableExceptionOnList; -import com.azure.search.documents.test.environment.models.HotelTwoDimensional; -import com.azure.search.documents.test.environment.models.HotelWithArray; -import com.azure.search.documents.test.environment.models.HotelWithEmptyInSynonymMaps; -import com.azure.search.documents.test.environment.models.HotelWithIgnoredFields; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.parallel.Execution; -import org.junit.jupiter.api.parallel.ExecutionMode; - -import java.time.OffsetDateTime; -import java.util.Arrays; -import java.util.Collections; -import java.util.Comparator; -import java.util.Date; -import java.util.List; -import java.util.Map; -import java.util.stream.Collectors; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNull; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.junit.jupiter.api.Assertions.assertTrue; - -@Execution(ExecutionMode.CONCURRENT) -public class FieldBuilderTests { - @Test - public void hotelSearchableThrowException() { - Exception exception = assertThrows(RuntimeException.class, - () -> SearchIndexClient.buildSearchFields(HotelSearchException.class, null)); - assertExceptionMassageAndDataType(exception, SearchFieldDataType.INT32, "getHotelId"); - } - - @Test - public void hotelListFieldSearchableThrowException() { - Exception exception = assertThrows(RuntimeException.class, - () -> SearchIndexClient.buildSearchFields(HotelSearchableExceptionOnList.class, null)); - assertExceptionMassageAndDataType(exception, SearchFieldDataType.collection(SearchFieldDataType.INT32), - "getPasscode"); - } - - @Test - public void hotelCircularDependencies() { - List actualFields - = sortByFieldName(SearchIndexClient.buildSearchFields(HotelCircularDependencies.class, null)); - List expectedFields = sortByFieldName(buildHotelCircularDependenciesModel()); - assertListFieldEquals(expectedFields, actualFields); - } - - @Test - public void hotelWithEmptySynonymMaps() { - // We cannot put null in the annotation. So no need to test null case. - List actualFields = SearchIndexClient.buildSearchFields(HotelWithEmptyInSynonymMaps.class, null); - - List expectedFields = Collections.singletonList( - new SearchField("tags", SearchFieldDataType.collection(SearchFieldDataType.STRING)).setSearchable(true) - .setKey(false) - .setStored(true) - .setHidden(false) - .setFilterable(false) - .setSortable(false) - .setFacetable(false) - .setSynonymMapNames(Arrays.asList("asynonymMaps", "maps"))); - - assertListFieldEquals(expectedFields, actualFields); - } - - @Test - public void hotelWithTwoDimensionalType() { - Exception exception = assertThrows(RuntimeException.class, - () -> SearchIndexClient.buildSearchFields(HotelTwoDimensional.class, null)); - assertExceptionMassageAndDataType(exception, null, "single-dimensional"); - } - - @Test - public void hotelAnalyzerException() { - Exception exception = assertThrows(RuntimeException.class, - () -> SearchIndexClient.buildSearchFields(HotelAnalyzerException.class, null)); - assertExceptionMassageAndDataType(exception, null, "either analyzer or both searchAnalyzer and indexAnalyzer"); - } - - @Test - public void hotelWithArrayType() { - List actualFields - = sortByFieldName(SearchIndexClient.buildSearchFields(HotelWithArray.class, null)); - List expectedFields = sortByFieldName(buildHotelWithArrayModel()); - assertListFieldEquals(expectedFields, actualFields); - } - - @Test - public void propertyRename() { - List actualFields - = sortByFieldName(SearchIndexClient.buildSearchFields(HotelRenameProperty.class, null)); - List expectedFieldNames = Arrays.asList("HotelName", "hotelId", "description"); - Collections.sort(expectedFieldNames); - assertEquals(expectedFieldNames.get(0), actualFields.get(0).getName()); - assertEquals(expectedFieldNames.get(1), actualFields.get(1).getName()); - assertEquals(expectedFieldNames.get(2), actualFields.get(2).getName()); - } - - @Test - public void ignoredPropertyName() { - List actualFields = SearchIndexClient.buildSearchFields(HotelWithIgnoredFields.class, null); - assertEquals(1, actualFields.size()); - assertEquals("notIgnoredName", actualFields.get(0).getName()); - } - - @Test - public void supportedFields() { - List fields = SearchIndexClient.buildSearchFields(AllSupportedFields.class, null); - - assertEquals(25, fields.size()); - - Map fieldToDataType - = fields.stream().collect(Collectors.toMap(SearchField::getName, SearchField::getType)); - - assertEquals(SearchFieldDataType.INT32, fieldToDataType.get("nullableInt")); - assertEquals(SearchFieldDataType.INT32, fieldToDataType.get("primitiveInt")); - assertEquals(SearchFieldDataType.INT64, fieldToDataType.get("nullableLong")); - assertEquals(SearchFieldDataType.INT64, fieldToDataType.get("primitiveLong")); - assertEquals(SearchFieldDataType.DOUBLE, fieldToDataType.get("nullableDouble")); - assertEquals(SearchFieldDataType.DOUBLE, fieldToDataType.get("primitiveDouble")); - assertEquals(SearchFieldDataType.BOOLEAN, fieldToDataType.get("nullableBoolean")); - assertEquals(SearchFieldDataType.BOOLEAN, fieldToDataType.get("primitiveBoolean")); - assertEquals(SearchFieldDataType.STRING, fieldToDataType.get("string")); - assertEquals(SearchFieldDataType.STRING, fieldToDataType.get("charSequence")); - assertEquals(SearchFieldDataType.STRING, fieldToDataType.get("nullableChar")); - assertEquals(SearchFieldDataType.STRING, fieldToDataType.get("primitiveChar")); - assertEquals(SearchFieldDataType.DATE_TIME_OFFSET, fieldToDataType.get("date")); - assertEquals(SearchFieldDataType.DATE_TIME_OFFSET, fieldToDataType.get("offsetDateTime")); - assertEquals(SearchFieldDataType.GEOGRAPHY_POINT, fieldToDataType.get("geoPoint")); - assertEquals(SearchFieldDataType.collection(SearchFieldDataType.INT32), fieldToDataType.get("intArray")); - assertEquals(SearchFieldDataType.collection(SearchFieldDataType.INT32), fieldToDataType.get("intList")); - assertEquals(SearchFieldDataType.collection(SearchFieldDataType.SINGLE), fieldToDataType.get("floatArray")); - assertEquals(SearchFieldDataType.collection(SearchFieldDataType.SINGLE), fieldToDataType.get("floatList")); - assertEquals(SearchFieldDataType.INT16, fieldToDataType.get("nullableShort")); - assertEquals(SearchFieldDataType.INT16, fieldToDataType.get("primitiveShort")); - assertEquals(SearchFieldDataType.SBYTE, fieldToDataType.get("nullableByte")); - assertEquals(SearchFieldDataType.SBYTE, fieldToDataType.get("primitiveByte")); - assertEquals(SearchFieldDataType.collection(SearchFieldDataType.SBYTE), fieldToDataType.get("byteArray")); - assertEquals(SearchFieldDataType.collection(SearchFieldDataType.SBYTE), fieldToDataType.get("byteList")); - - } - - @SuppressWarnings({ "unused", "UseOfObsoleteDateTimeApi" }) - private static final class AllSupportedFields { - // 1. name = 'nullableInt', OData type = INT32 - private Integer nullableInt; - - public Integer getNullableInt() { - return nullableInt; - } - - // 2. name = 'primitiveInt', OData type = INT32 - private int primitiveInt; - - public int getPrimitiveInt() { - return primitiveInt; - } - - // 3. name = 'nullableLong', OData type = INT64 - private Long nullableLong; - - public Long getNullableLong() { - return nullableLong; - } - - // 4. name = 'primitiveLong', OData type = INT64 - private long primitiveLong; - - public long getPrimitiveLong() { - return primitiveLong; - } - - // 5. name = 'nullableDouble', OData type = DOUBLE - private Double nullableDouble; - - public Double getNullableDouble() { - return nullableDouble; - } - - // 6. name = 'primitiveDouble', OData type = DOUBLE - private double primitiveDouble; - - public double getPrimitiveDouble() { - return primitiveDouble; - } - - // 7. name = 'nullableBoolean', OData type = BOOLEAN - private Boolean nullableBoolean; - - public Boolean getNullableBoolean() { - return nullableBoolean; - } - - // 8. name = 'primitiveBoolean', OData type = BOOLEAN - private boolean primitiveBoolean; - - public boolean isPrimitiveBoolean() { - return primitiveBoolean; - } - - // 9. name = 'string', OData type = STRING - private String string; - - public String getString() { - return string; - } - - // 10. name = 'charSequence', OData type = STRING - private CharSequence charSequence; - - public CharSequence getCharSequence() { - return charSequence; - } - - // 11. name = 'nullableChar', OData type = STRING - private Character nullableChar; - - public Character getNullableChar() { - return nullableChar; - } - - // 12. name = 'primitiveChar', OData type = STRING - private char primitiveChar; - - public char getPrimitiveChar() { - return primitiveChar; - } - - // 13. name = 'date', OData type = DATE_TIME_OFFSET - private Date date; - - public Date getDate() { - return date; - } - - // 14. name = 'offsetDateTime', OData type = DATE_TIME_OFFSET - private OffsetDateTime offsetDateTime; - - public OffsetDateTime getOffsetDateTime() { - return offsetDateTime; - } - - // 15. name = 'geoPoint', OData type = GEOGRAPHY_POINT - private GeoPoint geoPoint; - - public GeoPoint getGeoPoint() { - return geoPoint; - } - - // 16. name = 'intArray', OData type = COMPLEX - private int[] intArray; - - public int[] getIntArray() { - return intArray; - } - - // 17. name = 'intList', OData type = COMPLEX - private List intList; - - public List getIntList() { - return intList; - } - - // 18. name = 'floatList', OData type = COMPLEX - private List floatList; - - public List getFloatList() { - return floatList; - } - - // 19. name = 'floatArray', OData type = COMPLEX - private Float[] floatArray; - - public Float[] getFloatArray() { - return floatArray; - } - - // 20. name = 'primitiveShort', OData type = INT16 - private short primitiveShort; - - public short getPrimitiveShort() { - return primitiveShort; - } - - // 21. name = 'nullableShort', OData type = INT16 - private Short nullableShort; - - public Short getNullableShort() { - return nullableShort; - } - - // 22. name = 'primitiveByte', OData type = SBYTE - private byte primitiveByte; - - public byte getPrimitiveByte() { - return primitiveByte; - } - - // 23. name = 'nullableByte', OData type = SBYTE - private Byte nullableByte; - - public Byte getNullableByte() { - return nullableByte; - } - - // 24. name = 'byteArray', OData type = COMPLEX - private byte[] byteArray; - - public byte[] getByteArray() { - return byteArray; - } - - // 25. name = 'byteList', OData type = COMPLEX - private List byteList; - - public List getByteList() { - return byteList; - } - } - - @Test - public void onlyAnalyzerNameSetsOnlyAnalyzerName() { - List fields = SearchIndexClient.buildSearchFields(OnlyAnalyzerName.class, null); - - assertEquals(1, fields.size()); - - SearchField field = fields.get(0); - assertEquals("onlyAnalyzer", field.getAnalyzerName().toString()); - assertNull(field.getIndexAnalyzerName()); - assertNull(field.getSearchAnalyzerName()); - } - - @SuppressWarnings("unused") - public static final class OnlyAnalyzerName { - @SearchableField(analyzerName = "onlyAnalyzer") - public String onlyAnalyzer; - } - - @Test - public void indexAndSearchAnalyzersSetCorrectly() { - List fields = SearchIndexClient.buildSearchFields(IndexAndSearchAnalyzerNames.class, null); - - assertEquals(1, fields.size()); - - SearchField field = fields.get(0); - assertNull(field.getAnalyzerName()); - assertEquals("indexAnalyzer", field.getIndexAnalyzerName().toString()); - assertEquals("searchAnalyzer", field.getSearchAnalyzerName().toString()); - } - - @SuppressWarnings("unused") - public static final class IndexAndSearchAnalyzerNames { - @SearchableField(indexAnalyzerName = "indexAnalyzer", searchAnalyzerName = "searchAnalyzer") - public String indexAndSearchAnalyzer; - } - - @Test - public void vectorSearchField() { - List fields = SearchIndexClient.buildSearchFields(VectorSearchField.class, null); - - assertEquals(1, fields.size()); - - SearchField field = fields.get(0); - assertEquals(1536, field.getVectorSearchDimensions()); - assertEquals("myprofile", field.getVectorSearchProfileName()); - } - - @SuppressWarnings("unused") - public static final class VectorSearchField { - @SearchableField(vectorSearchDimensions = 1536, vectorSearchProfileName = "myprofile") - public List vectorSearchField; - } - - @Test - public void vectorFieldMissingDimensions() { - RuntimeException ex = assertThrows(RuntimeException.class, - () -> SearchIndexClient.buildSearchFields(VectorFieldMissingDimensions.class, null)); - - assertTrue(ex.getMessage().contains("Please specify both vectorSearchDimensions and vectorSearchProfile")); - } - - @SuppressWarnings("unused") - public static final class VectorFieldMissingDimensions { - @SearchableField(vectorSearchProfileName = "myprofile") - public List vectorSearchField; - } - - @Test - public void vectorFieldMissingProfile() { - RuntimeException ex = assertThrows(RuntimeException.class, - () -> SearchIndexClient.buildSearchFields(VectorFieldMissingProfile.class, null)); - - assertTrue(ex.getMessage().contains("Please specify both vectorSearchDimensions and vectorSearchProfile")); - } - - @SuppressWarnings("unused") - public static final class VectorFieldMissingProfile { - @SearchableField(vectorSearchDimensions = 1536) - public List vectorSearchField; - } - - private void assertListFieldEquals(List expected, List actual) { - assertEquals(expected.size(), actual.size()); - for (int i = 0; i < expected.size(); i++) { - TestHelpers.assertObjectEquals(expected.get(i), actual.get(i)); - } - } - - private void assertExceptionMassageAndDataType(Exception exception, SearchFieldDataType dataType, String msg) { - assertTrue(exception.getMessage().contains(msg)); - if (dataType != null) { - assertTrue(exception.getMessage().contains(dataType.toString())); - } - } - - private List buildHotelCircularDependenciesModel() { - SearchField homeAddress - = new SearchField("homeAddress", SearchFieldDataType.COMPLEX).setFields(buildHotelInAddress()); - SearchField billingAddress - = new SearchField("billingAddress", SearchFieldDataType.COMPLEX).setFields(buildHotelInAddress()); - return Arrays.asList(homeAddress, billingAddress); - } - - private List buildHotelInAddress() { - SearchField hotel = new SearchField("hotel", SearchFieldDataType.COMPLEX); - return Collections.singletonList(hotel); - } - - private List buildHotelWithArrayModel() { - SearchField hotelId = new SearchField("hotelId", SearchFieldDataType.STRING).setKey(true) - .setSortable(true) - .setStored(true) - .setHidden(false) - .setSearchable(false) - .setFacetable(false) - .setFilterable(false); - SearchField tags - = new SearchField("tags", SearchFieldDataType.collection(SearchFieldDataType.STRING)).setKey(false) - .setHidden(false) - .setStored(true) - .setSearchable(true) - .setSortable(false) - .setFilterable(false) - .setFacetable(false); - return Arrays.asList(hotelId, tags); - } - - private List sortByFieldName(List fields) { - fields.sort(Comparator.comparing(SearchField::getName)); - return fields; - } -} diff --git a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/indexes/IndexManagementTests.java b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/indexes/IndexManagementTests.java deleted file mode 100644 index 8c2a21e65459..000000000000 --- a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/indexes/IndexManagementTests.java +++ /dev/null @@ -1,854 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -package com.azure.search.documents.indexes; - -import com.azure.core.exception.HttpResponseException; -import com.azure.core.http.rest.Response; -import com.azure.core.test.TestMode; -import com.azure.core.util.Context; -import com.azure.search.documents.SearchTestBase; -import com.azure.search.documents.TestHelpers; -import com.azure.search.documents.indexes.models.CorsOptions; -import com.azure.search.documents.indexes.models.LexicalAnalyzerName; -import com.azure.search.documents.indexes.models.MagnitudeScoringFunction; -import com.azure.search.documents.indexes.models.MagnitudeScoringParameters; -import com.azure.search.documents.indexes.models.ScoringFunctionAggregation; -import com.azure.search.documents.indexes.models.ScoringFunctionInterpolation; -import com.azure.search.documents.indexes.models.ScoringProfile; -import com.azure.search.documents.indexes.models.SearchField; -import com.azure.search.documents.indexes.models.SearchFieldDataType; -import com.azure.search.documents.indexes.models.SearchIndex; -import com.azure.search.documents.indexes.models.SearchIndexStatistics; -import com.azure.search.documents.indexes.models.SearchSuggester; -import com.azure.search.documents.indexes.models.SynonymMap; -import org.junit.jupiter.api.AfterAll; -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.Test; - -import reactor.core.publisher.Mono; -import reactor.test.StepVerifier; -import reactor.util.function.Tuple2; -import reactor.util.function.Tuples; - -import java.net.HttpURLConnection; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.NoSuchElementException; -import java.util.Objects; -import java.util.Set; -import java.util.function.Function; -import java.util.stream.Collectors; - -import static com.azure.search.documents.TestHelpers.HOTEL_INDEX_NAME; -import static com.azure.search.documents.TestHelpers.assertHttpResponseException; -import static com.azure.search.documents.TestHelpers.assertObjectEquals; -import static com.azure.search.documents.TestHelpers.verifyHttpResponseError; -import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertInstanceOf; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertNull; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.junit.jupiter.api.Assertions.assertTrue; - -public class IndexManagementTests extends SearchTestBase { - private static SearchIndexClient sharedIndexClient; - private static SynonymMap sharedSynonymMap; - - private final List indexesToDelete = new ArrayList<>(); - - private SearchIndexClient client; - private SearchIndexAsyncClient asyncClient; - - @BeforeAll - public static void setupSharedResources() { - sharedSynonymMap = new SynonymMap("sharedhotelmotel").setSynonyms("hotel,motel"); - - if (TEST_MODE == TestMode.PLAYBACK) { - return; - } - - sharedIndexClient = new SearchIndexClientBuilder().endpoint(ENDPOINT) - .credential(TestHelpers.getTestTokenCredential()) - .buildClient(); - - sharedSynonymMap = sharedIndexClient.createSynonymMap(sharedSynonymMap); - } - - @AfterAll - public static void cleanupSharedResources() { - if (TEST_MODE == TestMode.PLAYBACK) { - return; // Running in PLAYBACK, no need to run. - } - - sharedIndexClient.deleteSynonymMap(sharedSynonymMap.getName()); - } - - @Override - protected void beforeTest() { - super.beforeTest(); - - client = getSearchIndexClientBuilder(true).buildClient(); - asyncClient = getSearchIndexClientBuilder(false).buildAsyncClient(); - } - - @Override - protected void afterTest() { - super.afterTest(); - - for (String index : indexesToDelete) { - client.deleteIndex(index); - } - } - - @Test - public void createAndGetIndexReturnsCorrectDefinitionSync() { - SearchIndex index = createTestIndex(null); - SearchIndex createdIndex = client.createIndex(index); - indexesToDelete.add(createdIndex.getName()); - - assertObjectEquals(index, createdIndex, true, "etag"); - - SearchIndex getIndex = client.getIndex(index.getName()); - assertObjectEquals(index, getIndex, true, "etag"); - } - - @Test - public void createAndGetIndexReturnsCorrectDefinitionAsync() { - SearchIndex index = createTestIndex(null); - - StepVerifier.create(asyncClient.createIndex(index)).assertNext(createdIndex -> { - indexesToDelete.add(createdIndex.getName()); - assertObjectEquals(index, createdIndex, true, "etag"); - }).verifyComplete(); - - StepVerifier.create(asyncClient.getIndex(index.getName())) - .assertNext(getIndex -> assertObjectEquals(index, getIndex, true, "etag")) - .verifyComplete(); - } - - @Test - public void createAndGetIndexReturnsCorrectDefinitionWithResponseSync() { - SearchIndex index = createTestIndex("hotel2"); - Response createIndexResponse = client.createIndexWithResponse(index, Context.NONE); - indexesToDelete.add(createIndexResponse.getValue().getName()); - - assertObjectEquals(index, createIndexResponse.getValue(), true, "etag"); - - Response getIndexResponse = client.getIndexWithResponse(index.getName(), Context.NONE); - assertObjectEquals(index, getIndexResponse.getValue(), true, "etag"); - } - - @Test - public void createAndGetIndexReturnsCorrectDefinitionWithResponseAsync() { - SearchIndex index = createTestIndex("hotel2"); - - StepVerifier.create(asyncClient.createIndexWithResponse(index)).assertNext(response -> { - indexesToDelete.add(response.getValue().getName()); - - assertObjectEquals(index, response.getValue(), true, "etag"); - }).verifyComplete(); - - StepVerifier.create(asyncClient.getIndexWithResponse(index.getName())) - .assertNext(response -> assertObjectEquals(index, response.getValue(), true, "etag")) - .verifyComplete(); - } - - @Test - public void createIndexReturnsCorrectDefaultValuesSync() { - SearchIndex index = createTestIndex(null).setCorsOptions(new CorsOptions(Collections.singletonList("*"))) - .setScoringProfiles(new ScoringProfile("MyProfile") - .setFunctions(new MagnitudeScoringFunction("Rating", 2.0, new MagnitudeScoringParameters(1, 4)))); - SearchIndex indexResponse = client.createIndex(index); - indexesToDelete.add(indexResponse.getName()); - - ScoringProfile scoringProfile = indexResponse.getScoringProfiles().get(0); - assertNull(indexResponse.getCorsOptions().getMaxAgeInSeconds()); - assertEquals(ScoringFunctionAggregation.SUM, scoringProfile.getFunctionAggregation()); - assertEquals(ScoringFunctionInterpolation.LINEAR, scoringProfile.getFunctions().get(0).getInterpolation()); - } - - @Test - public void createIndexReturnsCorrectDefaultValuesAsync() { - SearchIndex index = createTestIndex(null).setCorsOptions(new CorsOptions(Collections.singletonList("*"))) - .setScoringProfiles(new ScoringProfile("MyProfile") - .setFunctions(new MagnitudeScoringFunction("Rating", 2.0, new MagnitudeScoringParameters(1, 4)))); - - StepVerifier.create(asyncClient.createIndex(index)).assertNext(created -> { - indexesToDelete.add(created.getName()); - - ScoringProfile scoringProfile = created.getScoringProfiles().get(0); - assertNull(created.getCorsOptions().getMaxAgeInSeconds()); - assertEquals(ScoringFunctionAggregation.SUM, scoringProfile.getFunctionAggregation()); - assertEquals(ScoringFunctionInterpolation.LINEAR, scoringProfile.getFunctions().get(0).getInterpolation()); - }).verifyComplete(); - } - - @Test - public void createIndexFailsWithUsefulMessageOnUserErrorSync() { - String indexName = HOTEL_INDEX_NAME; - SearchIndex index = new SearchIndex(indexName) - .setFields(new SearchField("HotelId", SearchFieldDataType.STRING).setKey(false)); - String expectedMessage = String - .format("Found 0 key fields in index '%s'. " + "Each index must have exactly one key field.", indexName); - - HttpResponseException ex = assertThrows(HttpResponseException.class, () -> client.createIndex(index)); - assertEquals(HttpURLConnection.HTTP_BAD_REQUEST, ex.getResponse().getStatusCode()); - assertTrue(ex.getMessage().contains(expectedMessage), "Expected exception to contain message '" - + expectedMessage + "' but the message was '" + ex.getMessage() + "'."); - } - - @Test - public void createIndexFailsWithUsefulMessageOnUserErrorAsync() { - String indexName = HOTEL_INDEX_NAME; - SearchIndex index = new SearchIndex(indexName) - .setFields(new SearchField("HotelId", SearchFieldDataType.STRING).setKey(false)); - String expectedMessage = String - .format("Found 0 key fields in index '%s'. " + "Each index must have exactly one key field.", indexName); - - StepVerifier.create(asyncClient.createIndex(index)).verifyErrorSatisfies(throwable -> { - HttpResponseException ex = assertInstanceOf(HttpResponseException.class, throwable); - assertEquals(HttpURLConnection.HTTP_BAD_REQUEST, ex.getResponse().getStatusCode()); - assertTrue(ex.getMessage().contains(expectedMessage), "Expected exception to contain message '" - + expectedMessage + "' but the message was '" + ex.getMessage() + "'."); - }); - } - - @Test - public void getIndexThrowsOnNotFoundSync() { - assertHttpResponseException(() -> client.getIndex("thisindexdoesnotexist"), HttpURLConnection.HTTP_NOT_FOUND, - "No index with the name 'thisindexdoesnotexist' was found in the service"); - } - - @Test - public void getIndexThrowsOnNotFoundAsync() { - StepVerifier.create(asyncClient.getIndex("thisindexdoesnotexist")) - .verifyErrorSatisfies(throwable -> verifyHttpResponseError(throwable, HttpURLConnection.HTTP_NOT_FOUND, - "No index with the name 'thisindexdoesnotexist' was found in the service")); - } - - @Test - public void deleteIndexIfNotChangedWorksOnlyOnCurrentResourceSync() { - SearchIndex indexToCreate = createTestIndex(null); - - // Create the resource in the search service - SearchIndex originalIndex - = client.createOrUpdateIndexWithResponse(indexToCreate, false, false, Context.NONE).getValue(); - - // Update the resource, the eTag will be changed - SearchIndex updatedIndex - = client - .createOrUpdateIndexWithResponse( - originalIndex.setCorsOptions(new CorsOptions(Collections.singletonList("https://test.com/"))), - false, false, Context.NONE) - .getValue(); - - HttpResponseException ex = assertThrows(HttpResponseException.class, - () -> client.deleteIndexWithResponse(originalIndex, true, Context.NONE)); - assertEquals(HttpURLConnection.HTTP_PRECON_FAILED, ex.getResponse().getStatusCode()); - - assertDoesNotThrow(() -> client.deleteIndexWithResponse(updatedIndex, true, Context.NONE)); - } - - @Test - public void deleteIndexIfNotChangedWorksOnlyOnCurrentResourceAsync() { - SearchIndex indexToCreate = createTestIndex(null); - - // Create the resource in the search service - SearchIndex originalIndex = asyncClient.createOrUpdateIndexWithResponse(indexToCreate, false, false) - .map(Response::getValue) - .blockOptional() - .orElseThrow(NoSuchElementException::new); - - // Update the resource, the eTag will be changed - SearchIndex updatedIndex = asyncClient.createOrUpdateIndexWithResponse( - originalIndex.setCorsOptions(new CorsOptions(Collections.singletonList("https://test.com/"))), false, false) - .map(Response::getValue) - .block(); - - StepVerifier.create(asyncClient.deleteIndexWithResponse(originalIndex, true)) - .verifyErrorSatisfies(throwable -> { - HttpResponseException ex = assertInstanceOf(HttpResponseException.class, throwable); - assertEquals(HttpURLConnection.HTTP_PRECON_FAILED, ex.getResponse().getStatusCode()); - }); - - StepVerifier.create(asyncClient.deleteIndexWithResponse(updatedIndex, true)) - .expectNextCount(1) - .verifyComplete(); - } - - @Test - public void deleteIndexIfExistsWorksOnlyWhenResourceExistsSync() { - SearchIndex index - = client.createOrUpdateIndexWithResponse(createTestIndex(null), false, false, Context.NONE).getValue(); - - client.deleteIndexWithResponse(index, true, Context.NONE); - - // Try to delete again and expect to fail - HttpResponseException ex = assertThrows(HttpResponseException.class, - () -> client.deleteIndexWithResponse(index, true, Context.NONE)); - assertEquals(HttpURLConnection.HTTP_PRECON_FAILED, ex.getResponse().getStatusCode()); - } - - @Test - public void deleteIndexIfExistsWorksOnlyWhenResourceExistsAsync() { - SearchIndex index = asyncClient.createOrUpdateIndexWithResponse(createTestIndex(null), false, false) - .map(Response::getValue) - .block(); - - asyncClient.deleteIndexWithResponse(index, true).block(); - - // Try to delete again and expect to fail - StepVerifier.create(asyncClient.deleteIndexWithResponse(index, true)).verifyErrorSatisfies(throwable -> { - HttpResponseException ex = assertInstanceOf(HttpResponseException.class, throwable); - assertEquals(HttpURLConnection.HTTP_PRECON_FAILED, ex.getResponse().getStatusCode()); - }); - } - - @Test - public void deleteIndexIsIdempotentSync() { - SearchIndex index = new SearchIndex(HOTEL_INDEX_NAME) - .setFields(new SearchField("HotelId", SearchFieldDataType.STRING).setKey(true)); - Response deleteResponse = client.deleteIndexWithResponse(index, false, Context.NONE); - assertEquals(HttpURLConnection.HTTP_NOT_FOUND, deleteResponse.getStatusCode()); - - Response createResponse = client.createIndexWithResponse(index, Context.NONE); - assertEquals(HttpURLConnection.HTTP_CREATED, createResponse.getStatusCode()); - - // Delete the same index twice - deleteResponse = client.deleteIndexWithResponse(index, false, Context.NONE); - assertEquals(HttpURLConnection.HTTP_NO_CONTENT, deleteResponse.getStatusCode()); - - deleteResponse = client.deleteIndexWithResponse(index, false, Context.NONE); - assertEquals(HttpURLConnection.HTTP_NOT_FOUND, deleteResponse.getStatusCode()); - } - - @Test - public void deleteIndexIsIdempotentAsync() { - SearchIndex index = new SearchIndex(HOTEL_INDEX_NAME) - .setFields(new SearchField("HotelId", SearchFieldDataType.STRING).setKey(true)); - - StepVerifier.create(asyncClient.deleteIndexWithResponse(index, false)) - .assertNext(response -> assertEquals(HttpURLConnection.HTTP_NOT_FOUND, response.getStatusCode())) - .verifyComplete(); - - StepVerifier.create(asyncClient.createIndexWithResponse(index)) - .assertNext(response -> assertEquals(HttpURLConnection.HTTP_CREATED, response.getStatusCode())) - .verifyComplete(); - - // Delete the same index twice - StepVerifier.create(asyncClient.deleteIndexWithResponse(index, false)) - .assertNext(response -> assertEquals(HttpURLConnection.HTTP_NO_CONTENT, response.getStatusCode())) - .verifyComplete(); - - StepVerifier.create(asyncClient.deleteIndexWithResponse(index, false)) - .assertNext(response -> assertEquals(HttpURLConnection.HTTP_NOT_FOUND, response.getStatusCode())) - .verifyComplete(); - } - - @Test - public void canCreateAndListIndexesSyncAndAsync() { - SearchIndex index1 = createTestIndex("a" + randomIndexName(HOTEL_INDEX_NAME)); - SearchIndex index2 = createTestIndex("b" + randomIndexName(HOTEL_INDEX_NAME)); - - client.createIndex(index1); - indexesToDelete.add(index1.getName()); - client.createIndex(index2); - indexesToDelete.add(index2.getName()); - - Map expectedIndexes = new HashMap<>(); - expectedIndexes.put(index1.getName(), index1); - expectedIndexes.put(index2.getName(), index2); - - Map actualIndexes - = client.listIndexes().stream().collect(Collectors.toMap(SearchIndex::getName, si -> si)); - - compareMaps(expectedIndexes, actualIndexes, (expected, actual) -> assertObjectEquals(expected, actual, true), - false); - - StepVerifier.create(asyncClient.listIndexes().collectMap(SearchIndex::getName)) - .assertNext(actualIndexes2 -> compareMaps(expectedIndexes, actualIndexes2, - (expected, actual) -> assertObjectEquals(expected, actual, true), false)) - .verifyComplete(); - } - - @Test - public void canListIndexesWithSelectedFieldSyncAndAsync() { - SearchIndex index1 = createTestIndex("a" + randomIndexName(HOTEL_INDEX_NAME)); - SearchIndex index2 = createTestIndex("b" + randomIndexName(HOTEL_INDEX_NAME)); - - client.createIndex(index1); - indexesToDelete.add(index1.getName()); - client.createIndex(index2); - indexesToDelete.add(index2.getName()); - - Set expectedIndexNames = new HashSet<>(Arrays.asList(index1.getName(), index2.getName())); - Set actualIndexNames = client.listIndexNames(Context.NONE).stream().collect(Collectors.toSet()); - - // Only check that listing returned the expected index names. Don't check the number of indexes returned as - // other tests may have created indexes. - assertTrue(actualIndexNames.containsAll(expectedIndexNames)); - - StepVerifier.create(asyncClient.listIndexNames().collect(Collectors.toSet())) - .assertNext(actualIndexNames2 -> assertTrue(actualIndexNames2.containsAll(expectedIndexNames))) - .verifyComplete(); - } - - @Test - public void canAddSynonymFieldPropertySync() { - SearchIndex index = new SearchIndex(HOTEL_INDEX_NAME).setFields(Arrays.asList( - new SearchField("HotelId", SearchFieldDataType.STRING).setKey(true), - new SearchField("HotelName", SearchFieldDataType.STRING).setSynonymMapNames(sharedSynonymMap.getName()))); - - SearchIndex createdIndex = client.createIndex(index); - indexesToDelete.add(createdIndex.getName()); - - List actualSynonym = index.getFields().get(1).getSynonymMapNames(); - List expectedSynonym = createdIndex.getFields().get(1).getSynonymMapNames(); - assertEquals(actualSynonym, expectedSynonym); - } - - @Test - public void canAddSynonymFieldPropertyAsync() { - SearchIndex index = new SearchIndex(HOTEL_INDEX_NAME).setFields(Arrays.asList( - new SearchField("HotelId", SearchFieldDataType.STRING).setKey(true), - new SearchField("HotelName", SearchFieldDataType.STRING).setSynonymMapNames(sharedSynonymMap.getName()))); - - StepVerifier.create(asyncClient.createIndex(index)).assertNext(createdIndex -> { - indexesToDelete.add(createdIndex.getName()); - - List actualSynonym = index.getFields().get(1).getSynonymMapNames(); - List expectedSynonym = createdIndex.getFields().get(1).getSynonymMapNames(); - assertEquals(actualSynonym, expectedSynonym); - }).verifyComplete(); - } - - @Test - public void canUpdateSynonymFieldPropertySync() { - // Create an index - SearchIndex index = createTestIndex(null); - SearchField hotelNameField = getFieldByName(index, "HotelName"); - hotelNameField.setSynonymMapNames(sharedSynonymMap.getName()); - client.createIndex(index); - indexesToDelete.add(index.getName()); - - // Update an existing index - SearchIndex existingIndex = client.getIndex(index.getName()); - hotelNameField = getFieldByName(existingIndex, "HotelName"); - hotelNameField.setSynonymMapNames(Collections.emptyList()); - - SearchIndex updatedIndex - = client.createOrUpdateIndexWithResponse(existingIndex, true, false, Context.NONE).getValue(); - assertObjectEquals(existingIndex, updatedIndex, true, "etag", "@odata.etag"); - } - - @Test - public void canUpdateSynonymFieldPropertyAsync() { - // Create an index - SearchIndex index = createTestIndex(null); - SearchField hotelNameField = getFieldByName(index, "HotelName"); - hotelNameField.setSynonymMapNames(sharedSynonymMap.getName()); - asyncClient.createIndex(index).block(); - indexesToDelete.add(index.getName()); - - // Update an existing index - Mono> getAndUpdateIndexMono - = asyncClient.getIndex(index.getName()).flatMap(existingIndex -> { - getFieldByName(existingIndex, "HotelName").setSynonymMapNames(Collections.emptyList()); - - return asyncClient.createOrUpdateIndexWithResponse(existingIndex, true, false) - .map(response -> Tuples.of(existingIndex, response.getValue())); - }); - - StepVerifier.create(getAndUpdateIndexMono) - .assertNext(indexes -> assertObjectEquals(indexes.getT1(), indexes.getT2(), true, "etag", "@odata.etag")) - .verifyComplete(); - } - - @Test - public void canUpdateIndexDefinitionSync() { - SearchIndex fullFeaturedIndex = createTestIndex(null); - - // Start out with no scoring profiles and different CORS options. - SearchIndex initialIndex = createTestIndex(fullFeaturedIndex.getName()); - initialIndex.setScoringProfiles(new ArrayList<>()) - .setDefaultScoringProfile(null) - .setCorsOptions(mutateCorsOptionsInIndex(initialIndex, Collections.singletonList("*")).getCorsOptions()); - - SearchIndex index = client.createIndex(initialIndex); - indexesToDelete.add(index.getName()); - - // Now update the index. - List allowedOrigins = fullFeaturedIndex.getCorsOptions().getAllowedOrigins(); - index.setScoringProfiles(fullFeaturedIndex.getScoringProfiles()) - .setDefaultScoringProfile(fullFeaturedIndex.getDefaultScoringProfile()) - .setCorsOptions(mutateCorsOptionsInIndex(index, allowedOrigins).getCorsOptions()); - - SearchIndex updatedIndex = client.createOrUpdateIndex(index); - - assertObjectEquals(fullFeaturedIndex, updatedIndex, true, "etag", "@odata.etag"); - - // Modify the fields on an existing index - SearchIndex existingIndex = client.getIndex(fullFeaturedIndex.getName()); - - SearchField tagsField = getFieldByName(existingIndex, "Description_Custom"); - tagsField.setHidden(true) - .setSearchAnalyzerName(LexicalAnalyzerName.WHITESPACE) - .setSynonymMapNames(sharedSynonymMap.getName()); - - SearchField hotelWebSiteField - = new SearchField("HotelWebsite", SearchFieldDataType.STRING).setSearchable(Boolean.TRUE) - .setFilterable(Boolean.TRUE); - existingIndex.getFields().add(hotelWebSiteField); - - SearchField hotelNameField = getFieldByName(existingIndex, "HotelName"); - hotelNameField.setHidden(true); - - updatedIndex = client.createOrUpdateIndexWithResponse(existingIndex, true, false, Context.NONE).getValue(); - - assertObjectEquals(existingIndex, updatedIndex, true, "etag", "@odata.etag"); - } - - @Test - public void canUpdateIndexDefinitionAsync() { - SearchIndex fullFeaturedIndex = createTestIndex(null); - - // Start out with no scoring profiles and different CORS options. - SearchIndex initialIndex = mutateCorsOptionsInIndex( - createTestIndex(fullFeaturedIndex.getName()).setScoringProfiles(Collections.emptyList()) - .setDefaultScoringProfile(null)); - - SearchIndex index - = asyncClient.createIndex(initialIndex).blockOptional().orElseThrow(NoSuchElementException::new); - indexesToDelete.add(index.getName()); - - // Now update the index. - List allowedOrigins = fullFeaturedIndex.getCorsOptions().getAllowedOrigins(); - index.setScoringProfiles(fullFeaturedIndex.getScoringProfiles()) - .setDefaultScoringProfile(fullFeaturedIndex.getDefaultScoringProfile()) - .setCorsOptions(mutateCorsOptionsInIndex(index, allowedOrigins).getCorsOptions()); - - StepVerifier.create(asyncClient.createOrUpdateIndex(index)) - .assertNext( - updatedIndex -> assertObjectEquals(fullFeaturedIndex, updatedIndex, true, "etag", "@odata.etag")) - .verifyComplete(); - - // Modify the fields on an existing index - SearchIndex existingIndex = asyncClient.getIndex(fullFeaturedIndex.getName()) - .blockOptional() - .orElseThrow(NoSuchElementException::new); - - SearchField tagsField = getFieldByName(existingIndex, "Description_Custom"); - tagsField.setHidden(true) - .setSearchAnalyzerName(LexicalAnalyzerName.WHITESPACE) - .setSynonymMapNames(sharedSynonymMap.getName()); - - SearchField hotelWebSiteField - = new SearchField("HotelWebsite", SearchFieldDataType.STRING).setSearchable(Boolean.TRUE) - .setFilterable(Boolean.TRUE); - existingIndex.getFields().add(hotelWebSiteField); - - SearchField hotelNameField = getFieldByName(existingIndex, "HotelName"); - hotelNameField.setHidden(true); - - StepVerifier.create(asyncClient.createOrUpdateIndexWithResponse(existingIndex, true, false)) - .assertNext(response -> assertObjectEquals(existingIndex, response.getValue(), true, "etag", "@odata.etag")) - .verifyComplete(); - } - - @Test - public void canUpdateSuggesterWithNewIndexFieldsSync() { - SearchIndex index = createTestIndex(null); - client.createIndex(index); - indexesToDelete.add(index.getName()); - - SearchIndex existingIndex = client.getIndex(index.getName()); - - existingIndex.getFields() - .addAll(Arrays.asList(new SearchField("HotelAmenities", SearchFieldDataType.STRING), - new SearchField("HotelRewards", SearchFieldDataType.STRING))); - existingIndex.setSuggesters(new SearchSuggester("Suggestion", Arrays.asList("HotelAmenities", "HotelRewards"))); - - SearchIndex updatedIndex - = client.createOrUpdateIndexWithResponse(existingIndex, true, false, Context.NONE).getValue(); - assertObjectEquals(existingIndex, updatedIndex, true, "etag", "@odata.etag"); - } - - @Test - public void canUpdateSuggesterWithNewIndexFieldsAsync() { - Mono> createAndUpdateIndexMono - = asyncClient.createIndex(createTestIndex(null)).flatMap(index -> { - indexesToDelete.add(index.getName()); - index.getFields() - .addAll(Arrays.asList(new SearchField("HotelAmenities", SearchFieldDataType.STRING), - new SearchField("HotelRewards", SearchFieldDataType.STRING))); - index.setSuggesters(new SearchSuggester("Suggestion", Arrays.asList("HotelAmenities", "HotelRewards"))); - - return asyncClient.createOrUpdateIndexWithResponse(index, true, false) - .map(response -> Tuples.of(index, response.getValue())); - }); - - StepVerifier.create(createAndUpdateIndexMono) - .assertNext(indexes -> assertObjectEquals(indexes.getT1(), indexes.getT2(), true, "etag", "@odata.etag")) - .verifyComplete(); - } - - @Test - public void createOrUpdateIndexThrowsWhenUpdatingSuggesterWithExistingIndexFieldsSync() { - SearchIndex index = createTestIndex(null); - client.createIndex(index); - indexesToDelete.add(index.getName()); - - SearchIndex existingIndex = client.getIndex(index.getName()); - String existingFieldName = "Category"; - existingIndex.setSuggesters(new SearchSuggester("Suggestion", Collections.singletonList(existingFieldName))); - - assertHttpResponseException(() -> client.createOrUpdateIndex(existingIndex), HttpURLConnection.HTTP_BAD_REQUEST, - "Fields that were already present in an index (" + existingFieldName + ") cannot be referenced by a new " - + "suggester. Only new fields added in the same index update operation are allowed."); - } - - @Test - public void createOrUpdateIndexThrowsWhenUpdatingSuggesterWithExistingIndexFieldsAsync() { - String existingFieldName = "Category"; - Mono createThenInvalidUpdateMono - = asyncClient.createIndex(createTestIndex(null)).flatMap(index -> { - indexesToDelete.add(index.getName()); - - return asyncClient.createOrUpdateIndex(index - .setSuggesters(new SearchSuggester("Suggestion", Collections.singletonList(existingFieldName)))); - }); - - StepVerifier.create(createThenInvalidUpdateMono) - .verifyErrorSatisfies(throwable -> verifyHttpResponseError(throwable, HttpURLConnection.HTTP_BAD_REQUEST, - "Fields that were already present in an index (" + existingFieldName + ") cannot be referenced by a " - + "new suggester. Only new fields added in the same index update operation are allowed.")); - } - - @Test - public void createOrUpdateIndexCreatesWhenIndexDoesNotExistSync() { - SearchIndex expected = createTestIndex(null); - - SearchIndex actual = client.createOrUpdateIndex(expected); - indexesToDelete.add(actual.getName()); - assertObjectEquals(expected, actual, true, "etag"); - } - - @Test - public void createOrUpdateIndexCreatesWhenIndexDoesNotExistAsync() { - Function>> createAndValidateFunction = indexName -> { - SearchIndex expected = createTestIndex(indexName); - return asyncClient.createOrUpdateIndex(expected).map(actual -> Tuples.of(expected, actual)); - }; - - StepVerifier.create(createAndValidateFunction.apply(null)).assertNext(indexes -> { - indexesToDelete.add(indexes.getT2().getName()); - assertObjectEquals(indexes.getT1(), indexes.getT2(), true, "etag"); - }).verifyComplete(); - } - - @Test - public void createOrUpdateIndexCreatesWhenIndexDoesNotExistWithResponseSync() { - SearchIndex expected = createTestIndex(null); - - SearchIndex actual = client.createOrUpdateIndexWithResponse(expected, false, false, Context.NONE).getValue(); - indexesToDelete.add(actual.getName()); - assertObjectEquals(expected, actual, true, "etag"); - } - - @Test - public void createOrUpdateIndexCreatesWhenIndexDoesNotExistWithResponseAsync() { - Function>> createAndValidateFunction = indexName -> { - SearchIndex expected = createTestIndex(indexName); - return asyncClient.createOrUpdateIndexWithResponse(expected, false, false) - .map(response -> Tuples.of(expected, response.getValue())); - }; - - StepVerifier.create(createAndValidateFunction.apply(null)).assertNext(indexes -> { - indexesToDelete.add(indexes.getT2().getName()); - assertObjectEquals(indexes.getT1(), indexes.getT2(), true, "etag"); - }).verifyComplete(); - } - - @Test - public void createOrUpdateIndexIfNotExistsSucceedsOnNoResourceSync() { - SearchIndex index - = client.createOrUpdateIndexWithResponse(createTestIndex(null), false, true, Context.NONE).getValue(); - indexesToDelete.add(index.getName()); - - assertNotNull(index.getETag()); - } - - @Test - public void createOrUpdateIndexIfNotExistsSucceedsOnNoResourceAsync() { - StepVerifier.create(asyncClient.createOrUpdateIndexWithResponse(createTestIndex(null), false, true)) - .assertNext(response -> { - indexesToDelete.add(response.getValue().getName()); - assertNotNull(response.getValue().getETag()); - }) - .verifyComplete(); - } - - @Test - public void createOrUpdateIndexIfExistsSucceedsOnExistingResourceSync() { - SearchIndex original - = client.createOrUpdateIndexWithResponse(createTestIndex(null), false, false, Context.NONE).getValue(); - indexesToDelete.add(original.getName()); - - SearchIndex updated - = client.createOrUpdateIndexWithResponse(mutateCorsOptionsInIndex(original), false, false, Context.NONE) - .getValue(); - - validateETagUpdate(original.getETag(), updated.getETag()); - } - - @Test - public void createOrUpdateIndexIfExistsSucceedsOnExistingResourceAsync() { - Mono> createThenUpdateMono - = asyncClient.createOrUpdateIndexWithResponse(createTestIndex(null), false, false).flatMap(response -> { - SearchIndex original = response.getValue(); - String originalETag = original.getETag(); - indexesToDelete.add(original.getName()); - - return asyncClient.createOrUpdateIndexWithResponse(mutateCorsOptionsInIndex(original), false, false) - .map(update -> Tuples.of(originalETag, update.getValue().getETag())); - }); - - StepVerifier.create(createThenUpdateMono) - .assertNext(etags -> validateETagUpdate(etags.getT1(), etags.getT2())) - .verifyComplete(); - } - - @Test - public void createOrUpdateIndexIfNotChangedSucceedsWhenResourceUnchangedSync() { - SearchIndex original - = client.createOrUpdateIndexWithResponse(createTestIndex(null), false, false, Context.NONE).getValue(); - indexesToDelete.add(original.getName()); - - String updatedETag - = client.createOrUpdateIndexWithResponse(mutateCorsOptionsInIndex(original), false, true, Context.NONE) - .getValue() - .getETag(); - - validateETagUpdate(original.getETag(), updatedETag); - } - - @Test - public void createOrUpdateIndexIfNotChangedSucceedsWhenResourceUnchangedAsync() { - Mono> createThenUpdateMono - = asyncClient.createOrUpdateIndexWithResponse(createTestIndex(null), false, false).flatMap(response -> { - SearchIndex original = response.getValue(); - String originalETag = original.getETag(); - indexesToDelete.add(original.getName()); - - return asyncClient.createOrUpdateIndexWithResponse(mutateCorsOptionsInIndex(original), false, true) - .map(update -> Tuples.of(originalETag, update.getValue().getETag())); - }); - - StepVerifier.create(createThenUpdateMono) - .assertNext(etags -> validateETagUpdate(etags.getT1(), etags.getT2())) - .verifyComplete(); - } - - @Test - public void createOrUpdateIndexIfNotChangedFailsWhenResourceChangedSync() { - SearchIndex original - = client.createOrUpdateIndexWithResponse(createTestIndex(null), false, false, Context.NONE).getValue(); - indexesToDelete.add(original.getName()); - - String updatedETag - = client.createOrUpdateIndexWithResponse(mutateCorsOptionsInIndex(original), false, true, Context.NONE) - .getValue() - .getETag(); - - HttpResponseException ex = assertThrows(HttpResponseException.class, - () -> client.createOrUpdateIndexWithResponse(original, false, true, Context.NONE), - "createOrUpdateDefinition should have failed due to precondition."); - - assertEquals(HttpURLConnection.HTTP_PRECON_FAILED, ex.getResponse().getStatusCode()); - - validateETagUpdate(original.getETag(), updatedETag); - } - - @Test - public void createOrUpdateIndexIfNotChangedFailsWhenResourceChangedAsync() { - Mono> createUpdateThenFailUpdateMono - = asyncClient.createOrUpdateIndexWithResponse(createTestIndex(null), false, false).flatMap(response -> { - SearchIndex original = response.getValue(); - String originalETag = original.getETag(); - indexesToDelete.add(original.getName()); - - return asyncClient.createOrUpdateIndexWithResponse(mutateCorsOptionsInIndex(original), false, true) - .map(update -> Tuples.of(originalETag, update.getValue().getETag(), original)); - }) - .doOnNext(etags -> validateETagUpdate(etags.getT1(), etags.getT2())) - .flatMap(original -> asyncClient.createOrUpdateIndexWithResponse(original.getT3(), false, true)); - - StepVerifier.create(createUpdateThenFailUpdateMono).verifyErrorSatisfies(throwable -> { - HttpResponseException ex = assertInstanceOf(HttpResponseException.class, throwable); - assertEquals(HttpURLConnection.HTTP_PRECON_FAILED, ex.getResponse().getStatusCode()); - }); - } - - @Test - public void canCreateAndGetIndexStatsSync() { - SearchIndex index = createTestIndex(null); - client.createOrUpdateIndex(index); - indexesToDelete.add(index.getName()); - - SearchIndexStatistics indexStatistics = client.getIndexStatistics(index.getName()); - assertEquals(0, indexStatistics.getDocumentCount()); - assertEquals(0, indexStatistics.getStorageSize()); - - Response indexStatisticsResponse - = client.getIndexStatisticsWithResponse(index.getName(), Context.NONE); - assertEquals(0, indexStatisticsResponse.getValue().getDocumentCount()); - assertEquals(0, indexStatisticsResponse.getValue().getStorageSize()); - } - - @Test - public void canCreateAndGetIndexStatsAsync() { - SearchIndex index = createTestIndex(null); - asyncClient.createOrUpdateIndex(index).block(); - indexesToDelete.add(index.getName()); - - StepVerifier.create(asyncClient.getIndexStatistics(index.getName())).assertNext(indexStatistics -> { - assertEquals(0, indexStatistics.getDocumentCount()); - assertEquals(0, indexStatistics.getStorageSize()); - }).verifyComplete(); - - StepVerifier.create(asyncClient.getIndexStatisticsWithResponse(index.getName())) - .assertNext(indexStatisticsResponse -> { - assertEquals(0, indexStatisticsResponse.getValue().getDocumentCount()); - assertEquals(0, indexStatisticsResponse.getValue().getStorageSize()); - }) - .verifyComplete(); - } - - static SearchIndex mutateCorsOptionsInIndex(SearchIndex index) { - return mutateCorsOptionsInIndex(index, Collections.singletonList("*")); - } - - static SearchIndex mutateCorsOptionsInIndex(SearchIndex index, List allowedOrigins) { - CorsOptions mutatedCorsOptions - = new CorsOptions(allowedOrigins).setMaxAgeInSeconds(index.getCorsOptions().getMaxAgeInSeconds()); - - return index.setCorsOptions(mutatedCorsOptions); - } - - static SearchField getFieldByName(SearchIndex index, String name) { - for (SearchField field : index.getFields()) { - if (Objects.equals(name, field.getName())) { - return field; - } - } - - throw new NoSuchElementException( - "Unable to find a field with name '" + name + "' in index '" + index.getName() + "'."); - } -} diff --git a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/indexes/IndexersManagementTests.java b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/indexes/IndexersManagementTests.java deleted file mode 100644 index 9f9195e6186e..000000000000 --- a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/indexes/IndexersManagementTests.java +++ /dev/null @@ -1,1294 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -package com.azure.search.documents.indexes; - -import com.azure.core.exception.HttpResponseException; -import com.azure.core.http.policy.HttpPipelinePolicy; -import com.azure.core.http.rest.Response; -import com.azure.core.test.TestMode; -import com.azure.core.util.Context; -import com.azure.search.documents.SearchTestBase; -import com.azure.search.documents.TestHelpers; -import com.azure.search.documents.indexes.models.FieldMapping; -import com.azure.search.documents.indexes.models.IndexerExecutionResult; -import com.azure.search.documents.indexes.models.IndexerExecutionStatus; -import com.azure.search.documents.indexes.models.IndexerStatus; -import com.azure.search.documents.indexes.models.IndexingParameters; -import com.azure.search.documents.indexes.models.IndexingSchedule; -import com.azure.search.documents.indexes.models.InputFieldMappingEntry; -import com.azure.search.documents.indexes.models.OcrSkill; -import com.azure.search.documents.indexes.models.OutputFieldMappingEntry; -import com.azure.search.documents.indexes.models.SearchField; -import com.azure.search.documents.indexes.models.SearchFieldDataType; -import com.azure.search.documents.indexes.models.SearchIndex; -import com.azure.search.documents.indexes.models.SearchIndexer; -import com.azure.search.documents.indexes.models.SearchIndexerDataSourceConnection; -import com.azure.search.documents.indexes.models.SearchIndexerLimits; -import com.azure.search.documents.indexes.models.SearchIndexerSkill; -import com.azure.search.documents.indexes.models.SearchIndexerSkillset; -import com.azure.search.documents.indexes.models.SearchIndexerStatus; -import com.azure.search.documents.indexes.models.SoftDeleteColumnDeletionDetectionPolicy; -import org.junit.jupiter.api.AfterAll; -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.Test; -import reactor.core.publisher.Mono; -import reactor.test.StepVerifier; -import reactor.util.function.Tuple2; -import reactor.util.function.Tuples; - -import java.net.HttpURLConnection; -import java.time.Duration; -import java.time.OffsetDateTime; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.stream.Collectors; - -import static com.azure.search.documents.TestHelpers.BLOB_DATASOURCE_NAME; -import static com.azure.search.documents.TestHelpers.assertHttpResponseException; -import static com.azure.search.documents.TestHelpers.assertObjectEquals; -import static com.azure.search.documents.TestHelpers.verifyHttpResponseError; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertInstanceOf; -import static org.junit.jupiter.api.Assertions.assertNotEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.junit.jupiter.api.Assertions.assertTrue; -import static org.junit.jupiter.api.Assertions.fail; - -public class IndexersManagementTests extends SearchTestBase { - private static final String TARGET_INDEX_NAME = "indexforindexers"; - private static final HttpPipelinePolicy MOCK_STATUS_PIPELINE_POLICY = (context, next) -> { - String url = context.getHttpRequest().getUrl().toString(); - String separator = (url.indexOf('?') >= 0) ? "&" : "?"; - context.getHttpRequest().setUrl(url + separator + "mock_status=inProgress"); - return next.process(); - }; - - private static SearchIndexerClient sharedIndexerClient; - private static SearchIndexClient sharedIndexClient; - private static SearchIndexerSkillset sharedSkillset; - private static SearchIndexerDataSourceConnection sharedDatasource; - private static SearchIndex sharedIndex; - - private final List indexersToDelete = new ArrayList<>(); - - private SearchIndexerClient searchIndexerClient; - private SearchIndexerAsyncClient searchIndexerAsyncClient; - - private SearchIndexer createTestDataSourceAndIndexer() { - // Create the indexer object - SearchIndexer indexer = createBaseTestIndexerObject(sharedIndex.getName(), sharedDatasource.getName()); - searchIndexerClient.createIndexer(indexer); - indexersToDelete.add(indexer.getName()); - - return indexer; - } - - /** - * Creates the index and indexer in the search service and then retrieves the indexer and validates it - * - * @param indexer the indexer to be created - */ - private void createAndValidateIndexerSync(SearchIndexer indexer) { - // create this indexer in the service - SearchIndexer indexerResponse = searchIndexerClient.createIndexer(indexer); - indexersToDelete.add(indexerResponse.getName()); - - // verify the returned updated indexer is as expected - setSameStartTime(indexer, indexerResponse); - assertObjectEquals(indexer, indexerResponse, true, "etag"); - } - - private void createAndValidateIndexerAsync(SearchIndexer indexer) { - Mono createIndexerMono = searchIndexerAsyncClient.createIndexer(indexer).map(actual -> { - indexersToDelete.add(actual.getName()); - setSameStartTime(indexer, actual); - - return actual; - }); - - StepVerifier.create(createIndexerMono) - .assertNext(actual -> assertObjectEquals(indexer, actual, true, "etag")) - .verifyComplete(); - } - - @BeforeAll - public static void setupSharedResources() { - sharedSkillset = createSkillsetObject(); - sharedDatasource = createSharedDataSource(); - sharedIndex = createTestIndexForLiveDatasource(); - - if (TEST_MODE == TestMode.PLAYBACK) { - return; - } - - sharedIndexerClient = new SearchIndexerClientBuilder().endpoint(ENDPOINT) - .credential(TestHelpers.getTestTokenCredential()) - .buildClient(); - sharedIndexClient = new SearchIndexClientBuilder().endpoint(ENDPOINT) - .credential(TestHelpers.getTestTokenCredential()) - .buildClient(); - - sharedSkillset = sharedIndexerClient.createSkillset(sharedSkillset); - sharedDatasource = sharedIndexerClient.createOrUpdateDataSourceConnection(sharedDatasource); - sharedIndex = sharedIndexClient.createIndex(sharedIndex); - } - - @AfterAll - public static void cleanupSharedResources() { - if (TEST_MODE == TestMode.PLAYBACK) { - return; // Running in PLAYBACK, no need to run. - } - - sharedIndexerClient.deleteSkillset(sharedSkillset.getName()); - sharedIndexerClient.deleteDataSourceConnection(sharedDatasource.getName()); - sharedIndexClient.deleteIndex(sharedIndex.getName()); - } - - @Override - protected void beforeTest() { - super.beforeTest(); - - searchIndexerClient = getSearchIndexerClientBuilder(true).buildClient(); - searchIndexerAsyncClient = getSearchIndexerClientBuilder(false).buildAsyncClient(); - } - - @Override - protected void afterTest() { - super.afterTest(); - - for (String indexer : indexersToDelete) { - searchIndexerClient.deleteIndexer(indexer); - } - } - - @Test - public void createIndexerReturnsCorrectDefinitionSync() { - SearchIndexer expectedIndexer - = createBaseTestIndexerObject(sharedIndex.getName(), sharedDatasource.getName()).setIsDisabled(true) - .setParameters( - new IndexingParameters().setBatchSize(50).setMaxFailedItems(10).setMaxFailedItemsPerBatch(10)); - - SearchIndexer actualIndexer = searchIndexerClient.createIndexer(expectedIndexer); - indexersToDelete.add(actualIndexer.getName()); - - setSameStartTime(expectedIndexer, actualIndexer); - assertObjectEquals(expectedIndexer, actualIndexer, true, "etag"); - } - - @Test - public void createIndexerReturnsCorrectDefinitionAsync() { - SearchIndexer expectedIndexer - = createBaseTestIndexerObject(sharedIndex.getName(), sharedDatasource.getName()).setIsDisabled(true) - .setParameters( - new IndexingParameters().setBatchSize(50).setMaxFailedItems(10).setMaxFailedItemsPerBatch(10)); - - StepVerifier.create(searchIndexerAsyncClient.createIndexer(expectedIndexer)).assertNext(actualIndexer -> { - indexersToDelete.add(actualIndexer.getName()); - setSameStartTime(expectedIndexer, actualIndexer); - assertObjectEquals(expectedIndexer, actualIndexer, true, "etag"); - }).verifyComplete(); - } - - @Test - public void canCreateAndListIndexersSync() { - String indexName = sharedIndex.getName(); - String dataSourceName = sharedDatasource.getName(); - - // Create two indexers - SearchIndexer indexer1 - = createBaseTestIndexerObject("a" + testResourceNamer.randomName("indexer", 32), indexName, dataSourceName); - SearchIndexer indexer2 - = createBaseTestIndexerObject("b" + testResourceNamer.randomName("indexer", 32), indexName, dataSourceName); - - searchIndexerClient.createIndexer(indexer1); - indexersToDelete.add(indexer1.getName()); - searchIndexerClient.createIndexer(indexer2); - indexersToDelete.add(indexer2.getName()); - - Map expectedIndexers = new HashMap<>(); - expectedIndexers.put(indexer1.getName(), indexer1); - expectedIndexers.put(indexer2.getName(), indexer2); - - Map actualIndexers - = searchIndexerClient.listIndexers().stream().collect(Collectors.toMap(SearchIndexer::getName, si -> si)); - - compareMaps(expectedIndexers, actualIndexers, - (expected, actual) -> assertObjectEquals(expected, actual, true, "etag")); - } - - @Test - public void canCreateAndListIndexersAsync() { - String indexName = sharedIndex.getName(); - String dataSourceName = sharedDatasource.getName(); - - // Create two indexers - SearchIndexer indexer1 - = createBaseTestIndexerObject("a" + testResourceNamer.randomName("indexer", 32), indexName, dataSourceName); - SearchIndexer indexer2 - = createBaseTestIndexerObject("b" + testResourceNamer.randomName("indexer", 32), indexName, dataSourceName); - - searchIndexerAsyncClient.createIndexer(indexer1).block(); - indexersToDelete.add(indexer1.getName()); - searchIndexerAsyncClient.createIndexer(indexer2).block(); - indexersToDelete.add(indexer2.getName()); - - Map expectedIndexers = new HashMap<>(); - expectedIndexers.put(indexer1.getName(), indexer1); - expectedIndexers.put(indexer2.getName(), indexer2); - - Mono> listMono - = searchIndexerAsyncClient.listIndexers().collect(Collectors.toMap(SearchIndexer::getName, si -> si)); - - StepVerifier.create(listMono) - .assertNext(actualIndexers -> compareMaps(expectedIndexers, actualIndexers, - (expected, actual) -> assertObjectEquals(expected, actual, true, "etag"))) - .verifyComplete(); - } - - @Test - public void canCreateAndListIndexerNamesSync() { - String indexName = sharedIndex.getName(); - String dataSourceName = sharedDatasource.getName(); - - SearchIndexer indexer1 - = createBaseTestIndexerObject("a" + testResourceNamer.randomName("indexer", 32), indexName, dataSourceName); - SearchIndexer indexer2 - = createBaseTestIndexerObject("b" + testResourceNamer.randomName("indexer", 32), indexName, dataSourceName); - searchIndexerClient.createIndexer(indexer1); - indexersToDelete.add(indexer1.getName()); - searchIndexerClient.createIndexer(indexer2); - indexersToDelete.add(indexer2.getName()); - - Set expectedIndexers = new HashSet<>(Arrays.asList(indexer1.getName(), indexer2.getName())); - Set actualIndexers = searchIndexerClient.listIndexerNames().stream().collect(Collectors.toSet()); - - assertEquals(expectedIndexers.size(), actualIndexers.size()); - assertTrue(actualIndexers.containsAll(expectedIndexers)); - } - - @Test - public void canCreateAndListIndexerNamesAsync() { - String indexName = sharedIndex.getName(); - String dataSourceName = sharedDatasource.getName(); - - SearchIndexer indexer1 - = createBaseTestIndexerObject("a" + testResourceNamer.randomName("indexer", 32), indexName, dataSourceName); - SearchIndexer indexer2 - = createBaseTestIndexerObject("b" + testResourceNamer.randomName("indexer", 32), indexName, dataSourceName); - searchIndexerAsyncClient.createIndexer(indexer1).block(); - indexersToDelete.add(indexer1.getName()); - searchIndexerAsyncClient.createIndexer(indexer2).block(); - indexersToDelete.add(indexer2.getName()); - - Set expectedIndexers = new HashSet<>(Arrays.asList(indexer1.getName(), indexer2.getName())); - - StepVerifier.create(searchIndexerAsyncClient.listIndexerNames().collect(Collectors.toSet())) - .assertNext(actualIndexers -> { - assertEquals(expectedIndexers.size(), actualIndexers.size()); - assertTrue(actualIndexers.containsAll(expectedIndexers)); - }) - .verifyComplete(); - } - - @Test - public void createIndexerFailsWithUsefulMessageOnUserErrorSync() { - SearchIndexer indexer = createBaseTestIndexerObject(sharedIndex.getName(), "thisdatasourcedoesnotexist"); - - assertHttpResponseException(() -> searchIndexerClient.createIndexer(indexer), - HttpURLConnection.HTTP_BAD_REQUEST, - "This indexer refers to a data source 'thisdatasourcedoesnotexist' that doesn't exist"); - } - - @Test - public void createIndexerFailsWithUsefulMessageOnUserErrorAsync() { - SearchIndexer indexer = createBaseTestIndexerObject(sharedIndex.getName(), "thisdatasourcedoesnotexist"); - - StepVerifier.create(searchIndexerAsyncClient.createIndexer(indexer)) - .verifyErrorSatisfies(throwable -> verifyHttpResponseError(throwable, HttpURLConnection.HTTP_BAD_REQUEST, - "This indexer refers to a data source 'thisdatasourcedoesnotexist' that doesn't exist")); - } - - @Test - public void canResetIndexerAndGetIndexerStatusSync() { - SearchIndexer indexer = createTestDataSourceAndIndexer(); - - searchIndexerClient.resetIndexer(indexer.getName()); - SearchIndexerStatus indexerStatus = searchIndexerClient.getIndexerStatus(indexer.getName()); - assertEquals(IndexerStatus.RUNNING, indexerStatus.getStatus()); - assertEquals(IndexerExecutionStatus.RESET, indexerStatus.getLastResult().getStatus()); - } - - @Test - public void canResetIndexerAndGetIndexerStatusAsync() { - SearchIndexer indexer = createTestDataSourceAndIndexer(); - - searchIndexerAsyncClient.resetIndexer(indexer.getName()).block(); - - StepVerifier.create(searchIndexerAsyncClient.getIndexerStatus(indexer.getName())).assertNext(indexerStatus -> { - assertEquals(IndexerStatus.RUNNING, indexerStatus.getStatus()); - assertEquals(IndexerExecutionStatus.RESET, indexerStatus.getLastResult().getStatus()); - }).verifyComplete(); - } - - @Test - public void canResetIndexerAndGetIndexerStatusWithResponseSync() { - SearchIndexer indexer = createTestDataSourceAndIndexer(); - - searchIndexerClient.resetIndexerWithResponse(indexer.getName(), Context.NONE); - SearchIndexerStatus indexerStatusResponse - = searchIndexerClient.getIndexerStatusWithResponse(indexer.getName(), Context.NONE).getValue(); - assertEquals(IndexerStatus.RUNNING, indexerStatusResponse.getStatus()); - assertEquals(IndexerExecutionStatus.RESET, indexerStatusResponse.getLastResult().getStatus()); - } - - @Test - public void canResetIndexerAndGetIndexerStatusWithResponseAsync() { - SearchIndexer indexer = createTestDataSourceAndIndexer(); - - searchIndexerAsyncClient.resetIndexerWithResponse(indexer.getName()).block(); - - StepVerifier.create(searchIndexerAsyncClient.getIndexerStatusWithResponse(indexer.getName())) - .assertNext(response -> { - assertEquals(IndexerStatus.RUNNING, response.getValue().getStatus()); - assertEquals(IndexerExecutionStatus.RESET, response.getValue().getLastResult().getStatus()); - }) - .verifyComplete(); - - } - - @Test - public void canRunIndexerSync() { - SearchIndexer indexer = createTestDataSourceAndIndexer(); - searchIndexerClient.runIndexer(indexer.getName()); - - SearchIndexerStatus indexerExecutionInfo = searchIndexerClient.getIndexerStatus(indexer.getName()); - assertEquals(IndexerStatus.RUNNING, indexerExecutionInfo.getStatus()); - } - - @Test - public void canRunIndexerAsync() { - SearchIndexer indexer = createTestDataSourceAndIndexer(); - searchIndexerAsyncClient.runIndexer(indexer.getName()).block(); - - StepVerifier.create(searchIndexerAsyncClient.getIndexerStatus(indexer.getName())) - .assertNext(info -> assertEquals(IndexerStatus.RUNNING, info.getStatus())) - .verifyComplete(); - } - - @Test - public void canRunIndexerWithResponseSync() { - SearchIndexer indexer = createTestDataSourceAndIndexer(); - Response response = searchIndexerClient.runIndexerWithResponse(indexer.getName(), Context.NONE); - SearchIndexerStatus indexerExecutionInfo = searchIndexerClient.getIndexerStatus(indexer.getName()); - - assertEquals(HttpURLConnection.HTTP_ACCEPTED, response.getStatusCode()); - assertEquals(IndexerStatus.RUNNING, indexerExecutionInfo.getStatus()); - } - - @Test - public void canRunIndexerWithResponseAsync() { - SearchIndexer indexer = createTestDataSourceAndIndexer(); - - StepVerifier.create(searchIndexerAsyncClient.runIndexerWithResponse(indexer.getName())) - .assertNext(response -> assertEquals(HttpURLConnection.HTTP_ACCEPTED, response.getStatusCode())) - .verifyComplete(); - - StepVerifier.create(searchIndexerAsyncClient.getIndexerStatus(indexer.getName())) - .assertNext(info -> assertEquals(IndexerStatus.RUNNING, info.getStatus())) - .verifyComplete(); - } - - @Test - public void canRunIndexerAndGetIndexerStatusSync() { - SearchIndexer indexer = createBaseTestIndexerObject(sharedIndex.getName(), sharedDatasource.getName()); - - // When an indexer is created, the execution info may not be available immediately. Hence, a - // pipeline policy that injects a "mock_status" query string is added to the client, which results in service - // returning a well-known mock response - SearchIndexerClient mockStatusClient - = getSearchIndexerClientBuilder(true, MOCK_STATUS_PIPELINE_POLICY).buildClient(); - - mockStatusClient.createIndexer(indexer); - indexersToDelete.add(indexer.getName()); - - SearchIndexerStatus indexerExecutionInfo = mockStatusClient.getIndexerStatus(indexer.getName()); - assertEquals(IndexerStatus.RUNNING, indexerExecutionInfo.getStatus()); - - Response indexerRunResponse = mockStatusClient.runIndexerWithResponse(indexer.getName(), Context.NONE); - assertEquals(HttpURLConnection.HTTP_ACCEPTED, indexerRunResponse.getStatusCode()); - - assertValidSearchIndexerStatus(mockStatusClient.getIndexerStatus(indexer.getName())); - } - - @Test - public void canRunIndexerAndGetIndexerStatusAsync() { - SearchIndexer indexer = createBaseTestIndexerObject(sharedIndex.getName(), sharedDatasource.getName()); - - // When an indexer is created, the execution info may not be available immediately. Hence, a - // pipeline policy that injects a "mock_status" query string is added to the client, which results in service - // returning a well-known mock response - SearchIndexerAsyncClient mockStatusClient - = getSearchIndexerClientBuilder(false, MOCK_STATUS_PIPELINE_POLICY).buildAsyncClient(); - - mockStatusClient.createIndexer(indexer).block(); - indexersToDelete.add(indexer.getName()); - - StepVerifier.create(mockStatusClient.getIndexerStatus(indexer.getName())) - .assertNext(info -> assertEquals(IndexerStatus.RUNNING, info.getStatus())) - .verifyComplete(); - - StepVerifier.create(mockStatusClient.runIndexerWithResponse(indexer.getName())) - .assertNext(response -> assertEquals(HttpURLConnection.HTTP_ACCEPTED, response.getStatusCode())) - .verifyComplete(); - - StepVerifier.create(mockStatusClient.getIndexerStatus(indexer.getName())) - .assertNext(this::assertValidSearchIndexerStatus) - .verifyComplete(); - } - - @Test - public void canUpdateIndexerSync() { - String indexName = sharedIndex.getName(); - String dataSourceName = sharedDatasource.getName(); - - SearchIndexer initial = createBaseTestIndexerObject(indexName, dataSourceName).setIsDisabled(true); - searchIndexerClient.createIndexer(initial); - indexersToDelete.add(initial.getName()); - - SearchIndexer updated = createBaseTestIndexerObject(initial.getName(), indexName, dataSourceName) - .setDescription("somethingdifferent"); - SearchIndexer indexerResponse = searchIndexerClient.createOrUpdateIndexer(updated); - - // verify the returned updated indexer is as expected - setSameStartTime(updated, indexerResponse); - assertObjectEquals(updated, indexerResponse, true, "etag"); - } - - @Test - public void canUpdateIndexerAsync() { - String indexName = sharedIndex.getName(); - String dataSourceName = sharedDatasource.getName(); - - SearchIndexer initial = createBaseTestIndexerObject(indexName, dataSourceName).setIsDisabled(true); - searchIndexerAsyncClient.createIndexer(initial).block(); - indexersToDelete.add(initial.getName()); - - SearchIndexer updated = createBaseTestIndexerObject(initial.getName(), indexName, dataSourceName) - .setDescription("somethingdifferent"); - - StepVerifier.create(searchIndexerAsyncClient.createOrUpdateIndexer(updated)).assertNext(indexerResponse -> { - // verify the returned updated indexer is as expected - setSameStartTime(updated, indexerResponse); - assertObjectEquals(updated, indexerResponse, true, "etag"); - }).verifyComplete(); - } - - @Test - public void canUpdateIndexerFieldMappingSync() { - String indexName = sharedIndex.getName(); - String dataSourceName = sharedDatasource.getName(); - - SearchIndexer initial = createBaseTestIndexerObject(indexName, dataSourceName).setIsDisabled(true); - searchIndexerClient.createIndexer(initial); - indexersToDelete.add(initial.getName()); - - SearchIndexer updated = createBaseTestIndexerObject(initial.getName(), indexName, dataSourceName) - .setFieldMappings(Collections.singletonList(new FieldMapping("state_alpha").setTargetFieldName("state"))); - SearchIndexer indexerResponse = searchIndexerClient.createOrUpdateIndexer(updated); - - // verify the returned updated indexer is as expected - setSameStartTime(updated, indexerResponse); - assertObjectEquals(updated, indexerResponse, true, "etag"); - } - - @Test - public void canUpdateIndexerFieldMappingAsync() { - String indexName = sharedIndex.getName(); - String dataSourceName = sharedDatasource.getName(); - - SearchIndexer initial = createBaseTestIndexerObject(indexName, dataSourceName).setIsDisabled(true); - searchIndexerAsyncClient.createIndexer(initial).block(); - indexersToDelete.add(initial.getName()); - - SearchIndexer updated = createBaseTestIndexerObject(initial.getName(), indexName, dataSourceName) - .setFieldMappings(Collections.singletonList(new FieldMapping("state_alpha").setTargetFieldName("state"))); - - StepVerifier.create(searchIndexerAsyncClient.createOrUpdateIndexer(updated)).assertNext(indexerResponse -> { - // verify the returned updated indexer is as expected - setSameStartTime(updated, indexerResponse); - assertObjectEquals(updated, indexerResponse, true, "etag"); - }).verifyComplete(); - } - - @Test - public void canCreateIndexerWithFieldMappingSync() { - SearchIndexer indexer = createBaseTestIndexerObject(sharedIndex.getName(), sharedDatasource.getName()) - .setFieldMappings(Collections.singletonList(new FieldMapping("state_alpha").setTargetFieldName("state"))); - - createAndValidateIndexerSync(indexer); - } - - @Test - public void canCreateIndexerWithFieldMappingAsync() { - SearchIndexer indexer = createBaseTestIndexerObject(sharedIndex.getName(), sharedDatasource.getName()) - .setFieldMappings(Collections.singletonList(new FieldMapping("state_alpha").setTargetFieldName("state"))); - - createAndValidateIndexerAsync(indexer); - } - - @Test - public void canUpdateIndexerDisabledSync() { - String indexName = sharedIndex.getName(); - String dataSourceName = sharedDatasource.getName(); - - SearchIndexer initial = createBaseTestIndexerObject(indexName, dataSourceName).setIsDisabled(true); - searchIndexerClient.createIndexer(initial); - indexersToDelete.add(initial.getName()); - - SearchIndexer updated - = createBaseTestIndexerObject(initial.getName(), indexName, dataSourceName).setIsDisabled(false); - SearchIndexer indexerResponse = searchIndexerClient.createOrUpdateIndexer(updated); - - setSameStartTime(updated, indexerResponse); - assertObjectEquals(updated, indexerResponse, true, "etag"); - } - - @Test - public void canUpdateIndexerDisabledAsync() { - String indexName = sharedIndex.getName(); - String dataSourceName = sharedDatasource.getName(); - - SearchIndexer initial = createBaseTestIndexerObject(indexName, dataSourceName).setIsDisabled(true); - searchIndexerAsyncClient.createIndexer(initial).block(); - indexersToDelete.add(initial.getName()); - - SearchIndexer updated - = createBaseTestIndexerObject(initial.getName(), indexName, dataSourceName).setIsDisabled(false); - - StepVerifier.create(searchIndexerAsyncClient.createOrUpdateIndexer(updated)).assertNext(indexerResponse -> { - setSameStartTime(updated, indexerResponse); - assertObjectEquals(updated, indexerResponse, true, "etag"); - }).verifyComplete(); - } - - @Test - public void canUpdateIndexerScheduleSync() { - String indexName = sharedIndex.getName(); - String dataSourceName = sharedDatasource.getName(); - - SearchIndexer initial = createBaseTestIndexerObject(indexName, dataSourceName).setIsDisabled(true); - searchIndexerClient.createIndexer(initial); - indexersToDelete.add(initial.getName()); - - SearchIndexer updated = createBaseTestIndexerObject(initial.getName(), indexName, dataSourceName) - .setSchedule(new IndexingSchedule(Duration.ofMinutes(10))); - SearchIndexer indexerResponse = searchIndexerClient.createOrUpdateIndexer(updated); - - setSameStartTime(updated, indexerResponse); - assertObjectEquals(updated, indexerResponse, true, "etag"); - } - - @Test - public void canUpdateIndexerScheduleAsync() { - String indexName = sharedIndex.getName(); - String dataSourceName = sharedDatasource.getName(); - - SearchIndexer initial = createBaseTestIndexerObject(indexName, dataSourceName).setIsDisabled(true); - searchIndexerAsyncClient.createIndexer(initial).block(); - indexersToDelete.add(initial.getName()); - - SearchIndexer updated = createBaseTestIndexerObject(initial.getName(), indexName, dataSourceName) - .setSchedule(new IndexingSchedule(Duration.ofMinutes(10))); - - StepVerifier.create(searchIndexerAsyncClient.createOrUpdateIndexer(updated)).assertNext(indexerResponse -> { - setSameStartTime(updated, indexerResponse); - assertObjectEquals(updated, indexerResponse, true, "etag"); - }).verifyComplete(); - } - - @Test - public void canCreateIndexerWithScheduleSync() { - SearchIndexer indexer = createBaseTestIndexerObject(sharedIndex.getName(), sharedDatasource.getName()) - .setSchedule(new IndexingSchedule(Duration.ofMinutes(10))); - - createAndValidateIndexerSync(indexer); - } - - @Test - public void canCreateIndexerWithScheduleAsync() { - SearchIndexer indexer = createBaseTestIndexerObject(sharedIndex.getName(), sharedDatasource.getName()) - .setSchedule(new IndexingSchedule(Duration.ofMinutes(10))); - - createAndValidateIndexerAsync(indexer); - } - - @Test - public void canUpdateIndexerBatchSizeMaxFailedItemsSync() { - String indexName = sharedIndex.getName(); - String dataSourceName = sharedDatasource.getName(); - - SearchIndexer initial = createBaseTestIndexerObject(indexName, dataSourceName).setIsDisabled(true); - searchIndexerClient.createIndexer(initial); - indexersToDelete.add(initial.getName()); - - SearchIndexer updated = createIndexerWithDifferentIndexingParameters(initial); - SearchIndexer indexerResponse = searchIndexerClient.createOrUpdateIndexer(updated); - - setSameStartTime(updated, indexerResponse); - assertObjectEquals(updated, indexerResponse, true, "etag"); - } - - @Test - public void canUpdateIndexerBatchSizeMaxFailedItemsAsync() { - String indexName = sharedIndex.getName(); - String dataSourceName = sharedDatasource.getName(); - - SearchIndexer initial = createBaseTestIndexerObject(indexName, dataSourceName).setIsDisabled(true); - searchIndexerAsyncClient.createIndexer(initial).block(); - indexersToDelete.add(initial.getName()); - - SearchIndexer updated = createIndexerWithDifferentIndexingParameters(initial); - - StepVerifier.create(searchIndexerAsyncClient.createOrUpdateIndexer(updated)).assertNext(indexerResponse -> { - setSameStartTime(updated, indexerResponse); - assertObjectEquals(updated, indexerResponse, true, "etag"); - }).verifyComplete(); - } - - @Test - public void canCreateIndexerWithBatchSizeMaxFailedItemsSync() { - SearchIndexer indexer = createBaseTestIndexerObject(sharedIndex.getName(), sharedDatasource.getName()); - SearchIndexer updatedExpected = createIndexerWithDifferentIndexingParameters(indexer); - - createAndValidateIndexerSync(updatedExpected); - } - - @Test - public void canCreateIndexerWithBatchSizeMaxFailedItemsAsync() { - SearchIndexer indexer = createBaseTestIndexerObject(sharedIndex.getName(), sharedDatasource.getName()); - SearchIndexer updatedExpected = createIndexerWithDifferentIndexingParameters(indexer); - - createAndValidateIndexerAsync(updatedExpected); - } - - @Test - public void canUpdateIndexerBlobParamsSync() { - String indexName = sharedIndex.getName(); - - SearchIndexer initial = createBaseTestIndexerObject(indexName, sharedDatasource.getName()).setIsDisabled(true); - searchIndexerClient.createIndexer(initial); - indexersToDelete.add(initial.getName()); - - SearchIndexer updated - = createIndexerWithStorageConfig(initial.getName(), indexName, sharedDatasource.getName()); - SearchIndexer indexerResponse = searchIndexerClient.createOrUpdateIndexer(updated); - - setSameStartTime(updated, indexerResponse); - assertObjectEquals(updated, indexerResponse, true, "etag"); - } - - @Test - public void canUpdateIndexerBlobParamsAsync() { - String indexName = sharedIndex.getName(); - - SearchIndexer initial = createBaseTestIndexerObject(indexName, sharedDatasource.getName()).setIsDisabled(true); - searchIndexerAsyncClient.createIndexer(initial).block(); - indexersToDelete.add(initial.getName()); - - SearchIndexer updated - = createIndexerWithStorageConfig(initial.getName(), indexName, sharedDatasource.getName()); - - StepVerifier.create(searchIndexerAsyncClient.createOrUpdateIndexer(updated)).assertNext(indexerResponse -> { - setSameStartTime(updated, indexerResponse); - assertObjectEquals(updated, indexerResponse, true, "etag"); - }).verifyComplete(); - } - - @Test - public void canCreateIndexerWithBlobParamsSync() { - // modify the indexer's blob params - SearchIndexer indexer = createIndexerWithStorageConfig(sharedIndex.getName(), sharedDatasource.getName()); - - createAndValidateIndexerSync(indexer); - } - - @Test - public void canCreateIndexerWithBlobParamsAsync() { - // Create the data source within the search service - String targetIndexName = sharedIndex.getName(); - SearchIndexer indexer = createIndexerWithStorageConfig(targetIndexName, sharedDatasource.getName()); - - createAndValidateIndexerAsync(indexer); - } - - @Test - public void canCreateAndDeleteIndexerSync() { - SearchIndexer indexer = createBaseTestIndexerObject(sharedIndex.getName(), sharedDatasource.getName()); - searchIndexerClient.createIndexer(indexer); - - searchIndexerClient.deleteIndexer(indexer.getName()); - assertThrows(HttpResponseException.class, () -> searchIndexerClient.getIndexer(indexer.getName())); - } - - @Test - public void canCreateAndDeleteIndexerAsync() { - SearchIndexer indexer = createBaseTestIndexerObject(sharedIndex.getName(), sharedDatasource.getName()); - searchIndexerAsyncClient.createIndexer(indexer).block(); - - searchIndexerAsyncClient.deleteIndexer(indexer.getName()).block(); - - StepVerifier.create(searchIndexerAsyncClient.getIndexer(indexer.getName())) - .verifyError(HttpResponseException.class); - } - - @Test - public void canCreateAndDeleteIndexerWithResponseSync() { - SearchIndexer indexer = createBaseTestIndexerObject(sharedIndex.getName(), sharedDatasource.getName()); - searchIndexerClient.createIndexerWithResponse(indexer, Context.NONE); - - searchIndexerClient.deleteIndexerWithResponse(indexer, false, Context.NONE); - assertThrows(HttpResponseException.class, () -> searchIndexerClient.getIndexer(indexer.getName())); - } - - @Test - public void canCreateAndDeleteIndexerWithResponseAsync() { - SearchIndexer indexer = createBaseTestIndexerObject(sharedIndex.getName(), sharedDatasource.getName()); - searchIndexerAsyncClient.createIndexerWithResponse(indexer).block(); - - searchIndexerAsyncClient.deleteIndexerWithResponse(indexer, false).block(); - - StepVerifier.create(searchIndexerAsyncClient.getIndexer(indexer.getName())) - .verifyError(HttpResponseException.class); - } - - @Test - public void deleteIndexerIsIdempotentSync() { - // Create the indexer object - SearchIndexer indexer = createBaseTestIndexerObject(sharedIndex.getName(), sharedDatasource.getName()); - - // Try deleting before the indexer even exists. - Response result = searchIndexerClient.deleteIndexerWithResponse(indexer, false, Context.NONE); - assertEquals(HttpURLConnection.HTTP_NOT_FOUND, result.getStatusCode()); - - // Actually create the indexer - searchIndexerClient.createIndexer(indexer); - - // Now delete twice. - result = searchIndexerClient.deleteIndexerWithResponse(indexer, false, Context.NONE); - assertEquals(HttpURLConnection.HTTP_NO_CONTENT, result.getStatusCode()); - - result = searchIndexerClient.deleteIndexerWithResponse(indexer, false, Context.NONE); - assertEquals(HttpURLConnection.HTTP_NOT_FOUND, result.getStatusCode()); - } - - @Test - public void deleteIndexerIsIdempotentAsync() { - // Create the indexer object - SearchIndexer indexer = createBaseTestIndexerObject(sharedIndex.getName(), sharedDatasource.getName()); - - // Try deleting before the indexer even exists. - StepVerifier.create(searchIndexerAsyncClient.deleteIndexerWithResponse(indexer, false)) - .assertNext(response -> assertEquals(HttpURLConnection.HTTP_NOT_FOUND, response.getStatusCode())) - .verifyComplete(); - - // Actually create the indexer - searchIndexerAsyncClient.createIndexer(indexer).block(); - - // Now delete twice. - StepVerifier.create(searchIndexerAsyncClient.deleteIndexerWithResponse(indexer, false)) - .assertNext(response -> assertEquals(HttpURLConnection.HTTP_NO_CONTENT, response.getStatusCode())) - .verifyComplete(); - - StepVerifier.create(searchIndexerAsyncClient.deleteIndexerWithResponse(indexer, false)) - .assertNext(response -> assertEquals(HttpURLConnection.HTTP_NOT_FOUND, response.getStatusCode())) - .verifyComplete(); - } - - @Test - public void canCreateAndGetIndexerSync() { - SearchIndexer indexer = createBaseTestIndexerObject(sharedIndex.getName(), sharedDatasource.getName()); - searchIndexerClient.createIndexer(indexer); - indexersToDelete.add(indexer.getName()); - - SearchIndexer indexerResult = searchIndexerClient.getIndexer(indexer.getName()); - assertObjectEquals(indexer, indexerResult, true, "etag"); - - indexerResult = searchIndexerClient.getIndexerWithResponse(indexer.getName(), Context.NONE).getValue(); - assertObjectEquals(indexer, indexerResult, true, "etag"); - } - - @Test - public void canCreateAndGetIndexerAsync() { - SearchIndexer indexer = createBaseTestIndexerObject(sharedIndex.getName(), sharedDatasource.getName()); - searchIndexerAsyncClient.createIndexer(indexer).block(); - indexersToDelete.add(indexer.getName()); - - StepVerifier.create(searchIndexerAsyncClient.getIndexer(indexer.getName())) - .assertNext(indexerResult -> assertObjectEquals(indexer, indexerResult, true, "etag")) - .verifyComplete(); - - StepVerifier.create(searchIndexerAsyncClient.getIndexerWithResponse(indexer.getName())) - .assertNext(response -> assertObjectEquals(indexer, response.getValue(), true, "etag")) - .verifyComplete(); - } - - @Test - public void getIndexerThrowsOnNotFoundSync() { - assertHttpResponseException(() -> searchIndexerClient.getIndexer("thisindexerdoesnotexist"), - HttpURLConnection.HTTP_NOT_FOUND, "Indexer 'thisindexerdoesnotexist' was not found"); - } - - @Test - public void getIndexerThrowsOnNotFoundAsync() { - StepVerifier.create(searchIndexerAsyncClient.getIndexer("thisindexerdoesnotexist")) - .verifyErrorSatisfies(throwable -> verifyHttpResponseError(throwable, HttpURLConnection.HTTP_NOT_FOUND, - "Indexer 'thisindexerdoesnotexist' was not found")); - } - - @Test - public void createOrUpdateIndexerIfNotExistsSucceedsOnNoResourceSync() { - SearchIndexer indexer = createBaseTestIndexerObject(sharedIndex.getName(), sharedDatasource.getName()); - SearchIndexer created - = searchIndexerClient.createOrUpdateIndexerWithResponse(indexer, true, Context.NONE).getValue(); - indexersToDelete.add(created.getName()); - - assertNotNull(created.getETag()); - } - - @Test - public void createOrUpdateIndexerIfNotExistsSucceedsOnNoResourceAsync() { - SearchIndexer indexer = createBaseTestIndexerObject(sharedIndex.getName(), sharedDatasource.getName()); - - StepVerifier.create(searchIndexerAsyncClient.createOrUpdateIndexerWithResponse(indexer, true)) - .assertNext(response -> { - indexersToDelete.add(response.getValue().getName()); - assertNotNull(response.getValue().getETag()); - }) - .verifyComplete(); - } - - @Test - public void deleteIndexerIfExistsWorksOnlyWhenResourceExistsSync() { - SearchIndexer indexer = createBaseTestIndexerObject(sharedIndex.getName(), sharedDatasource.getName()); - SearchIndexer created - = searchIndexerClient.createOrUpdateIndexerWithResponse(indexer, false, Context.NONE).getValue(); - - searchIndexerClient.deleteIndexerWithResponse(created, true, Context.NONE); - - // Try to delete again and expect to fail - try { - searchIndexerClient.deleteIndexerWithResponse(created, true, Context.NONE); - fail("deleteFunc should have failed due to non existent resource."); - } catch (HttpResponseException ex) { - assertEquals(HttpURLConnection.HTTP_PRECON_FAILED, ex.getResponse().getStatusCode()); - } - } - - @Test - public void deleteIndexerIfExistsWorksOnlyWhenResourceExistsAsync() { - SearchIndexer indexer = createBaseTestIndexerObject(sharedIndex.getName(), sharedDatasource.getName()); - - Mono> createDeleteThenFailToDeleteMono - = searchIndexerAsyncClient.createOrUpdateIndexerWithResponse(indexer, false) - .flatMap(response -> searchIndexerAsyncClient.deleteIndexerWithResponse(response.getValue(), true) - .then(searchIndexerAsyncClient.deleteIndexerWithResponse(response.getValue(), true))); - - StepVerifier.create(createDeleteThenFailToDeleteMono).verifyErrorSatisfies(throwable -> { - HttpResponseException ex = assertInstanceOf(HttpResponseException.class, throwable); - assertEquals(HttpURLConnection.HTTP_PRECON_FAILED, ex.getResponse().getStatusCode()); - }); - } - - @Test - public void deleteIndexerIfNotChangedWorksOnlyOnCurrentResourceSync() { - SearchIndexer indexer = createBaseTestIndexerObject(sharedIndex.getName(), sharedDatasource.getName()); - SearchIndexer stale - = searchIndexerClient.createOrUpdateIndexerWithResponse(indexer, true, Context.NONE).getValue(); - - SearchIndexer updated - = searchIndexerClient.createOrUpdateIndexerWithResponse(stale, false, Context.NONE).getValue(); - - try { - searchIndexerClient.deleteIndexerWithResponse(stale, true, Context.NONE); - fail("deleteFunc should have failed due to precondition."); - } catch (HttpResponseException ex) { - assertEquals(HttpURLConnection.HTTP_PRECON_FAILED, ex.getResponse().getStatusCode()); - } - - searchIndexerClient.deleteIndexerWithResponse(updated, true, Context.NONE); - } - - @Test - public void deleteIndexerIfNotChangedWorksOnlyOnCurrentResourceAsync() { - SearchIndexer indexer = createBaseTestIndexerObject(sharedIndex.getName(), sharedDatasource.getName()); - SearchIndexer stale - = searchIndexerAsyncClient.createOrUpdateIndexerWithResponse(indexer, true).map(Response::getValue).block(); - - SearchIndexer updated - = searchIndexerAsyncClient.createOrUpdateIndexerWithResponse(stale, false).map(Response::getValue).block(); - - StepVerifier.create(searchIndexerAsyncClient.deleteIndexerWithResponse(stale, true)) - .verifyErrorSatisfies(throwable -> { - HttpResponseException ex = assertInstanceOf(HttpResponseException.class, throwable); - assertEquals(HttpURLConnection.HTTP_PRECON_FAILED, ex.getResponse().getStatusCode()); - }); - - StepVerifier.create(searchIndexerAsyncClient.deleteIndexerWithResponse(updated, true)) - .expectNextCount(1) - .verifyComplete(); - } - - @Test - public void updateIndexerIfExistsSucceedsOnExistingResourceSync() { - SearchIndexer indexer = createBaseTestIndexerObject(sharedIndex.getName(), sharedDatasource.getName()); - SearchIndexer original - = searchIndexerClient.createOrUpdateIndexerWithResponse(indexer, false, Context.NONE).getValue(); - String originalETag = original.getETag(); - indexersToDelete.add(original.getName()); - - SearchIndexer updated = searchIndexerClient - .createOrUpdateIndexerWithResponse(original.setDescription("ABrandNewDescription"), false, Context.NONE) - .getValue(); - String updatedETag = updated.getETag(); - - assertNotNull(updatedETag); - assertNotEquals(originalETag, updatedETag); - } - - @Test - public void updateIndexerIfExistsSucceedsOnExistingResourceAsync() { - SearchIndexer indexer = createBaseTestIndexerObject(sharedIndex.getName(), sharedDatasource.getName()); - - Mono> createAndUpdateIndexerMono - = searchIndexerAsyncClient.createOrUpdateIndexerWithResponse(indexer, false).flatMap(response -> { - SearchIndexer original = response.getValue(); - String originalETag = original.getETag(); - indexersToDelete.add(original.getName()); - - return searchIndexerAsyncClient - .createOrUpdateIndexerWithResponse(original.setDescription("an update"), false) - .map(updated -> Tuples.of(originalETag, updated.getValue().getETag())); - }); - - StepVerifier.create(createAndUpdateIndexerMono).assertNext(etags -> { - assertNotNull(etags.getT2()); - assertNotEquals(etags.getT1(), etags.getT2()); - }).verifyComplete(); - } - - @Test - public void updateIndexerIfNotChangedFailsWhenResourceChangedSync() { - SearchIndexer indexer = createBaseTestIndexerObject(sharedIndex.getName(), sharedDatasource.getName()); - SearchIndexer original - = searchIndexerClient.createOrUpdateIndexerWithResponse(indexer, false, Context.NONE).getValue(); - String originalETag = original.getETag(); - indexersToDelete.add(original.getName()); - - SearchIndexer updated = searchIndexerClient - .createOrUpdateIndexerWithResponse(original.setDescription("ABrandNewDescription"), true, Context.NONE) - .getValue(); - String updatedETag = updated.getETag(); - - // Update and check the eTags were changed - try { - searchIndexerClient.createOrUpdateIndexerWithResponse(original, true, Context.NONE); - fail("createOrUpdateDefinition should have failed due to precondition."); - } catch (HttpResponseException ex) { - assertEquals(HttpURLConnection.HTTP_PRECON_FAILED, ex.getResponse().getStatusCode()); - } - - // Check eTags - assertNotNull(originalETag); - assertNotNull(updatedETag); - assertNotEquals(originalETag, updatedETag); - } - - @Test - public void updateIndexerIfNotChangedFailsWhenResourceChangedAsync() { - SearchIndexer indexer = createBaseTestIndexerObject(sharedIndex.getName(), sharedDatasource.getName()); - - Mono> createUpdateAndFailToUpdateMono - = searchIndexerAsyncClient.createOrUpdateIndexerWithResponse(indexer, false).flatMap(response -> { - SearchIndexer original = response.getValue(); - String originalETag = original.getETag(); - indexersToDelete.add(original.getName()); - - return searchIndexerAsyncClient - .createOrUpdateIndexerWithResponse(original.setDescription("an update"), true) - .map(update -> Tuples.of(originalETag, update.getValue().getETag(), original)); - }).doOnNext(etags -> { - assertNotNull(etags.getT1()); - assertNotNull(etags.getT2()); - assertNotEquals(etags.getT1(), etags.getT2()); - }).flatMap(original -> searchIndexerAsyncClient.createOrUpdateIndexerWithResponse(original.getT3(), true)); - - StepVerifier.create(createUpdateAndFailToUpdateMono).verifyErrorSatisfies(throwable -> { - HttpResponseException ex = assertInstanceOf(HttpResponseException.class, throwable); - assertEquals(HttpURLConnection.HTTP_PRECON_FAILED, ex.getResponse().getStatusCode()); - }); - } - - @Test - public void updateIndexerIfNotChangedSucceedsWhenResourceUnchangedSync() { - SearchIndexer indexer = createBaseTestIndexerObject(sharedIndex.getName(), sharedDatasource.getName()); - SearchIndexer original - = searchIndexerClient.createOrUpdateIndexerWithResponse(indexer, false, Context.NONE).getValue(); - String originalETag = original.getETag(); - indexersToDelete.add(original.getName()); - - SearchIndexer updated = searchIndexerClient - .createOrUpdateIndexerWithResponse(original.setDescription("ABrandNewDescription"), true, Context.NONE) - .getValue(); - String updatedETag = updated.getETag(); - - // Check eTags as expected - assertNotNull(originalETag); - assertNotNull(updatedETag); - assertNotEquals(originalETag, updatedETag); - } - - @Test - public void updateIndexerIfNotChangedSucceedsWhenResourceUnchangedAsync() { - SearchIndexer indexer = createBaseTestIndexerObject(sharedIndex.getName(), sharedDatasource.getName()); - - Mono> createAndUpdateIndexerMono - = searchIndexerAsyncClient.createOrUpdateIndexerWithResponse(indexer, false).flatMap(response -> { - SearchIndexer original = response.getValue(); - String originalETag = original.getETag(); - indexersToDelete.add(original.getName()); - - return searchIndexerAsyncClient - .createOrUpdateIndexerWithResponse(original.setDescription("an update"), true) - .map(update -> Tuples.of(originalETag, update.getValue().getETag())); - }); - - StepVerifier.create(createAndUpdateIndexerMono).assertNext(etags -> { - assertNotNull(etags.getT1()); - assertNotNull(etags.getT2()); - assertNotEquals(etags.getT1(), etags.getT2()); - }).verifyComplete(); - } - - @Test - public void canUpdateIndexerSkillsetSync() { - String indexName = sharedIndex.getName(); - String dataSourceName = sharedDatasource.getName(); - - SearchIndexer initial = createBaseTestIndexerObject(indexName, dataSourceName).setIsDisabled(true); - searchIndexerClient.createIndexer(initial); - indexersToDelete.add(initial.getName()); - - SearchIndexer updated = createBaseTestIndexerObject(initial.getName(), indexName, dataSourceName) - .setSkillsetName(sharedSkillset.getName()); - SearchIndexer indexerResponse = searchIndexerClient.createOrUpdateIndexer(updated); - - setSameStartTime(updated, indexerResponse); - assertObjectEquals(updated, indexerResponse, true, "etag"); - } - - @Test - public void canUpdateIndexerSkillsetAsync() { - String indexName = sharedIndex.getName(); - String dataSourceName = sharedDatasource.getName(); - - SearchIndexer initial = createBaseTestIndexerObject(indexName, dataSourceName).setIsDisabled(true); - searchIndexerAsyncClient.createIndexer(initial).block(); - indexersToDelete.add(initial.getName()); - - SearchIndexer updated = createBaseTestIndexerObject(initial.getName(), indexName, dataSourceName) - .setSkillsetName(sharedSkillset.getName()); - SearchIndexer indexerResponse = searchIndexerClient.createOrUpdateIndexer(updated); - - setSameStartTime(updated, indexerResponse); - assertObjectEquals(updated, indexerResponse, true, "etag"); - } - - @Test - public void canCreateIndexerWithSkillsetSync() { - SearchIndexer indexer = createBaseTestIndexerObject(sharedIndex.getName(), sharedDatasource.getName()) - .setSkillsetName(sharedSkillset.getName()); - - createAndValidateIndexerSync(indexer); - } - - @Test - public void canCreateIndexerWithSkillsetAsync() { - SearchIndexer indexer = createBaseTestIndexerObject(sharedIndex.getName(), sharedDatasource.getName()) - .setSkillsetName(sharedSkillset.getName()); - - createAndValidateIndexerAsync(indexer); - } - - /** - * Create a new valid skillset object - * - * @return the newly created skillset object - */ - private static SearchIndexerSkillset createSkillsetObject() { - List inputs - = Arrays.asList(new InputFieldMappingEntry("url").setSource("/document/url"), - new InputFieldMappingEntry("queryString").setSource("/document/queryString")); - - List outputs - = Collections.singletonList(new OutputFieldMappingEntry("text").setTargetName("mytext")); - - List skills - = Collections.singletonList(new OcrSkill(inputs, outputs).setShouldDetectOrientation(true) - .setName("myocr") - .setDescription("Tested OCR skill") - .setContext("/document")); - - return new SearchIndexerSkillset("shared-ocr-skillset") - .setDescription("Skillset for testing default configuration") - .setSkills(skills); - } - - private static SearchIndexerDataSourceConnection createSharedDataSource() { - // create the new data source object for this storage account and container - return SearchIndexerDataSources.createFromAzureBlobStorage("shared-" + BLOB_DATASOURCE_NAME, - STORAGE_CONNECTION_STRING, BLOB_CONTAINER_NAME, "/", "real live blob", - new SoftDeleteColumnDeletionDetectionPolicy().setSoftDeleteColumnName("fieldName") - .setSoftDeleteMarkerValue("someValue")); - } - - SearchIndexer createBaseTestIndexerObject(String targetIndexName, String dataSourceName) { - return createBaseTestIndexerObject(testResourceNamer.randomName("indexer", 32), targetIndexName, - dataSourceName); - } - - SearchIndexer createBaseTestIndexerObject(String name, String targetIndexName, String dataSourceName) { - if (name == null) { - name = testResourceNamer.randomName("indexer", 32); - } - - return new SearchIndexer(name, dataSourceName, targetIndexName) - .setSchedule(new IndexingSchedule(Duration.ofDays(1))); - } - - /** - * This index contains fields that are declared on the live data source we use to test the indexers - * - * @return the newly created Index object - */ - private static SearchIndex createTestIndexForLiveDatasource() { - return new SearchIndex("shared" + IndexersManagementTests.TARGET_INDEX_NAME).setFields(Arrays.asList( - new SearchField("county_name", SearchFieldDataType.STRING).setSearchable(Boolean.FALSE) - .setFilterable(Boolean.TRUE), - new SearchField("state", SearchFieldDataType.STRING).setSearchable(Boolean.TRUE) - .setFilterable(Boolean.TRUE), - new SearchField("feature_id", SearchFieldDataType.STRING).setKey(Boolean.TRUE) - .setSearchable(Boolean.TRUE) - .setFilterable(Boolean.FALSE))); - } - - /** - * Create a new indexer and change its indexing parameters - * - * @return the created indexer - */ - SearchIndexer createIndexerWithDifferentIndexingParameters(SearchIndexer indexer) { - // create a new indexer object - IndexingParameters ip - = new IndexingParameters().setMaxFailedItems(121).setMaxFailedItemsPerBatch(11).setBatchSize(20); - - // modify the indexer - indexer.setParameters(ip); - - return indexer; - } - - SearchIndexer createIndexerWithStorageConfig(String targetIndexName, String dataSourceName) { - return createIndexerWithStorageConfig(null, targetIndexName, dataSourceName); - } - - SearchIndexer createIndexerWithStorageConfig(String name, String targetIndexName, String dataSourceName) { - // create an indexer object - SearchIndexer updatedExpected = createBaseTestIndexerObject(name, targetIndexName, dataSourceName); - - // just adding some(valid) config values for blobs - HashMap config = new HashMap<>(); - config.put("indexedFileNameExtensions", ".pdf,.docx"); - config.put("excludedFileNameExtensions", ".xlsx"); - config.put("dataToExtract", "storageMetadata"); - config.put("failOnUnsupportedContentType", false); - - IndexingParameters ip = new IndexingParameters().setConfiguration(config); - - // modify it - updatedExpected.setParameters(ip); - - return updatedExpected; - } - - void setSameStartTime(SearchIndexer expected, SearchIndexer actual) { - // There ought to be a start time in the response; We just can't know what it is because it would - // make the test timing-dependent. - expected.getSchedule().setStartTime(actual.getSchedule().getStartTime()); - } - - void assertStartAndEndTimeValid(IndexerExecutionResult result) { - assertNotNull(result.getStartTime()); - assertNotEquals(OffsetDateTime.now(), result.getStartTime()); - assertNotNull(result.getEndTime()); - assertNotEquals(OffsetDateTime.now(), result.getEndTime()); - } - - void assertValidSearchIndexerStatus(SearchIndexerStatus indexerExecutionInfo) { - assertEquals(IndexerExecutionStatus.IN_PROGRESS, indexerExecutionInfo.getLastResult().getStatus()); - assertEquals(3, indexerExecutionInfo.getExecutionHistory().size()); - - SearchIndexerLimits limits = indexerExecutionInfo.getLimits(); - assertNotNull(limits); - assertEquals(100000, limits.getMaxDocumentContentCharactersToExtract(), 0); - assertEquals(1000, limits.getMaxDocumentExtractionSize(), 0); - - IndexerExecutionResult newestResult = indexerExecutionInfo.getExecutionHistory().get(0); - IndexerExecutionResult middleResult = indexerExecutionInfo.getExecutionHistory().get(1); - IndexerExecutionResult oldestResult = indexerExecutionInfo.getExecutionHistory().get(2); - - assertEquals(IndexerExecutionStatus.TRANSIENT_FAILURE, newestResult.getStatus()); - assertEquals("The indexer could not connect to the data source", newestResult.getErrorMessage()); - assertStartAndEndTimeValid(newestResult); - - assertEquals(IndexerExecutionStatus.RESET, middleResult.getStatus()); - assertStartAndEndTimeValid(middleResult); - - assertEquals(IndexerExecutionStatus.SUCCESS, oldestResult.getStatus()); - assertEquals(124876, oldestResult.getItemCount()); - assertEquals(2, oldestResult.getFailedItemCount()); - assertEquals("100", oldestResult.getInitialTrackingState()); - assertEquals("200", oldestResult.getFinalTrackingState()); - assertStartAndEndTimeValid(oldestResult); - - assertEquals(2, oldestResult.getErrors().size()); - assertEquals("1", oldestResult.getErrors().get(0).getKey()); - assertEquals("Key field contains unsafe characters", oldestResult.getErrors().get(0).getErrorMessage()); - assertEquals("DocumentExtraction.AzureBlob.MyDataSource", oldestResult.getErrors().get(0).getName()); - assertEquals("The file could not be parsed.", oldestResult.getErrors().get(0).getDetails()); - assertEquals("https://go.microsoft.com/fwlink/?linkid=2049388", - oldestResult.getErrors().get(0).getDocumentationLink()); - - assertEquals("121713", oldestResult.getErrors().get(1).getKey()); - assertEquals("Item is too large", oldestResult.getErrors().get(1).getErrorMessage()); - assertEquals("DocumentExtraction.AzureBlob.DataReader", oldestResult.getErrors().get(1).getName()); - assertEquals("Blob size cannot exceed 256 MB.", oldestResult.getErrors().get(1).getDetails()); - assertEquals("https://go.microsoft.com/fwlink/?linkid=2049388", - oldestResult.getErrors().get(1).getDocumentationLink()); - - assertEquals(1, oldestResult.getWarnings().size()); - assertEquals("2", oldestResult.getWarnings().get(0).getKey()); - assertEquals("Document was truncated to 50000 characters.", oldestResult.getWarnings().get(0).getMessage()); - assertEquals("Enrichment.LanguageDetectionSkill.#4", oldestResult.getWarnings().get(0).getName()); - assertEquals("Try to split the input into smaller chunks using Split skill.", - oldestResult.getWarnings().get(0).getDetails()); - assertEquals("https://go.microsoft.com/fwlink/?linkid=2099692", - oldestResult.getWarnings().get(0).getDocumentationLink()); - } -} diff --git a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/indexes/IndexesTestHelpers.java b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/indexes/IndexesTestHelpers.java deleted file mode 100644 index 1227d3f37bc4..000000000000 --- a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/indexes/IndexesTestHelpers.java +++ /dev/null @@ -1,16 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.search.documents.indexes; - -import com.azure.core.http.HttpPipeline; - -public class IndexesTestHelpers { - public static HttpPipeline getHttpPipeline(SearchIndexClient searchIndexClient) { - return searchIndexClient.getHttpPipeline(); - } - - public static HttpPipeline getHttpPipeline(SearchIndexAsyncClient searchIndexAsyncClient) { - return searchIndexAsyncClient.getHttpPipeline(); - } -} diff --git a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/indexes/NonRestCallTests.java b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/indexes/NonRestCallTests.java deleted file mode 100644 index 763849746ae6..000000000000 --- a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/indexes/NonRestCallTests.java +++ /dev/null @@ -1,46 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.search.documents.indexes; - -import com.azure.core.credential.AzureKeyCredential; -import com.azure.core.test.http.MockHttpResponse; -import org.junit.jupiter.api.parallel.Execution; -import org.junit.jupiter.api.parallel.ExecutionMode; -import org.junit.jupiter.params.ParameterizedTest; -import org.junit.jupiter.params.provider.MethodSource; -import org.reactivestreams.Publisher; -import reactor.core.publisher.Mono; -import reactor.test.StepVerifier; - -import java.util.stream.Stream; - -/** - * Tests non-REST call cases. - */ -@Execution(ExecutionMode.CONCURRENT) -public class NonRestCallTests { - @ParameterizedTest - @MethodSource("apiCallReturnsErrorSupplier") - public void apiCallReturnsError(Publisher apiCall) { - StepVerifier.create(apiCall).verifyError(NullPointerException.class); - } - - static Stream> apiCallReturnsErrorSupplier() { - SearchIndexerAsyncClient client - = new SearchIndexerClientBuilder().httpClient(request -> Mono.just(new MockHttpResponse(request, 200))) - .endpoint("https://fake.com") - .credential(new AzureKeyCredential("fake")) - .buildAsyncClient(); - - return Stream.of(client.createOrUpdateDataSourceConnection(null), - client.createOrUpdateDataSourceConnectionWithResponse(null, true), - client.deleteDataSourceConnectionWithResponse(null, true), - - client.createOrUpdateIndexer(null), client.createOrUpdateIndexerWithResponse(null, true), - client.deleteIndexerWithResponse(null, true), - - client.createSkillset(null), client.createSkillsetWithResponse(null), client.createOrUpdateSkillset(null), - client.createOrUpdateSkillsetWithResponse(null, true), client.deleteSkillsetWithResponse(null, true)); - } -} diff --git a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/indexes/SearchIndexClientBuilderTests.java b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/indexes/SearchIndexClientBuilderTests.java deleted file mode 100644 index fb9f5791c329..000000000000 --- a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/indexes/SearchIndexClientBuilderTests.java +++ /dev/null @@ -1,235 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -package com.azure.search.documents.indexes; - -import com.azure.core.credential.AzureKeyCredential; -import com.azure.core.exception.HttpResponseException; -import com.azure.core.http.HttpClient; -import com.azure.core.http.HttpHeaderName; -import com.azure.core.http.HttpHeaders; -import com.azure.core.http.HttpMethod; -import com.azure.core.http.HttpRequest; -import com.azure.core.http.HttpResponse; -import com.azure.core.http.policy.ExponentialBackoffOptions; -import com.azure.core.http.policy.FixedDelay; -import com.azure.core.http.policy.FixedDelayOptions; -import com.azure.core.http.policy.HttpLogOptions; -import com.azure.core.http.policy.RetryOptions; -import com.azure.core.http.policy.RetryPolicy; -import com.azure.core.test.http.MockHttpResponse; -import com.azure.core.util.ClientOptions; -import com.azure.core.util.CoreUtils; -import com.azure.core.util.DateTimeRfc1123; -import com.azure.core.util.Header; -import com.azure.search.documents.SearchServiceVersion; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.parallel.Execution; -import org.junit.jupiter.api.parallel.ExecutionMode; -import reactor.core.publisher.Flux; -import reactor.core.publisher.Mono; -import reactor.test.StepVerifier; - -import java.io.IOException; -import java.net.MalformedURLException; -import java.net.URL; -import java.security.SecureRandom; -import java.time.Duration; -import java.util.Collections; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.junit.jupiter.api.Assertions.assertTrue; - -@Execution(ExecutionMode.CONCURRENT) -public class SearchIndexClientBuilderTests { - private final AzureKeyCredential searchApiKeyCredential = new AzureKeyCredential("0123"); - private final String searchEndpoint = "https://test.search.windows.net"; - private final SearchServiceVersion apiVersion = SearchServiceVersion.V2020_06_30; - - @Test - public void buildSyncClientTest() { - SearchIndexClient client - = new SearchIndexClientBuilder().httpClient(request -> Mono.just(new MockHttpResponse(request, 200))) - .endpoint(searchEndpoint) - .credential(searchApiKeyCredential) - .serviceVersion(apiVersion) - .buildClient(); - - assertNotNull(client); - assertEquals(SearchIndexClient.class.getSimpleName(), client.getClass().getSimpleName()); - } - - @Test - public void buildSyncClientUsingDefaultApiVersionTest() { - SearchIndexClient client - = new SearchIndexClientBuilder().httpClient(request -> Mono.just(new MockHttpResponse(request, 200))) - .endpoint(searchEndpoint) - .credential(searchApiKeyCredential) - .buildClient(); - - assertNotNull(client); - assertEquals(SearchIndexClient.class.getSimpleName(), client.getClass().getSimpleName()); - } - - @Test - public void buildAsyncClientTest() { - SearchIndexAsyncClient client - = new SearchIndexClientBuilder().httpClient(request -> Mono.just(new MockHttpResponse(request, 200))) - .endpoint(searchEndpoint) - .credential(searchApiKeyCredential) - .serviceVersion(apiVersion) - .buildAsyncClient(); - - assertNotNull(client); - assertEquals(SearchIndexAsyncClient.class.getSimpleName(), client.getClass().getSimpleName()); - } - - @Test - public void buildAsyncClientUsingDefaultApiVersionTest() { - SearchIndexAsyncClient client - = new SearchIndexClientBuilder().httpClient(request -> Mono.just(new MockHttpResponse(request, 200))) - .endpoint(searchEndpoint) - .credential(searchApiKeyCredential) - .buildAsyncClient(); - - assertNotNull(client); - assertEquals(SearchIndexAsyncClient.class.getSimpleName(), client.getClass().getSimpleName()); - } - - @Test - public void whenBuildClientAndVerifyPropertiesThenSuccess() { - SearchIndexClient client - = new SearchIndexClientBuilder().httpClient(request -> Mono.just(new MockHttpResponse(request, 200))) - .endpoint(searchEndpoint) - .credential(searchApiKeyCredential) - .buildClient(); - - assertEquals(searchEndpoint, client.getEndpoint()); - - SearchIndexAsyncClient asyncClient - = new SearchIndexClientBuilder().httpClient(request -> Mono.just(new MockHttpResponse(request, 200))) - .endpoint(searchEndpoint) - .credential(searchApiKeyCredential) - .serviceVersion(apiVersion) - .buildAsyncClient(); - - assertEquals(searchEndpoint, asyncClient.getEndpoint()); - } - - @Test - public void emptyEndpointThrowsIllegalArgumentException() { - assertThrows(IllegalArgumentException.class, () -> new SearchIndexClientBuilder().endpoint("")); - } - - @Test - public void credentialWithEmptyApiKeyThrowsIllegalArgumentException() { - assertThrows(IllegalArgumentException.class, - () -> new SearchIndexClientBuilder().credential(new AzureKeyCredential(""))); - } - - @Test - public void serviceClientFreshDateOnRetry() throws MalformedURLException { - byte[] randomData = new byte[256]; - new SecureRandom().nextBytes(randomData); - SearchIndexAsyncClient searchIndexAsyncClient = new SearchIndexClientBuilder().endpoint(searchEndpoint) - .credential(searchApiKeyCredential) - .retryOptions(new RetryOptions(new FixedDelayOptions(3, Duration.ofSeconds(1)))) - .httpClient(new FreshDateTestClient()) - .buildAsyncClient(); - - StepVerifier - .create(searchIndexAsyncClient.getHttpPipeline().send(request(searchIndexAsyncClient.getEndpoint()))) - .assertNext(response -> assertEquals(200, response.getStatusCode())) - .verifyComplete(); - } - - public static HttpRequest request(String url) throws MalformedURLException { - return new HttpRequest(HttpMethod.HEAD, new URL(url), new HttpHeaders().set(HttpHeaderName.CONTENT_LENGTH, "0"), - Flux.empty()); - } - - public static final class FreshDateTestClient implements HttpClient { - private DateTimeRfc1123 firstDate; - - @Override - public Mono send(HttpRequest request) { - if (firstDate == null) { - firstDate = convertToDateObject(request.getHeaders().getValue(HttpHeaderName.DATE)); - return Mono.error(new IOException("IOException!")); - } - - assert !firstDate.equals(convertToDateObject(request.getHeaders().getValue(HttpHeaderName.DATE))); - return Mono.just(new MockHttpResponse(request, 200)); - } - - private static DateTimeRfc1123 convertToDateObject(String dateHeader) { - if (CoreUtils.isNullOrEmpty(dateHeader)) { - throw new RuntimeException("Failed to set 'Date' header."); - } - - return new DateTimeRfc1123(dateHeader); - } - } - - @SuppressWarnings("deprecation") - @Test - public void clientOptionsIsPreferredOverLogOptions() { - SearchIndexClient searchIndexClient = new SearchIndexClientBuilder().endpoint(searchEndpoint) - .credential(searchApiKeyCredential) - .httpLogOptions(new HttpLogOptions().setApplicationId("anOldApplication")) - .clientOptions(new ClientOptions().setApplicationId("aNewApplication")) - .retryPolicy(new RetryPolicy(new FixedDelay(3, Duration.ofMillis(1)))) - .httpClient(httpRequest -> { - assertTrue(httpRequest.getHeaders().getValue("User-Agent").contains("aNewApplication")); - return Mono.just(new MockHttpResponse(httpRequest, 400)); - }) - .buildClient(); - - assertThrows(HttpResponseException.class, searchIndexClient::getServiceStatistics); - } - - @SuppressWarnings("deprecation") - @Test - public void applicationIdFallsBackToLogOptions() { - SearchIndexClient searchIndexClient = new SearchIndexClientBuilder().endpoint(searchEndpoint) - .credential(searchApiKeyCredential) - .httpLogOptions(new HttpLogOptions().setApplicationId("anOldApplication")) - .retryPolicy(new RetryPolicy(new FixedDelay(3, Duration.ofMillis(1)))) - .httpClient(httpRequest -> { - assertTrue(httpRequest.getHeaders().getValue(HttpHeaderName.USER_AGENT).contains("anOldApplication")); - return Mono.just(new MockHttpResponse(httpRequest, 400)); - }) - .buildClient(); - - assertThrows(HttpResponseException.class, searchIndexClient::getServiceStatistics); - } - - @Test - public void clientOptionHeadersAreAddedLast() { - SearchIndexClient searchIndexClient = new SearchIndexClientBuilder().endpoint(searchEndpoint) - .credential(searchApiKeyCredential) - .clientOptions( - new ClientOptions().setHeaders(Collections.singletonList(new Header("User-Agent", "custom")))) - .retryPolicy(new RetryPolicy(new FixedDelay(3, Duration.ofMillis(1)))) - .httpClient(httpRequest -> { - assertEquals("custom", httpRequest.getHeaders().getValue(HttpHeaderName.USER_AGENT)); - return Mono.just(new MockHttpResponse(httpRequest, 400)); - }) - .buildClient(); - - assertThrows(HttpResponseException.class, searchIndexClient::getServiceStatistics); - } - - @Test - public void bothRetryOptionsAndRetryPolicySet() { - assertThrows(IllegalStateException.class, - () -> new SearchIndexClientBuilder().httpClient(request -> Mono.just(new MockHttpResponse(request, 200))) - .endpoint(searchEndpoint) - .credential(searchApiKeyCredential) - .serviceVersion(apiVersion) - .retryOptions(new RetryOptions(new ExponentialBackoffOptions())) - .retryPolicy(new RetryPolicy()) - .buildClient()); - } -} diff --git a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/indexes/SearchIndexerClientBuilderTests.java b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/indexes/SearchIndexerClientBuilderTests.java deleted file mode 100644 index e09164f4d075..000000000000 --- a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/indexes/SearchIndexerClientBuilderTests.java +++ /dev/null @@ -1,235 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -package com.azure.search.documents.indexes; - -import com.azure.core.credential.AzureKeyCredential; -import com.azure.core.exception.HttpResponseException; -import com.azure.core.http.HttpClient; -import com.azure.core.http.HttpHeaderName; -import com.azure.core.http.HttpHeaders; -import com.azure.core.http.HttpMethod; -import com.azure.core.http.HttpRequest; -import com.azure.core.http.HttpResponse; -import com.azure.core.http.policy.ExponentialBackoffOptions; -import com.azure.core.http.policy.FixedDelay; -import com.azure.core.http.policy.FixedDelayOptions; -import com.azure.core.http.policy.HttpLogOptions; -import com.azure.core.http.policy.RetryOptions; -import com.azure.core.http.policy.RetryPolicy; -import com.azure.core.test.http.MockHttpResponse; -import com.azure.core.util.ClientOptions; -import com.azure.core.util.CoreUtils; -import com.azure.core.util.DateTimeRfc1123; -import com.azure.core.util.Header; -import com.azure.search.documents.SearchServiceVersion; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.parallel.Execution; -import org.junit.jupiter.api.parallel.ExecutionMode; -import reactor.core.publisher.Flux; -import reactor.core.publisher.Mono; -import reactor.test.StepVerifier; - -import java.io.IOException; -import java.net.MalformedURLException; -import java.net.URL; -import java.security.SecureRandom; -import java.time.Duration; -import java.util.Collections; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.junit.jupiter.api.Assertions.assertTrue; - -@Execution(ExecutionMode.CONCURRENT) -public class SearchIndexerClientBuilderTests { - private final AzureKeyCredential searchApiKeyCredential = new AzureKeyCredential("0123"); - private final String searchEndpoint = "https://test.search.windows.net"; - private final SearchServiceVersion apiVersion = SearchServiceVersion.V2020_06_30; - - @Test - public void buildSyncClientTest() { - SearchIndexerClient client - = new SearchIndexerClientBuilder().httpClient(request -> Mono.just(new MockHttpResponse(request, 200))) - .endpoint(searchEndpoint) - .credential(searchApiKeyCredential) - .serviceVersion(apiVersion) - .buildClient(); - - assertNotNull(client); - assertEquals(SearchIndexerClient.class.getSimpleName(), client.getClass().getSimpleName()); - } - - @Test - public void buildSyncClientUsingDefaultApiVersionTest() { - SearchIndexerClient client - = new SearchIndexerClientBuilder().httpClient(request -> Mono.just(new MockHttpResponse(request, 200))) - .endpoint(searchEndpoint) - .credential(searchApiKeyCredential) - .buildClient(); - - assertNotNull(client); - assertEquals(SearchIndexerClient.class.getSimpleName(), client.getClass().getSimpleName()); - } - - @Test - public void buildAsyncClientTest() { - SearchIndexerAsyncClient client - = new SearchIndexerClientBuilder().httpClient(request -> Mono.just(new MockHttpResponse(request, 200))) - .endpoint(searchEndpoint) - .credential(searchApiKeyCredential) - .serviceVersion(apiVersion) - .buildAsyncClient(); - - assertNotNull(client); - assertEquals(SearchIndexerAsyncClient.class.getSimpleName(), client.getClass().getSimpleName()); - } - - @Test - public void buildAsyncClientUsingDefaultApiVersionTest() { - SearchIndexerAsyncClient client - = new SearchIndexerClientBuilder().httpClient(request -> Mono.just(new MockHttpResponse(request, 200))) - .endpoint(searchEndpoint) - .credential(searchApiKeyCredential) - .buildAsyncClient(); - - assertNotNull(client); - assertEquals(SearchIndexerAsyncClient.class.getSimpleName(), client.getClass().getSimpleName()); - } - - @Test - public void whenBuildClientAndVerifyPropertiesThenSuccess() { - SearchIndexerClient client - = new SearchIndexerClientBuilder().httpClient(request -> Mono.just(new MockHttpResponse(request, 200))) - .endpoint(searchEndpoint) - .credential(searchApiKeyCredential) - .buildClient(); - - assertEquals(searchEndpoint, client.getEndpoint()); - - SearchIndexerAsyncClient asyncClient - = new SearchIndexerClientBuilder().httpClient(request -> Mono.just(new MockHttpResponse(request, 200))) - .endpoint(searchEndpoint) - .credential(searchApiKeyCredential) - .serviceVersion(apiVersion) - .buildAsyncClient(); - - assertEquals(searchEndpoint, asyncClient.getEndpoint()); - } - - @Test - public void emptyEndpointThrowsIllegalArgumentException() { - assertThrows(IllegalArgumentException.class, () -> new SearchIndexerClientBuilder().endpoint("")); - } - - @Test - public void credentialWithEmptyApiKeyThrowsIllegalArgumentException() { - assertThrows(IllegalArgumentException.class, - () -> new SearchIndexerClientBuilder().credential(new AzureKeyCredential(""))); - } - - @Test - public void serviceClientFreshDateOnRetry() throws MalformedURLException { - byte[] randomData = new byte[256]; - new SecureRandom().nextBytes(randomData); - SearchIndexerAsyncClient searchIndexerAsyncClient = new SearchIndexerClientBuilder().endpoint(searchEndpoint) - .credential(searchApiKeyCredential) - .retryOptions(new RetryOptions(new FixedDelayOptions(3, Duration.ofSeconds(1)))) - .httpClient(new FreshDateTestClient()) - .buildAsyncClient(); - - StepVerifier - .create(searchIndexerAsyncClient.getHttpPipeline().send(request(searchIndexerAsyncClient.getEndpoint()))) - .assertNext(response -> assertEquals(200, response.getStatusCode())) - .verifyComplete(); - } - - static HttpRequest request(String url) throws MalformedURLException { - return new HttpRequest(HttpMethod.HEAD, new URL(url), new HttpHeaders().set(HttpHeaderName.CONTENT_LENGTH, "0"), - Flux.empty()); - } - - static final class FreshDateTestClient implements HttpClient { - private DateTimeRfc1123 firstDate; - - @Override - public Mono send(HttpRequest request) { - if (firstDate == null) { - firstDate = convertToDateObject(request.getHeaders().getValue(HttpHeaderName.DATE)); - return Mono.error(new IOException("IOException!")); - } - - assert !firstDate.equals(convertToDateObject(request.getHeaders().getValue(HttpHeaderName.DATE))); - return Mono.just(new MockHttpResponse(request, 200)); - } - - private static DateTimeRfc1123 convertToDateObject(String dateHeader) { - if (CoreUtils.isNullOrEmpty(dateHeader)) { - throw new RuntimeException("Failed to set 'Date' header."); - } - - return new DateTimeRfc1123(dateHeader); - } - } - - @SuppressWarnings("deprecation") - @Test - public void clientOptionsIsPreferredOverLogOptions() { - SearchIndexerClient searchIndexerClient = new SearchIndexerClientBuilder().endpoint(searchEndpoint) - .credential(searchApiKeyCredential) - .httpLogOptions(new HttpLogOptions().setApplicationId("anOldApplication")) - .clientOptions(new ClientOptions().setApplicationId("aNewApplication")) - .retryPolicy(new RetryPolicy(new FixedDelay(3, Duration.ofMillis(1)))) - .httpClient(httpRequest -> { - assertTrue(httpRequest.getHeaders().getValue(HttpHeaderName.USER_AGENT).contains("aNewApplication")); - return Mono.just(new MockHttpResponse(httpRequest, 400)); - }) - .buildClient(); - - assertThrows(HttpResponseException.class, () -> searchIndexerClient.getIndexer("anindexer")); - } - - @SuppressWarnings("deprecation") - @Test - public void applicationIdFallsBackToLogOptions() { - SearchIndexerClient searchIndexerClient = new SearchIndexerClientBuilder().endpoint(searchEndpoint) - .credential(searchApiKeyCredential) - .httpLogOptions(new HttpLogOptions().setApplicationId("anOldApplication")) - .retryPolicy(new RetryPolicy(new FixedDelay(3, Duration.ofMillis(1)))) - .httpClient(httpRequest -> { - assertTrue(httpRequest.getHeaders().getValue(HttpHeaderName.USER_AGENT).contains("anOldApplication")); - return Mono.just(new MockHttpResponse(httpRequest, 400)); - }) - .buildClient(); - - assertThrows(HttpResponseException.class, () -> searchIndexerClient.getIndexer("anindexer")); - } - - @Test - public void clientOptionHeadersAreAddedLast() { - SearchIndexerClient searchIndexerClient = new SearchIndexerClientBuilder().endpoint(searchEndpoint) - .credential(searchApiKeyCredential) - .clientOptions( - new ClientOptions().setHeaders(Collections.singletonList(new Header("User-Agent", "custom")))) - .retryPolicy(new RetryPolicy(new FixedDelay(3, Duration.ofMillis(1)))) - .httpClient(httpRequest -> { - assertEquals("custom", httpRequest.getHeaders().getValue(HttpHeaderName.USER_AGENT)); - return Mono.just(new MockHttpResponse(httpRequest, 400)); - }) - .buildClient(); - - assertThrows(HttpResponseException.class, () -> searchIndexerClient.getIndexer("anindexer")); - } - - @Test - public void bothRetryOptionsAndRetryPolicySet() { - assertThrows(IllegalStateException.class, - () -> new SearchIndexerClientBuilder().httpClient(request -> Mono.just(new MockHttpResponse(request, 200))) - .endpoint(searchEndpoint) - .credential(searchApiKeyCredential) - .serviceVersion(apiVersion) - .retryOptions(new RetryOptions(new ExponentialBackoffOptions())) - .retryPolicy(new RetryPolicy()) - .buildClient()); - } -} diff --git a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/indexes/SearchServiceTests.java b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/indexes/SearchServiceTests.java deleted file mode 100644 index 1a13f7106ab2..000000000000 --- a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/indexes/SearchServiceTests.java +++ /dev/null @@ -1,99 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -package com.azure.search.documents.indexes; - -import com.azure.core.http.rest.Response; -import com.azure.core.test.annotation.LiveOnly; -import com.azure.core.util.Context; -import com.azure.search.documents.SearchTestBase; -import com.azure.search.documents.indexes.models.SearchServiceCounters; -import com.azure.search.documents.indexes.models.SearchServiceStatistics; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; -import reactor.test.StepVerifier; - -import static org.junit.jupiter.api.Assertions.assertTrue; - -public class SearchServiceTests extends SearchTestBase { - - @Test - public void getServiceStatsReturnsCorrectDefinitionSync() { - SearchIndexClient serviceClient = getSearchIndexClientBuilder(true).buildClient(); - - validateServiceStatistics(serviceClient.getServiceStatistics()); - } - - @Test - public void getServiceStatsReturnsCorrectDefinitionAsync() { - StepVerifier.create(getSearchIndexClientBuilder(false).buildAsyncClient().getServiceStatistics()) - .assertNext(SearchServiceTests::validateServiceStatistics) - .verifyComplete(); - } - - @Test - public void getServiceStatsReturnsCorrectDefinitionWithResponseSync() { - SearchIndexClient serviceClient = getSearchIndexClientBuilder(true).buildClient(); - - SearchServiceStatistics searchServiceStatistics - = serviceClient.getServiceStatisticsWithResponse(Context.NONE).getValue(); - validateServiceStatistics(searchServiceStatistics); - } - - @Test - public void getServiceStatsReturnsCorrectDefinitionWithResponseAsync() { - StepVerifier.create(getSearchIndexClientBuilder(false).buildAsyncClient().getServiceStatisticsWithResponse()) - .assertNext(response -> validateServiceStatistics(response.getValue())) - .verifyComplete(); - } - - @Test - @LiveOnly - public void getServiceStatsReturnsRequestIdSync() { - SearchIndexClient serviceClient = getSearchIndexClientBuilder(true).buildClient(); - - Response response = serviceClient.getServiceStatisticsWithResponse(Context.NONE); - - /* - * The service will always return a request-id and will conditionally return client-request-id if - * return-client-request-id is set to true. If client-request-id is sent in the request then request-id will - * have the same value. This test validates that client-request-id is returned and that request-id is equal to - * it. - */ - String actualRequestId = response.getHeaders().getValue("request-id"); - String actualClientRequestId = response.getHeaders().getValue("client-request-id"); - - Assertions.assertNotNull(actualClientRequestId); - Assertions.assertEquals(actualClientRequestId, actualRequestId); - validateServiceStatistics(response.getValue()); - } - - @Test - @LiveOnly - public void getServiceStatsReturnsRequestIdAsync() { - StepVerifier.create(getSearchIndexClientBuilder(false).buildAsyncClient().getServiceStatisticsWithResponse()) - .assertNext(response -> { - /* - * The service will always return a request-id and will conditionally return client-request-id if - * return-client-request-id is set to true. If client-request-id is sent in the request then request-id - * will have the same value. This test validates that client-request-id is returned and that request-id - * is equal to it. - */ - String actualRequestId = response.getHeaders().getValue("request-id"); - String actualClientRequestId = response.getHeaders().getValue("client-request-id"); - - Assertions.assertNotNull(actualClientRequestId); - Assertions.assertEquals(actualClientRequestId, actualRequestId); - validateServiceStatistics(response.getValue()); - }) - .verifyComplete(); - } - - private static void validateServiceStatistics(SearchServiceStatistics searchServiceStatistics) { - SearchServiceCounters searchServiceCounters = searchServiceStatistics.getCounters(); - assertTrue(searchServiceCounters.getIndexCounter().getQuota() >= 1); - assertTrue(searchServiceCounters.getIndexerCounter().getQuota() >= 1); - assertTrue(searchServiceCounters.getDataSourceCounter().getQuota() >= 1); - assertTrue(searchServiceCounters.getStorageSizeCounter().getQuota() >= 1); - assertTrue(searchServiceCounters.getSynonymMapCounter().getQuota() >= 1); - } -} diff --git a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/indexes/SkillsSupportedVersionsTests.java b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/indexes/SkillsSupportedVersionsTests.java deleted file mode 100644 index 9a2d9624c5fc..000000000000 --- a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/indexes/SkillsSupportedVersionsTests.java +++ /dev/null @@ -1,71 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.search.documents.indexes; - -import com.azure.search.documents.indexes.models.EntityRecognitionSkill; -import com.azure.search.documents.indexes.models.EntityRecognitionSkillVersion; -import com.azure.search.documents.indexes.models.SentimentSkill; -import org.junit.jupiter.api.function.Executable; -import org.junit.jupiter.api.parallel.Execution; -import org.junit.jupiter.api.parallel.ExecutionMode; -import org.junit.jupiter.params.ParameterizedTest; -import org.junit.jupiter.params.provider.MethodSource; - -import java.util.stream.Stream; - -import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; -import static org.junit.jupiter.api.Assertions.assertThrows; - -/** - * Tests that multi-version skills throw an exception when an unsupported property is set. - */ -@Execution(ExecutionMode.CONCURRENT) -public class SkillsSupportedVersionsTests { - @ParameterizedTest - @MethodSource("throwsAsExpectedSupplier") - public void throwsAsExpected(Executable executable) { - assertThrows(IllegalArgumentException.class, executable); - } - - @SuppressWarnings("deprecation") - static Stream throwsAsExpectedSupplier() { - return Stream.of( - // V1 doesn't support setting a model version. - () -> new EntityRecognitionSkill(null, null).setModelVersion(""), - - // V3 doesn't support setting include typeless entities. - () -> new EntityRecognitionSkill(null, null, EntityRecognitionSkillVersion.V3) - .setTypelessEntitiesIncluded(false), - - // V1 doesn't support setting a model version. - () -> new SentimentSkill(null, null).setModelVersion(""), - - // V1 doesn't support setting include opinion mining. - () -> new SentimentSkill(null, null).setOpinionMiningIncluded(false)); - } - - @ParameterizedTest - @MethodSource("doesNotThrowAsExpectedSupplier") - public void doesNotThrowAsExpected(Executable executable) { - assertDoesNotThrow(executable); - } - - @SuppressWarnings("deprecation") - static Stream doesNotThrowAsExpectedSupplier() { - // Setting null values are fine. - return Stream.of( - // V1 doesn't support setting a model version. - () -> new EntityRecognitionSkill(null, null).setModelVersion(null), - - // V3 doesn't support setting include typeless entities. - () -> new EntityRecognitionSkill(null, null, EntityRecognitionSkillVersion.V3) - .setTypelessEntitiesIncluded(null), - - // V1 doesn't support setting a model version. - () -> new SentimentSkill(null, null).setModelVersion(null), - - // V1 doesn't support setting include opinion mining. - () -> new SentimentSkill(null, null).setOpinionMiningIncluded(null)); - } -} diff --git a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/indexes/SkillsetManagementTests.java b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/indexes/SkillsetManagementTests.java deleted file mode 100644 index 010305262cd8..000000000000 --- a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/indexes/SkillsetManagementTests.java +++ /dev/null @@ -1,1296 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -package com.azure.search.documents.indexes; - -import com.azure.core.exception.HttpResponseException; -import com.azure.core.http.policy.HttpLogDetailLevel; -import com.azure.core.http.policy.HttpLogOptions; -import com.azure.core.http.rest.Response; -import com.azure.core.util.Context; -import com.azure.search.documents.SearchTestBase; -import com.azure.search.documents.indexes.models.ConditionalSkill; -import com.azure.search.documents.indexes.models.DefaultCognitiveServicesAccount; -import com.azure.search.documents.indexes.models.EntityCategory; -import com.azure.search.documents.indexes.models.EntityRecognitionSkill; -import com.azure.search.documents.indexes.models.EntityRecognitionSkillLanguage; -import com.azure.search.documents.indexes.models.EntityRecognitionSkillVersion; -import com.azure.search.documents.indexes.models.ImageAnalysisSkill; -import com.azure.search.documents.indexes.models.ImageAnalysisSkillLanguage; -import com.azure.search.documents.indexes.models.ImageDetail; -import com.azure.search.documents.indexes.models.InputFieldMappingEntry; -import com.azure.search.documents.indexes.models.KeyPhraseExtractionSkill; -import com.azure.search.documents.indexes.models.KeyPhraseExtractionSkillLanguage; -import com.azure.search.documents.indexes.models.LanguageDetectionSkill; -import com.azure.search.documents.indexes.models.MergeSkill; -import com.azure.search.documents.indexes.models.OcrSkill; -import com.azure.search.documents.indexes.models.OcrSkillLanguage; -import com.azure.search.documents.indexes.models.OutputFieldMappingEntry; -import com.azure.search.documents.indexes.models.SearchIndexerSkill; -import com.azure.search.documents.indexes.models.SearchIndexerSkillset; -import com.azure.search.documents.indexes.models.SentimentSkill; -import com.azure.search.documents.indexes.models.SentimentSkillLanguage; -import com.azure.search.documents.indexes.models.SentimentSkillVersion; -import com.azure.search.documents.indexes.models.ShaperSkill; -import com.azure.search.documents.indexes.models.SplitSkill; -import com.azure.search.documents.indexes.models.SplitSkillLanguage; -import com.azure.search.documents.indexes.models.TextSplitMode; -import com.azure.search.documents.indexes.models.VisualFeature; -import com.azure.search.documents.indexes.models.WebApiSkill; -import org.junit.jupiter.api.Disabled; -import org.junit.jupiter.api.Test; -import reactor.core.publisher.Mono; -import reactor.test.StepVerifier; -import reactor.util.function.Tuple2; -import reactor.util.function.Tuples; - -import java.net.HttpURLConnection; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.stream.Collectors; - -import static com.azure.search.documents.TestHelpers.assertHttpResponseException; -import static com.azure.search.documents.TestHelpers.assertObjectEquals; -import static com.azure.search.documents.TestHelpers.verifyHttpResponseError; -import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertInstanceOf; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.junit.jupiter.api.Assertions.assertTrue; - -public class SkillsetManagementTests extends SearchTestBase { - private static final String CONTEXT_VALUE = "/document"; - private static final String OCR_SKILLSET_NAME = "ocr-skillset"; - - private final List skillsetsToDelete = new ArrayList<>(); - - private SearchIndexerClient client; - private SearchIndexerAsyncClient asyncClient; - - @Override - protected void beforeTest() { - super.beforeTest(); - // Disable `("$..source")` sanitizer - if (!interceptorManager.isLiveMode()) { - interceptorManager.removeSanitizers("AZSDK3423"); - } - client = getSearchIndexerClientBuilder(true) - .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS)) - .buildClient(); - asyncClient = getSearchIndexerClientBuilder(false) - .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS)) - .buildAsyncClient(); - } - - @Override - protected void afterTest() { - super.afterTest(); - - for (String skillset : skillsetsToDelete) { - client.deleteSkillset(skillset); - } - } - - @Test - public void createSkillsetReturnsCorrectDefinitionImageAnalysisKeyPhraseSync() { - createAndValidateSkillsetSync(createTestSkillsetImageAnalysisKeyPhrase()); - } - - @Test - public void createSkillsetReturnsCorrectDefinitionImageAnalysisKeyPhraseAsync() { - createAndValidateSkillsetAsync(createTestSkillsetImageAnalysisKeyPhrase()); - } - - @Test - public void createSkillsetReturnsCorrectDefinitionImageAnalysisKeyPhraseWithResponseSync() { - SearchIndexerSkillset expectedSkillset = createTestSkillsetImageAnalysisKeyPhrase(); - Response skillsetResponse - = client.createSkillsetWithResponse(expectedSkillset, Context.NONE); - skillsetsToDelete.add(skillsetResponse.getValue().getName()); - - assertObjectEquals(expectedSkillset, skillsetResponse.getValue(), true, "etag"); - } - - @Test - public void createSkillsetReturnsCorrectDefinitionImageAnalysisKeyPhraseWithResponseAsync() { - SearchIndexerSkillset expectedSkillset = createTestSkillsetImageAnalysisKeyPhrase(); - - StepVerifier.create(asyncClient.createSkillsetWithResponse(expectedSkillset)).assertNext(response -> { - skillsetsToDelete.add(response.getValue().getName()); - assertObjectEquals(expectedSkillset, response.getValue(), true, "etag"); - }).verifyComplete(); - - } - - @Test - public void createSkillsetReturnsCorrectDefinitionLanguageDetectionSync() { - createAndValidateSkillsetSync(createTestSkillsetLanguageDetection()); - } - - @Test - public void createSkillsetReturnsCorrectDefinitionLanguageDetectionAsync() { - createAndValidateSkillsetAsync(createTestSkillsetLanguageDetection()); - } - - @Test - public void createSkillsetReturnsCorrectDefinitionMergeTextSync() { - createAndValidateSkillsetSync(createTestSkillsetMergeText()); - } - - @Test - public void createSkillsetReturnsCorrectDefinitionMergeTextAsync() { - createAndValidateSkillsetAsync(createTestSkillsetMergeText()); - } - - @Test - public void createSkillsetReturnsCorrectDefinitionOcrEntitySync() { - createAndValidateSkillsetSync(createTestSkillsetOcrEntity(null)); - - createAndValidateSkillsetSync(createTestSkillsetOcrEntity( - Arrays.asList(EntityCategory.LOCATION, EntityCategory.ORGANIZATION, EntityCategory.PERSON))); - } - - @Test - public void createSkillsetReturnsCorrectDefinitionOcrEntityAsync() { - createAndValidateSkillsetAsync(createTestSkillsetOcrEntity(null)); - - createAndValidateSkillsetAsync(createTestSkillsetOcrEntity( - Arrays.asList(EntityCategory.LOCATION, EntityCategory.ORGANIZATION, EntityCategory.PERSON))); - } - - @Test - public void createSkillsetReturnsCorrectDefinitionOcrHandwritingSentimentSync() { - createAndValidateSkillsetSync( - createTestSkillsetOcrSentiment(OcrSkillLanguage.PT, SentimentSkillLanguage.PT_PT)); - - createAndValidateSkillsetSync(createTestSkillsetOcrSentiment(OcrSkillLanguage.FI, SentimentSkillLanguage.FI)); - - createAndValidateSkillsetSync(createTestSkillsetOcrSentiment(OcrSkillLanguage.EN, SentimentSkillLanguage.EN)); - } - - @Test - public void createSkillsetReturnsCorrectDefinitionOcrHandwritingSentimentAsync() { - createAndValidateSkillsetAsync( - createTestSkillsetOcrSentiment(OcrSkillLanguage.PT, SentimentSkillLanguage.PT_PT)); - - createAndValidateSkillsetAsync(createTestSkillsetOcrSentiment(OcrSkillLanguage.FI, SentimentSkillLanguage.FI)); - - createAndValidateSkillsetAsync(createTestSkillsetOcrSentiment(OcrSkillLanguage.EN, SentimentSkillLanguage.EN)); - } - - @Test - public void createSkillsetReturnsCorrectDefinitionOcrKeyPhraseSync() { - createAndValidateSkillsetSync( - createTestSkillsetOcrKeyPhrase(OcrSkillLanguage.EN, KeyPhraseExtractionSkillLanguage.EN)); - - createAndValidateSkillsetSync( - createTestSkillsetOcrKeyPhrase(OcrSkillLanguage.FR, KeyPhraseExtractionSkillLanguage.FR)); - - createAndValidateSkillsetSync( - createTestSkillsetOcrKeyPhrase(OcrSkillLanguage.ES, KeyPhraseExtractionSkillLanguage.ES)); - } - - @Test - public void createSkillsetReturnsCorrectDefinitionOcrKeyPhraseAsync() { - createAndValidateSkillsetAsync( - createTestSkillsetOcrKeyPhrase(OcrSkillLanguage.EN, KeyPhraseExtractionSkillLanguage.EN)); - - createAndValidateSkillsetAsync( - createTestSkillsetOcrKeyPhrase(OcrSkillLanguage.FR, KeyPhraseExtractionSkillLanguage.FR)); - - createAndValidateSkillsetAsync( - createTestSkillsetOcrKeyPhrase(OcrSkillLanguage.ES, KeyPhraseExtractionSkillLanguage.ES)); - } - - @Test - public void createSkillsetReturnsCorrectDefinitionOcrShaperSync() { - createAndValidateSkillsetSync(createTestSkillsetOcrShaper()); - } - - @Test - public void createSkillsetReturnsCorrectDefinitionOcrShaperAsync() { - createAndValidateSkillsetAsync(createTestSkillsetOcrShaper()); - } - - @Test - @Disabled("TODO: Service is not responding to api calls. 500 error thrown with little information.") - public void createSkillsetReturnsCorrectDefinitionOcrSplitTextSync() { - createAndValidateSkillsetSync( - createTestSkillsetOcrSplitText(OcrSkillLanguage.EN, SplitSkillLanguage.EN, TextSplitMode.PAGES)); - - createAndValidateSkillsetSync( - createTestSkillsetOcrSplitText(OcrSkillLanguage.FR, SplitSkillLanguage.FR, TextSplitMode.PAGES)); - - // not working - createAndValidateSkillsetSync( - createTestSkillsetOcrSplitText(OcrSkillLanguage.FI, SplitSkillLanguage.FI, TextSplitMode.SENTENCES)); - - // not working - createAndValidateSkillsetSync( - createTestSkillsetOcrSplitText(OcrSkillLanguage.DA, SplitSkillLanguage.DA, TextSplitMode.SENTENCES)); - } - - @Test - @Disabled("TODO: Service is not responding to api calls. 500 error thrown with little information.") - public void createSkillsetReturnsCorrectDefinitionOcrSplitTextAsync() { - createAndValidateSkillsetAsync( - createTestSkillsetOcrSplitText(OcrSkillLanguage.EN, SplitSkillLanguage.EN, TextSplitMode.PAGES)); - - createAndValidateSkillsetAsync( - createTestSkillsetOcrSplitText(OcrSkillLanguage.FR, SplitSkillLanguage.FR, TextSplitMode.PAGES)); - - createAndValidateSkillsetAsync( - createTestSkillsetOcrSplitText(OcrSkillLanguage.FI, SplitSkillLanguage.FI, TextSplitMode.SENTENCES)); - - createAndValidateSkillsetAsync( - createTestSkillsetOcrSplitText(OcrSkillLanguage.DA, SplitSkillLanguage.DA, TextSplitMode.SENTENCES)); - } - - @Test - public void createSkillsetReturnsCorrectDefinitionWithCognitiveServicesDefaultSync() { - createAndValidateSkillsetSync(createSkillsetWithCognitiveServicesKey()); - } - - @Test - public void createSkillsetReturnsCorrectDefinitionWithCognitiveServicesDefaultAsync() { - createAndValidateSkillsetAsync(createSkillsetWithCognitiveServicesKey()); - } - - @Test - public void createSkillsetReturnsCorrectDefinitionWithOcrDefaultSettingsSync() { - createAndValidateSkillsetSync(createSkillsetWithOcrDefaultSettings(false)); - } - - @Test - public void createSkillsetReturnsCorrectDefinitionWithOcrDefaultSettingsAsync() { - createAndValidateSkillsetAsync(createSkillsetWithOcrDefaultSettings(false)); - } - - @Test - public void createSkillsetReturnsCorrectDefinitionWithImageAnalysisDefaultSettingsSync() { - createAndValidateSkillsetSync(createSkillsetWithImageAnalysisDefaultSettings()); - } - - @Test - public void createSkillsetReturnsCorrectDefinitionWithImageAnalysisDefaultSettingsAsync() { - createAndValidateSkillsetAsync(createSkillsetWithImageAnalysisDefaultSettings()); - } - - @Test - public void createSkillsetReturnsCorrectDefinitionWithKeyPhraseExtractionDefaultSettingsSync() { - createAndValidateSkillsetSync(createSkillsetWithKeyPhraseExtractionDefaultSettings()); - } - - @Test - public void createSkillsetReturnsCorrectDefinitionWithKeyPhraseExtractionDefaultSettingsAsync() { - createAndValidateSkillsetAsync(createSkillsetWithKeyPhraseExtractionDefaultSettings()); - } - - @Test - public void createSkillsetReturnsCorrectDefinitionWithMergeDefaultSettingsSync() { - createAndValidateSkillsetSync(createSkillsetWithMergeDefaultSettings()); - } - - @Test - public void createSkillsetReturnsCorrectDefinitionWithMergeDefaultSettingsAsync() { - createAndValidateSkillsetAsync(createSkillsetWithMergeDefaultSettings()); - } - - @Test - public void createSkillsetReturnsCorrectDefinitionWithEntityRecognitionDefaultSettingsSync() { - createAndValidateSkillsetSync(createSkillsetWithEntityRecognitionDefaultSettings()); - } - - @Test - public void createSkillsetReturnsCorrectDefinitionWithEntityRecognitionDefaultSettingsAsync() { - createAndValidateSkillsetAsync(createSkillsetWithEntityRecognitionDefaultSettings()); - } - - @Test - public void getOcrSkillsetReturnsCorrectDefinitionSync() { - SearchIndexerSkillset expected = createSkillsetWithOcrDefaultSettings(false); - client.createSkillset(expected); - skillsetsToDelete.add(expected.getName()); - - SearchIndexerSkillset actual = client.getSkillset(expected.getName()); - assertObjectEquals(expected, actual, true, "etag"); - } - - @Test - public void getOcrSkillsetReturnsCorrectDefinitionAsync() { - SearchIndexerSkillset expected = createSkillsetWithOcrDefaultSettings(false); - asyncClient.createSkillset(expected).block(); - skillsetsToDelete.add(expected.getName()); - - StepVerifier.create(asyncClient.getSkillset(expected.getName())) - .assertNext(actual -> assertObjectEquals(expected, actual, true, "etag")) - .verifyComplete(); - } - - @Test - public void getOcrSkillsetReturnsCorrectDefinitionWithResponseSync() { - SearchIndexerSkillset expected = createSkillsetWithOcrDefaultSettings(false); - client.createSkillset(expected); - skillsetsToDelete.add(expected.getName()); - - SearchIndexerSkillset actual = client.getSkillsetWithResponse(expected.getName(), Context.NONE).getValue(); - assertObjectEquals(expected, actual, true, "etag"); - } - - @Test - public void getOcrSkillsetReturnsCorrectDefinitionWithResponseAsync() { - SearchIndexerSkillset expected = createSkillsetWithOcrDefaultSettings(false); - asyncClient.createSkillset(expected).block(); - skillsetsToDelete.add(expected.getName()); - - StepVerifier.create(asyncClient.getSkillsetWithResponse(expected.getName(), Context.NONE)) - .assertNext(response -> assertObjectEquals(expected, response.getValue(), true, "etag")) - .verifyComplete(); - } - - @Test - public void getOcrSkillsetWithShouldDetectOrientationReturnsCorrectDefinitionSync() { - SearchIndexerSkillset expected = createSkillsetWithOcrDefaultSettings(true); - client.createSkillset(expected); - skillsetsToDelete.add(expected.getName()); - - SearchIndexerSkillset actual = client.getSkillset(expected.getName()); - assertObjectEquals(expected, actual, true, "etag"); - } - - @Test - public void getOcrSkillsetWithShouldDetectOrientationReturnsCorrectDefinitionAsync() { - SearchIndexerSkillset expected = createSkillsetWithOcrDefaultSettings(true); - asyncClient.createSkillset(expected).block(); - skillsetsToDelete.add(expected.getName()); - - StepVerifier.create(asyncClient.getSkillset(expected.getName())) - .assertNext(actual -> assertObjectEquals(expected, actual, true, "etag")) - .verifyComplete(); - } - - @Test - public void createSkillsetReturnsCorrectDefinitionWithSentimentDefaultSettingsSync() { - createAndValidateSkillsetSync(createSkillsetWithSentimentDefaultSettings()); - } - - @Test - public void createSkillsetReturnsCorrectDefinitionWithSentimentDefaultSettingsAsync() { - createAndValidateSkillsetAsync(createSkillsetWithSentimentDefaultSettings()); - } - - @Test - public void createSkillsetReturnsCorrectDefinitionWithSplitDefaultSettingsSync() { - createAndValidateSkillsetSync(createSkillsetWithSplitDefaultSettings()); - } - - @Test - public void createSkillsetReturnsCorrectDefinitionWithSplitDefaultSettingsAsync() { - createAndValidateSkillsetAsync(createSkillsetWithSplitDefaultSettings()); - } - - @Test - public void createCustomSkillsetReturnsCorrectDefinitionSync() { - createAndValidateSkillsetSync(createSkillsetWithCustomSkills()); - } - - @Test - public void createCustomSkillsetReturnsCorrectDefinitionAsync() { - createAndValidateSkillsetAsync(createSkillsetWithCustomSkills()); - } - - private void createAndValidateSkillsetSync(SearchIndexerSkillset expected) { - SearchIndexerSkillset actual = client.createSkillset(expected); - skillsetsToDelete.add(actual.getName()); - - assertObjectEquals(expected, actual, true, "etag"); - } - - private void createAndValidateSkillsetAsync(SearchIndexerSkillset expected) { - StepVerifier.create(asyncClient.createSkillset(expected)).assertNext(actual -> { - skillsetsToDelete.add(actual.getName()); - assertObjectEquals(expected, actual, true, "etag"); - }).verifyComplete(); - } - - @Test - public void getSkillsetThrowsOnNotFoundSync() { - assertHttpResponseException(() -> client.getSkillset("thisdoesnotexist"), HttpURLConnection.HTTP_NOT_FOUND, - "No skillset with the name 'thisdoesnotexist' was found in service"); - } - - @Test - public void getSkillsetThrowsOnNotFoundAsync() { - StepVerifier.create(asyncClient.getSkillset("thisdoesnotexist")) - .verifyErrorSatisfies(throwable -> verifyHttpResponseError(throwable, HttpURLConnection.HTTP_NOT_FOUND, - "No skillset with the name 'thisdoesnotexist' was found in service")); - } - - @Test - public void canCreateAndListSkillsetsSyncAndAsync() { - SearchIndexerSkillset skillset1 = createSkillsetWithCognitiveServicesKey(); - SearchIndexerSkillset skillset2 = createSkillsetWithEntityRecognitionDefaultSettings(); - - client.createSkillset(skillset1); - skillsetsToDelete.add(skillset1.getName()); - client.createSkillset(skillset2); - skillsetsToDelete.add(skillset2.getName()); - - Map expectedSkillsets = new HashMap<>(); - expectedSkillsets.put(skillset1.getName(), skillset1); - expectedSkillsets.put(skillset2.getName(), skillset2); - - Map actualSkillsets = client.listSkillsets() - .stream() - .collect(Collectors.toMap(SearchIndexerSkillset::getName, skillset -> skillset)); - - compareMaps(expectedSkillsets, actualSkillsets, - (expected, actual) -> assertObjectEquals(expected, actual, true)); - - StepVerifier.create(asyncClient.listSkillsets().collectMap(SearchIndexerSkillset::getName)) - .assertNext(actualSkillsetsAsync -> compareMaps(expectedSkillsets, actualSkillsetsAsync, - (expected, actual) -> assertObjectEquals(expected, actual, true))) - .verifyComplete(); - } - - @Test - public void canListSkillsetsWithSelectedFieldSyncAndAsync() { - SearchIndexerSkillset skillset1 = createSkillsetWithCognitiveServicesKey(); - SearchIndexerSkillset skillset2 = createSkillsetWithEntityRecognitionDefaultSettings(); - - client.createSkillset(skillset1); - skillsetsToDelete.add(skillset1.getName()); - client.createSkillset(skillset2); - skillsetsToDelete.add(skillset2.getName()); - - Set expectedSkillsetNames = new HashSet<>(Arrays.asList(skillset1.getName(), skillset2.getName())); - Set actualSkillsetNames = client.listSkillsetNames(Context.NONE).stream().collect(Collectors.toSet()); - - assertEquals(expectedSkillsetNames.size(), actualSkillsetNames.size()); - assertTrue(actualSkillsetNames.containsAll(expectedSkillsetNames)); - - StepVerifier.create(asyncClient.listSkillsetNames().collect(Collectors.toSet())) - .assertNext(actualSkillsetNamesAsync -> { - assertEquals(actualSkillsetNamesAsync.size(), actualSkillsetNames.size()); - assertTrue(actualSkillsetNamesAsync.containsAll(expectedSkillsetNames)); - }) - .verifyComplete(); - } - - @Test - public void deleteSkillsetIsIdempotentSync() { - SearchIndexerSkillset skillset = createSkillsetWithOcrDefaultSettings(false); - - Response deleteResponse = client.deleteSkillsetWithResponse(skillset, false, Context.NONE); - assertEquals(HttpURLConnection.HTTP_NOT_FOUND, deleteResponse.getStatusCode()); - - client.createSkillset(skillset); - - // Delete the same skillset twice - deleteResponse = client.deleteSkillsetWithResponse(skillset, false, Context.NONE); - assertEquals(HttpURLConnection.HTTP_NO_CONTENT, deleteResponse.getStatusCode()); - - deleteResponse = client.deleteSkillsetWithResponse(skillset, false, Context.NONE); - assertEquals(HttpURLConnection.HTTP_NOT_FOUND, deleteResponse.getStatusCode()); - } - - @Test - public void deleteSkillsetIsIdempotentAsync() { - SearchIndexerSkillset skillset = createSkillsetWithOcrDefaultSettings(false); - - StepVerifier.create(asyncClient.deleteSkillsetWithResponse(skillset, false)) - .assertNext(response -> assertEquals(HttpURLConnection.HTTP_NOT_FOUND, response.getStatusCode())) - .verifyComplete(); - - asyncClient.createSkillset(skillset).block(); - - // Delete the same skillset twice - StepVerifier.create(asyncClient.deleteSkillsetWithResponse(skillset, false)) - .assertNext(response -> assertEquals(HttpURLConnection.HTTP_NO_CONTENT, response.getStatusCode())) - .verifyComplete(); - - StepVerifier.create(asyncClient.deleteSkillsetWithResponse(skillset, false)) - .assertNext(response -> assertEquals(HttpURLConnection.HTTP_NOT_FOUND, response.getStatusCode())) - .verifyComplete(); - } - - @Test - public void canCreateAndDeleteSkillsetSync() { - SearchIndexerSkillset expected = createSkillsetWithOcrDefaultSettings(false); - client.createSkillset(expected); - client.deleteSkillset(expected.getName()); - - assertThrows(HttpResponseException.class, () -> client.getSkillset(expected.getName())); - } - - @Test - public void canCreateAndDeleteSkillsetAsync() { - SearchIndexerSkillset expected = createSkillsetWithOcrDefaultSettings(false); - asyncClient.createSkillset(expected).block(); - asyncClient.deleteSkillset(expected.getName()).block(); - - StepVerifier.create(asyncClient.getSkillset(expected.getName())).verifyError(HttpResponseException.class); - } - - @Test - public void createOrUpdateCreatesWhenSkillsetDoesNotExistSync() { - SearchIndexerSkillset expected = createTestOcrSkillset(); - SearchIndexerSkillset actual = client.createOrUpdateSkillset(expected); - skillsetsToDelete.add(actual.getName()); - - assertObjectEquals(expected, actual, true, "etag"); - } - - @Test - public void createOrUpdateCreatesWhenSkillsetDoesNotExistAsync() { - SearchIndexerSkillset expected = createTestOcrSkillset(); - - StepVerifier.create(asyncClient.createOrUpdateSkillset(expected)).assertNext(actual -> { - skillsetsToDelete.add(actual.getName()); - assertObjectEquals(expected, actual, true, "etag"); - }).verifyComplete(); - } - - @Test - public void createOrUpdateCreatesWhenSkillsetDoesNotExistWithResponseSync() { - SearchIndexerSkillset expected = createTestOcrSkillset(); - Response createOrUpdateResponse - = client.createOrUpdateSkillsetWithResponse(expected, false, Context.NONE); - skillsetsToDelete.add(createOrUpdateResponse.getValue().getName()); - - assertEquals(HttpURLConnection.HTTP_CREATED, createOrUpdateResponse.getStatusCode()); - } - - @Test - public void createOrUpdateCreatesWhenSkillsetDoesNotExistWithResponseAsync() { - SearchIndexerSkillset expected = createTestOcrSkillset(); - - StepVerifier.create(asyncClient.createOrUpdateSkillsetWithResponse(expected, false)).assertNext(response -> { - skillsetsToDelete.add(response.getValue().getName()); - assertEquals(HttpURLConnection.HTTP_CREATED, response.getStatusCode()); - }).verifyComplete(); - } - - @Test - public void createOrUpdateUpdatesWhenSkillsetExistsSync() { - SearchIndexerSkillset skillset = createTestOcrSkillset(); - Response createOrUpdateResponse - = client.createOrUpdateSkillsetWithResponse(skillset, false, Context.NONE); - skillsetsToDelete.add(createOrUpdateResponse.getValue().getName()); - assertEquals(HttpURLConnection.HTTP_CREATED, createOrUpdateResponse.getStatusCode()); - SearchIndexerSkillset updatedSkillset = createTestOcrSkillset(2, skillset.getName()); - createOrUpdateResponse = client.createOrUpdateSkillsetWithResponse(updatedSkillset, false, Context.NONE); - assertEquals(HttpURLConnection.HTTP_OK, createOrUpdateResponse.getStatusCode()); - } - - @Test - public void createOrUpdateUpdatesWhenSkillsetExistsAsync() { - SearchIndexerSkillset skillset = createTestOcrSkillset(); - - StepVerifier.create(asyncClient.createOrUpdateSkillsetWithResponse(skillset, false)).assertNext(response -> { - skillsetsToDelete.add(response.getValue().getName()); - assertEquals(HttpURLConnection.HTTP_CREATED, response.getStatusCode()); - }).verifyComplete(); - - StepVerifier - .create(asyncClient.createOrUpdateSkillsetWithResponse(createTestOcrSkillset(2, skillset.getName()), false)) - .assertNext(response -> assertEquals(HttpURLConnection.HTTP_OK, response.getStatusCode())) - .verifyComplete(); - } - - @Test - public void createOrUpdateUpdatesSkillsSync() { - SearchIndexerSkillset skillset = createSkillsetWithOcrDefaultSettings(false); - SearchIndexerSkillset createdSkillset = client.createSkillset(skillset); - skillsetsToDelete.add(createdSkillset.getName()); - - // update skills - createdSkillset.setSkills(getCreateOrUpdateSkills()); - - assertObjectEquals(createdSkillset, client.createOrUpdateSkillset(createdSkillset), true, "etag", - "@odata.etag"); - } - - @Test - public void createOrUpdateUpdatesSkillsAsync() { - SearchIndexerSkillset skillset = createSkillsetWithOcrDefaultSettings(false); - - SearchIndexerSkillset createdSkillset = asyncClient.createSkillset(skillset).map(created -> { - skillsetsToDelete.add(created.getName()); - return created.setSkills(getCreateOrUpdateSkills()); - }).block(); - - StepVerifier.create(asyncClient.createOrUpdateSkillset(createdSkillset)) - .assertNext(updated -> assertObjectEquals(createdSkillset, updated, true, "etag", "@odata.etag")) - .verifyComplete(); - } - - @Test - public void createOrUpdateUpdatesCognitiveServiceSync() { - SearchIndexerSkillset skillset = createSkillsetWithOcrDefaultSettings(false); - SearchIndexerSkillset createdSkillset = client.createSkillset(skillset); - skillsetsToDelete.add(createdSkillset.getName()); - - // update skills - createdSkillset - .setCognitiveServicesAccount(new DefaultCognitiveServicesAccount().setDescription("description")); - - assertObjectEquals(createdSkillset, client.createOrUpdateSkillset(createdSkillset), true, "etag", - "@odata.etag"); - } - - @Test - public void createOrUpdateUpdatesCognitiveServiceAsync() { - SearchIndexerSkillset skillset = createSkillsetWithOcrDefaultSettings(false); - - SearchIndexerSkillset createdSkillset = asyncClient.createSkillset(skillset).map(created -> { - skillsetsToDelete.add(created.getName()); - return created - .setCognitiveServicesAccount(new DefaultCognitiveServicesAccount().setDescription("description")); - }).block(); - - StepVerifier.create(asyncClient.createOrUpdateSkillset(createdSkillset)) - .assertNext(updated -> assertObjectEquals(createdSkillset, updated, true, "etag", "@odata.etag")) - .verifyComplete(); - } - - @Test - public void createSkillsetReturnsCorrectDefinitionShaperWithNestedInputsSync() { - SearchIndexerSkillset expected = createSkillsetWithSharperSkillWithNestedInputs(); - SearchIndexerSkillset actual = client.createSkillset(expected); - skillsetsToDelete.add(actual.getName()); - - assertObjectEquals(expected, actual, true, "etag"); - } - - @Test - public void createSkillsetReturnsCorrectDefinitionShaperWithNestedInputsAsync() { - SearchIndexerSkillset expected = createSkillsetWithSharperSkillWithNestedInputs(); - StepVerifier.create(asyncClient.createSkillset(expected)).assertNext(actual -> { - skillsetsToDelete.add(actual.getName()); - assertObjectEquals(expected, actual, true, "etag"); - }).verifyComplete(); - } - - @Test - public void createSkillsetReturnsCorrectDefinitionConditionalSync() { - SearchIndexerSkillset expected = createTestSkillsetConditional(); - SearchIndexerSkillset actual = client.createSkillset(expected); - skillsetsToDelete.add(expected.getName()); - - assertObjectEquals(expected, actual, true, "etag"); - } - - @Test - public void createSkillsetReturnsCorrectDefinitionConditionalAsync() { - SearchIndexerSkillset expected = createTestSkillsetConditional(); - StepVerifier.create(asyncClient.createSkillset(expected)).assertNext(actual -> { - skillsetsToDelete.add(actual.getName()); - assertObjectEquals(expected, actual, true, "etag"); - }).verifyComplete(); - } - - @Test - public void createOrUpdateSkillsetIfNotExistsSucceedsOnNoResourceSync() { - SearchIndexerSkillset created - = client.createOrUpdateSkillsetWithResponse(createSkillsetWithOcrDefaultSettings(false), true, Context.NONE) - .getValue(); - skillsetsToDelete.add(created.getName()); - - assertNotNull(created.getETag()); - } - - @Test - public void createOrUpdateSkillsetIfNotExistsSucceedsOnNoResourceAsync() { - StepVerifier - .create(asyncClient.createOrUpdateSkillsetWithResponse(createSkillsetWithOcrDefaultSettings(false), true)) - .assertNext(response -> { - skillsetsToDelete.add(response.getValue().getName()); - assertNotNull(response.getValue().getETag()); - }) - .verifyComplete(); - } - - @Test - public void createOrUpdateSkillsetIfExistsSucceedsOnExistingResourceSync() { - SearchIndexerSkillset original = client - .createOrUpdateSkillsetWithResponse(createSkillsetWithOcrDefaultSettings(false), false, Context.NONE) - .getValue(); - skillsetsToDelete.add(original.getName()); - - SearchIndexerSkillset updated - = client.createOrUpdateSkillsetWithResponse(mutateSkillsInSkillset(original), false, Context.NONE) - .getValue(); - - validateETagUpdate(original.getETag(), updated.getETag()); - } - - @Test - public void createOrUpdateSkillsetIfExistsSucceedsOnExistingResourceAsync() { - Mono> createAndUpdateMono - = asyncClient.createOrUpdateSkillsetWithResponse(createSkillsetWithOcrDefaultSettings(false), false) - .flatMap(response -> { - SearchIndexerSkillset original = response.getValue(); - skillsetsToDelete.add(original.getName()); - - return asyncClient.createOrUpdateSkillsetWithResponse(mutateSkillsInSkillset(original), false) - .map(update -> Tuples.of(original.getETag(), update.getValue().getETag())); - }); - - StepVerifier.create(createAndUpdateMono) - .assertNext(etags -> validateETagUpdate(etags.getT1(), etags.getT2())) - .verifyComplete(); - } - - @Test - public void createOrUpdateSkillsetIfNotChangedSucceedsWhenResourceUnchangedSync() { - SearchIndexerSkillset original = client - .createOrUpdateSkillsetWithResponse(createSkillsetWithOcrDefaultSettings(false), false, Context.NONE) - .getValue(); - skillsetsToDelete.add(original.getName()); - - SearchIndexerSkillset updated - = client.createOrUpdateSkillsetWithResponse(mutateSkillsInSkillset(original), true, Context.NONE) - .getValue(); - - validateETagUpdate(original.getETag(), updated.getETag()); - } - - @Test - public void createOrUpdateSkillsetIfNotChangedSucceedsWhenResourceUnchangedAsync() { - Mono> createAndUpdateMono - = asyncClient.createOrUpdateSkillsetWithResponse(createSkillsetWithOcrDefaultSettings(false), false) - .flatMap(response -> { - SearchIndexerSkillset original = response.getValue(); - skillsetsToDelete.add(original.getName()); - - return asyncClient.createOrUpdateSkillsetWithResponse(mutateSkillsInSkillset(original), true) - .map(update -> Tuples.of(original.getETag(), update.getValue().getETag())); - }); - - StepVerifier.create(createAndUpdateMono) - .assertNext(etags -> validateETagUpdate(etags.getT1(), etags.getT2())) - .verifyComplete(); - } - - @Test - public void createOrUpdateSkillsetIfNotChangedFailsWhenResourceChangedSyncAndAsync() { - SearchIndexerSkillset original = client - .createOrUpdateSkillsetWithResponse(createSkillsetWithOcrDefaultSettings(false), false, Context.NONE) - .getValue(); - skillsetsToDelete.add(original.getName()); - - SearchIndexerSkillset updated - = client.createOrUpdateSkillsetWithResponse(mutateSkillsInSkillset(original), true, Context.NONE) - .getValue(); - - // Update and check the eTags were changed - HttpResponseException ex = assertThrows(HttpResponseException.class, - () -> client.createOrUpdateSkillsetWithResponse(original, true, Context.NONE)); - assertEquals(HttpURLConnection.HTTP_PRECON_FAILED, ex.getResponse().getStatusCode()); - - StepVerifier.create(asyncClient.createOrUpdateSkillsetWithResponse(original, true)) - .verifyErrorSatisfies(throwable -> { - HttpResponseException exAsync = assertInstanceOf(HttpResponseException.class, throwable); - assertEquals(HttpURLConnection.HTTP_PRECON_FAILED, exAsync.getResponse().getStatusCode()); - }); - - validateETagUpdate(original.getETag(), updated.getETag()); - } - - @Test - public void deleteSkillsetIfNotChangedWorksOnlyOnCurrentResourceSync() { - SearchIndexerSkillset stale - = client.createOrUpdateSkillsetWithResponse(createSkillsetWithOcrDefaultSettings(false), true, Context.NONE) - .getValue(); - - SearchIndexerSkillset current = client.createOrUpdateSkillsetWithResponse(stale, true, Context.NONE).getValue(); - - HttpResponseException ex = assertThrows(HttpResponseException.class, - () -> client.deleteSkillsetWithResponse(stale, true, Context.NONE)); - assertEquals(HttpURLConnection.HTTP_PRECON_FAILED, ex.getResponse().getStatusCode()); - - assertDoesNotThrow(() -> client.deleteSkillsetWithResponse(current, true, Context.NONE)); - } - - @Test - public void deleteSkillsetIfNotChangedWorksOnlyOnCurrentResourceAsync() { - SearchIndexerSkillset stale - = asyncClient.createOrUpdateSkillsetWithResponse(createSkillsetWithOcrDefaultSettings(false), true) - .map(Response::getValue) - .block(); - - SearchIndexerSkillset current - = asyncClient.createOrUpdateSkillsetWithResponse(stale, true).map(Response::getValue).block(); - - StepVerifier.create(asyncClient.deleteSkillsetWithResponse(stale, true)).verifyErrorSatisfies(throwable -> { - HttpResponseException ex = assertInstanceOf(HttpResponseException.class, throwable); - assertEquals(HttpURLConnection.HTTP_PRECON_FAILED, ex.getResponse().getStatusCode()); - }); - - StepVerifier.create(asyncClient.deleteSkillsetWithResponse(current, true)).expectNextCount(1).verifyComplete(); - } - - @Test - public void deleteSkillsetIfExistsWorksOnlyWhenResourceExistsSyncAndAsync() { - SearchIndexerSkillset skillset = client - .createOrUpdateSkillsetWithResponse(createSkillsetWithOcrDefaultSettings(false), false, Context.NONE) - .getValue(); - - client.deleteSkillsetWithResponse(skillset, true, Context.NONE); - - HttpResponseException ex = assertThrows(HttpResponseException.class, - () -> client.deleteSkillsetWithResponse(skillset, true, Context.NONE)); - assertEquals(HttpURLConnection.HTTP_PRECON_FAILED, ex.getResponse().getStatusCode()); - - StepVerifier.create(asyncClient.deleteSkillsetWithResponse(skillset, true)).verifyErrorSatisfies(throwable -> { - HttpResponseException exAsync = assertInstanceOf(HttpResponseException.class, throwable); - assertEquals(HttpURLConnection.HTTP_PRECON_FAILED, exAsync.getResponse().getStatusCode()); - }); - } - - private static InputFieldMappingEntry simpleInputFieldMappingEntry(String name, String source) { - return new InputFieldMappingEntry(name).setSource(source); - } - - private static OutputFieldMappingEntry createOutputFieldMappingEntry(String name, String targetName) { - return new OutputFieldMappingEntry(name).setTargetName(targetName); - } - - SearchIndexerSkillset createTestSkillsetImageAnalysisKeyPhrase() { - List skills = new ArrayList<>(); - - List inputs = Arrays.asList(simpleInputFieldMappingEntry("url", "/document/url"), - simpleInputFieldMappingEntry("queryString", "/document/queryString")); - - List outputs - = Collections.singletonList(createOutputFieldMappingEntry("description", "mydescription")); - - skills.add(new ImageAnalysisSkill(inputs, outputs).setVisualFeatures(new ArrayList<>(VisualFeature.values())) - .setDetails(new ArrayList<>(ImageDetail.values())) - .setDefaultLanguageCode(ImageAnalysisSkillLanguage.EN) - .setName("myimage") - .setDescription("Tested image analysis skill") - .setContext(CONTEXT_VALUE)); - - inputs = Collections.singletonList(simpleInputFieldMappingEntry("text", "/document/mydescription/*/Tags/*")); - outputs = Collections.singletonList(createOutputFieldMappingEntry("keyPhrases", "myKeyPhrases")); - skills.add( - new KeyPhraseExtractionSkill(inputs, outputs).setDefaultLanguageCode(KeyPhraseExtractionSkillLanguage.EN) - .setName("mykeyphrases") - .setDescription("Tested Key Phrase skill") - .setContext(CONTEXT_VALUE)); - - return new SearchIndexerSkillset(testResourceNamer.randomName("image-analysis-key-phrase-skillset", 48)) - .setDescription("Skillset for testing") - .setSkills(skills); - } - - SearchIndexerSkillset createTestSkillsetLanguageDetection() { - List inputs - = Collections.singletonList(simpleInputFieldMappingEntry("text", "/document/text")); - - List outputs - = Collections.singletonList(createOutputFieldMappingEntry("languageCode", "myLanguageCode")); - - List skills - = Collections.singletonList(new LanguageDetectionSkill(inputs, outputs).setName("mylanguage") - .setDescription("Tested Language Detection skill") - .setContext(CONTEXT_VALUE)); - - return new SearchIndexerSkillset(testResourceNamer.randomName("language-detection-skillset", 48)) - .setDescription("Skillset for testing") - .setSkills(skills); - } - - SearchIndexerSkillset createTestSkillsetMergeText() { - List inputs = Arrays.asList(simpleInputFieldMappingEntry("text", "/document/text"), - simpleInputFieldMappingEntry("itemsToInsert", "/document/textitems"), - simpleInputFieldMappingEntry("offsets", "/document/offsets")); - - List outputs - = Collections.singletonList(createOutputFieldMappingEntry("mergedText", "myMergedText")); - - List skills - = Collections.singletonList(new MergeSkill(inputs, outputs).setInsertPostTag("__e") - .setInsertPreTag("__") - .setName("mymerge") - .setDescription("Tested Merged Text skill") - .setContext(CONTEXT_VALUE)); - - return new SearchIndexerSkillset(testResourceNamer.randomName("merge-text-skillset", 48)) - .setDescription("Skillset for testing") - .setSkills(skills); - } - - SearchIndexerSkillset createTestSkillsetOcrShaper() { - List skills = new ArrayList<>(); - List inputs = Arrays.asList(simpleInputFieldMappingEntry("url", "/document/url"), - simpleInputFieldMappingEntry("queryString", "/document/queryString")); - - List outputs - = Collections.singletonList(createOutputFieldMappingEntry("text", "mytext")); - - skills.add(new OcrSkill(inputs, outputs).setDefaultLanguageCode(OcrSkillLanguage.EN) - .setName("myocr") - .setDescription("Tested OCR skill") - .setContext(CONTEXT_VALUE)); - - inputs = Collections.singletonList(simpleInputFieldMappingEntry("text", "/document/mytext")); - outputs = Collections.singletonList(createOutputFieldMappingEntry("output", "myOutput")); - skills.add(new ShaperSkill(inputs, outputs).setName("mysharper") - .setDescription("Tested Shaper skill") - .setContext(CONTEXT_VALUE)); - - return new SearchIndexerSkillset(testResourceNamer.randomName("ocr-shaper-skillset", 48)) - .setDescription("Skillset for testing") - .setSkills(skills); - } - - SearchIndexerSkillset createSkillsetWithCognitiveServicesKey() { - List inputs = Arrays.asList(simpleInputFieldMappingEntry("url", "/document/url"), - simpleInputFieldMappingEntry("queryString", "/document/queryString")); - - List outputs - = Collections.singletonList(createOutputFieldMappingEntry("text", "mytext")); - - List skills - = Collections.singletonList(new OcrSkill(inputs, outputs).setDefaultLanguageCode(OcrSkillLanguage.EN) - .setName("myocr") - .setDescription("Tested OCR skill") - .setContext(CONTEXT_VALUE)); - - return new SearchIndexerSkillset(testResourceNamer.randomName("cognitive-services-key-skillset", 48), skills) - .setDescription("Skillset for testing") - .setCognitiveServicesAccount(new DefaultCognitiveServicesAccount()); - } - - SearchIndexerSkillset createTestSkillsetConditional() { - List inputs - = Arrays.asList(simpleInputFieldMappingEntry("condition", "= $(/document/language) == null"), - simpleInputFieldMappingEntry("whenTrue", "= 'es'"), - simpleInputFieldMappingEntry("whenFalse", "= $(/document/language)")); - - List outputs - = Collections.singletonList(createOutputFieldMappingEntry("output", "myLanguageCode")); - - List skills - = Collections.singletonList(new ConditionalSkill(inputs, outputs).setName("myconditional") - .setDescription("Tested Conditional skill") - .setContext(CONTEXT_VALUE)); - - return new SearchIndexerSkillset(testResourceNamer.randomName("conditional-skillset", 48)) - .setDescription("Skillset for testing") - .setSkills(skills); - } - - static SearchIndexerSkillset mutateSkillsInSkillset(SearchIndexerSkillset skillset) { - return skillset.setSkills(new KeyPhraseExtractionSkill( - Collections.singletonList(simpleInputFieldMappingEntry("text", "/document/mydescription/*/Tags/*")), - Collections.singletonList(createOutputFieldMappingEntry("keyPhrases", "myKeyPhrases"))) - .setDefaultLanguageCode(KeyPhraseExtractionSkillLanguage.EN) - .setName("mykeyphrases") - .setDescription("Tested Key Phrase skill") - .setContext(CONTEXT_VALUE)); - } - - SearchIndexerSkillset createTestSkillsetOcrEntity(List categories) { - List skills = new ArrayList<>(); - List inputs = Arrays.asList(simpleInputFieldMappingEntry("url", "/document/url"), - simpleInputFieldMappingEntry("queryString", "/document/queryString")); - - List outputs - = Collections.singletonList(createOutputFieldMappingEntry("text", "mytext")); - - skills.add(new OcrSkill(inputs, outputs).setDefaultLanguageCode(OcrSkillLanguage.EN) - .setName("myocr") - .setDescription("Tested OCR skill") - .setContext(CONTEXT_VALUE)); - - inputs = Collections.singletonList(simpleInputFieldMappingEntry("text", "/document/mytext")); - outputs = Collections.singletonList(createOutputFieldMappingEntry("namedEntities", "myEntities")); - skills - .add(new EntityRecognitionSkill(inputs, outputs, EntityRecognitionSkillVersion.V3).setCategories(categories) - .setDefaultLanguageCode(EntityRecognitionSkillLanguage.EN) - .setMinimumPrecision(0.5) - .setName("myentity") - .setDescription("Tested Entity Recognition skill") - .setContext(CONTEXT_VALUE)); - - return new SearchIndexerSkillset(testResourceNamer.randomName("ocr-entity-skillset", 48), skills) - .setDescription("Skillset for testing"); - } - - SearchIndexerSkillset createTestSkillsetOcrSentiment(OcrSkillLanguage ocrLanguageCode, - SentimentSkillLanguage sentimentLanguageCode) { - List skills = new ArrayList<>(); - List inputs = Arrays.asList(simpleInputFieldMappingEntry("url", "/document/url"), - simpleInputFieldMappingEntry("queryString", "/document/queryString")); - - List outputs - = Collections.singletonList(createOutputFieldMappingEntry("text", "mytext")); - skills.add(new OcrSkill(inputs, outputs).setDefaultLanguageCode(ocrLanguageCode) - .setName("myocr") - .setDescription("Tested OCR skill") - .setContext(CONTEXT_VALUE)); - - inputs = Collections.singletonList(simpleInputFieldMappingEntry("text", "/document/mytext")); - outputs = Collections.singletonList(createOutputFieldMappingEntry("confidenceScores", "mySentiment")); - skills.add( - new SentimentSkill(inputs, outputs, SentimentSkillVersion.V3).setDefaultLanguageCode(sentimentLanguageCode) - .setName("mysentiment") - .setDescription("Tested Sentiment skill") - .setContext(CONTEXT_VALUE)); - - return new SearchIndexerSkillset(testResourceNamer.randomName("ocr-sentiment-skillset", 48), skills) - .setDescription("Skillset for testing"); - } - - SearchIndexerSkillset createTestSkillsetOcrKeyPhrase(OcrSkillLanguage ocrLanguageCode, - KeyPhraseExtractionSkillLanguage keyPhraseLanguageCode) { - List skills = new ArrayList<>(); - List inputs = Arrays.asList(simpleInputFieldMappingEntry("url", "/document/url"), - simpleInputFieldMappingEntry("queryString", "/document/queryString")); - - List outputs - = Collections.singletonList(createOutputFieldMappingEntry("text", "mytext")); - - skills.add(new OcrSkill(inputs, outputs).setDefaultLanguageCode(ocrLanguageCode) - .setName("myocr") - .setDescription("Tested OCR skill") - .setContext(CONTEXT_VALUE)); - - inputs = Collections.singletonList(simpleInputFieldMappingEntry("text", "/document/mytext")); - outputs = Collections.singletonList(createOutputFieldMappingEntry("keyPhrases", "myKeyPhrases")); - skills.add(new KeyPhraseExtractionSkill(inputs, outputs).setDefaultLanguageCode(keyPhraseLanguageCode) - .setName("mykeyphrases") - .setDescription("Tested Key Phrase skill") - .setContext(CONTEXT_VALUE)); - - return new SearchIndexerSkillset(testResourceNamer.randomName("ocr-key-phrase-skillset", 48), skills) - .setDescription("Skillset for testing"); - } - - SearchIndexerSkillset createTestSkillsetOcrSplitText(OcrSkillLanguage ocrLanguageCode, - SplitSkillLanguage splitLanguageCode, TextSplitMode textSplitMode) { - List skills = new ArrayList<>(); - List inputs = Arrays.asList(simpleInputFieldMappingEntry("url", "/document/url"), - simpleInputFieldMappingEntry("queryString", "/document/queryString")); - - List outputs - = Collections.singletonList(createOutputFieldMappingEntry("text", "mytext")); - - skills.add(new OcrSkill(inputs, outputs).setDefaultLanguageCode(ocrLanguageCode) - .setName("myocr") - .setDescription("Tested OCR skill") - .setContext(CONTEXT_VALUE)); - - inputs = Collections.singletonList(simpleInputFieldMappingEntry("text", "/document/mytext")); - outputs = Collections.singletonList(createOutputFieldMappingEntry("textItems", "myTextItems")); - skills.add(new SplitSkill(inputs, outputs).setDefaultLanguageCode(splitLanguageCode) - .setTextSplitMode(textSplitMode) - .setName("mysplit") - .setDescription("Tested Split skill") - .setContext(CONTEXT_VALUE)); - - return new SearchIndexerSkillset(testResourceNamer.randomName("ocr-split-text-skillset", 48), skills) - .setDescription("Skillset for testing"); - } - - SearchIndexerSkillset createTestOcrSkillset() { - return createTestOcrSkillset(1, testResourceNamer.randomName("testskillset", 48)); - } - - SearchIndexerSkillset createTestOcrSkillset(int repeat, String name) { - List skills = new ArrayList<>(); - - List inputs = Arrays.asList(simpleInputFieldMappingEntry("url", "/document/url"), - simpleInputFieldMappingEntry("queryString", "/document/queryString")); - - for (int i = 0; i < repeat; i++) { - List outputs - = Collections.singletonList(createOutputFieldMappingEntry("text", "mytext" + i)); - - skills.add(new OcrSkill(inputs, outputs).setDefaultLanguageCode(OcrSkillLanguage.EN) - .setShouldDetectOrientation(false) - .setName("myocr-" + i) - .setDescription("Tested OCR skill") - .setContext(CONTEXT_VALUE)); - } - - return new SearchIndexerSkillset(name, skills).setDescription("Skillset for testing OCR"); - } - - SearchIndexerSkillset createSkillsetWithOcrDefaultSettings(Boolean shouldDetectOrientation) { - List inputs = Arrays.asList(simpleInputFieldMappingEntry("url", "/document/url"), - simpleInputFieldMappingEntry("queryString", "/document/queryString")); - - List outputs - = Collections.singletonList(createOutputFieldMappingEntry("text", "mytext")); - - List skills = Collections - .singletonList(new OcrSkill(inputs, outputs).setShouldDetectOrientation(shouldDetectOrientation) - .setName("myocr") - .setDescription("Tested OCR skill") - .setContext(CONTEXT_VALUE)); - - return new SearchIndexerSkillset(testResourceNamer.randomName(SkillsetManagementTests.OCR_SKILLSET_NAME, 48), - skills).setDescription("Skillset for testing default configuration"); - } - - SearchIndexerSkillset createSkillsetWithImageAnalysisDefaultSettings() { - List inputs = Arrays.asList(simpleInputFieldMappingEntry("url", "/document/url"), - simpleInputFieldMappingEntry("queryString", "/document/queryString")); - - List outputs - = Collections.singletonList(createOutputFieldMappingEntry("description", "mydescription")); - - List skills - = Collections.singletonList(new ImageAnalysisSkill(inputs, outputs).setName("myimage") - .setDescription("Tested image analysis skill") - .setContext(CONTEXT_VALUE)); - - return new SearchIndexerSkillset(testResourceNamer.randomName("image-analysis-skillset", 48), skills) - .setDescription("Skillset for testing default configuration"); - } - - SearchIndexerSkillset createSkillsetWithKeyPhraseExtractionDefaultSettings() { - List inputs - = Collections.singletonList(simpleInputFieldMappingEntry("text", "/document/myText")); - - List outputs - = Collections.singletonList(createOutputFieldMappingEntry("keyPhrases", "myKeyPhrases")); - - List skills - = Collections.singletonList(new KeyPhraseExtractionSkill(inputs, outputs).setName("mykeyphrases") - .setDescription("Tested Key Phrase skill") - .setContext(CONTEXT_VALUE)); - - return new SearchIndexerSkillset(testResourceNamer.randomName("key-phrase-extraction-skillset", 48), skills) - .setDescription("Skillset for testing default configuration"); - } - - SearchIndexerSkillset createSkillsetWithMergeDefaultSettings() { - List inputs = Arrays.asList(simpleInputFieldMappingEntry("text", "/document/text"), - simpleInputFieldMappingEntry("itemsToInsert", "/document/textitems"), - simpleInputFieldMappingEntry("offsets", "/document/offsets")); - - List outputs - = Collections.singletonList(createOutputFieldMappingEntry("mergedText", "myMergedText")); - - List skills = Collections.singletonList(new MergeSkill(inputs, outputs).setName("mymerge") - .setDescription("Tested Merged Text skill") - .setContext(CONTEXT_VALUE)); - - return new SearchIndexerSkillset(testResourceNamer.randomName("merge-skillset", 48), skills) - .setDescription("Skillset for testing default configuration"); - } - - SearchIndexerSkillset createSkillsetWithSentimentDefaultSettings() { - List inputs - = Collections.singletonList(simpleInputFieldMappingEntry("text", "/document/mytext")); - - List outputs - = Collections.singletonList(createOutputFieldMappingEntry("confidenceScores", "mySentiment")); - - List skills = Collections - .singletonList(new SentimentSkill(inputs, outputs, SentimentSkillVersion.V3).setName("mysentiment") - .setDescription("Tested Sentiment skill") - .setContext(CONTEXT_VALUE)); - - return new SearchIndexerSkillset(testResourceNamer.randomName("sentiment-skillset", 48), skills) - .setDescription("Skillset for testing default configuration"); - } - - SearchIndexerSkillset createSkillsetWithEntityRecognitionDefaultSettings() { - List inputs - = Collections.singletonList(simpleInputFieldMappingEntry("text", "/document/mytext")); - - List outputs - = Collections.singletonList(createOutputFieldMappingEntry("namedEntities", "myEntities")); - - List skills = Collections.singletonList( - new EntityRecognitionSkill(inputs, outputs, EntityRecognitionSkillVersion.V3).setName("myentity") - .setDescription("Tested Entity Recognition skill") - .setContext(CONTEXT_VALUE)); - - return new SearchIndexerSkillset(testResourceNamer.randomName("entity-recognition-skillset", 48), skills) - .setDescription("Skillset for testing default configuration"); - } - - SearchIndexerSkillset createSkillsetWithSplitDefaultSettings() { - List inputs - = Collections.singletonList(simpleInputFieldMappingEntry("text", "/document/mytext")); - - List outputs - = Collections.singletonList(createOutputFieldMappingEntry("textItems", "myTextItems")); - - List skills - = Collections.singletonList(new SplitSkill(inputs, outputs).setTextSplitMode(TextSplitMode.PAGES) - .setName("mysplit") - .setDescription("Tested Split skill") - .setContext(CONTEXT_VALUE)); - - return new SearchIndexerSkillset(testResourceNamer.randomName("split-skillset", 48), skills) - .setDescription("Skillset for testing default configuration"); - } - - SearchIndexerSkillset createSkillsetWithCustomSkills() { - HashMap headers = new HashMap<>(); - headers.put("Ocp-Apim-Subscription-Key", "foobar"); - - List inputs - = Collections.singletonList(simpleInputFieldMappingEntry("text", "/document/mytext")); - - List outputs - = Collections.singletonList(createOutputFieldMappingEntry("textItems", "myTextItems")); - - SearchIndexerSkill webApiSkill = new WebApiSkill(inputs, outputs, - "https://indexer-e2e-webskill.azurewebsites.net/api/InvokeTextAnalyticsV3?code=foo").setHttpMethod("POST") - .setHttpHeaders(headers) - .setName("webapi-skill") - .setDescription("Calls an Azure function, which in turn calls Bing Entity Search"); - - return new SearchIndexerSkillset(testResourceNamer.randomName("custom-skillset", 48), - Collections.singletonList(webApiSkill)).setDescription("Skillset for testing custom skillsets"); - } - - SearchIndexerSkillset createSkillsetWithSharperSkillWithNestedInputs() { - List inputs = createNestedInputFieldMappingEntry(); - List outputs = createOutputFieldMappingEntry(); - - List skills = new ArrayList<>(); - skills.add(new ShaperSkill(inputs, outputs).setName("myshaper") - .setDescription("Tested Shaper skill") - .setContext(CONTEXT_VALUE)); - - return new SearchIndexerSkillset(testResourceNamer.randomName("nested-skillset-with-sharperskill", 48), skills) - .setDescription("Skillset for testing"); - } - - private static List createNestedInputFieldMappingEntry() { - return Collections.singletonList(new InputFieldMappingEntry("doc").setSourceContext("/document") - .setInputs(Arrays.asList(simpleInputFieldMappingEntry("text", "/document/content"), - simpleInputFieldMappingEntry("images", "/document/normalized_images/*")))); - } - - private static List createOutputFieldMappingEntry() { - return Collections.singletonList(createOutputFieldMappingEntry("output", "myOutput")); - } - - private static List getCreateOrUpdateSkills() { - return Collections.singletonList(new KeyPhraseExtractionSkill( - Collections.singletonList(simpleInputFieldMappingEntry("text", "/document/mytext")), - Collections.singletonList(createOutputFieldMappingEntry("keyPhrases", "myKeyPhrases"))) - .setDefaultLanguageCode(KeyPhraseExtractionSkillLanguage.EN) - .setName("mykeyphrases") - .setDescription("Tested Key Phrase skill") - .setContext(CONTEXT_VALUE)); - } -} diff --git a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/indexes/SpatialFormatterTests.java b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/indexes/SpatialFormatterTests.java deleted file mode 100644 index dc837566c721..000000000000 --- a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/indexes/SpatialFormatterTests.java +++ /dev/null @@ -1,173 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.search.documents.indexes; - -import com.azure.core.models.GeoLineString; -import com.azure.core.models.GeoLinearRing; -import com.azure.core.models.GeoPolygon; -import com.azure.core.models.GeoPosition; -import com.azure.core.util.logging.ClientLogger; -import com.azure.search.documents.implementation.util.SpatialFormatter; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.parallel.Execution; -import org.junit.jupiter.api.parallel.ExecutionMode; -import org.junit.jupiter.params.ParameterizedTest; -import org.junit.jupiter.params.provider.Arguments; -import org.junit.jupiter.params.provider.MethodSource; -import reactor.util.function.Tuple2; -import reactor.util.function.Tuples; - -import java.util.Arrays; -import java.util.Collections; -import java.util.List; -import java.util.stream.Stream; - -import static com.azure.search.documents.TestHelpers.createGeographyPolygon; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertThrows; - -/** - * Tests {@link SpatialFormatter}. - */ -@Execution(ExecutionMode.CONCURRENT) -public class SpatialFormatterTests { - private final ClientLogger logger = new ClientLogger(SpatialFormatterTests.class); - - @ParameterizedTest - @MethodSource("encodePointSupplier") - public void encodePoint(double longitude, double latitude, String expected) { - assertEquals(expected, SpatialFormatter.encodePoint(longitude, latitude)); - } - - static Stream encodePointSupplier() { - final String pointFormat = "geography'POINT(%s %s)'"; - - return Stream.of(Arguments.of(0D, 0D, String.format(pointFormat, "0", "0")), - Arguments.of(0.0D, 0.0D, String.format(pointFormat, "0", "0")), - Arguments.of(0.000000000000D, 0.000000000000D, String.format(pointFormat, "0", "0")), - Arguments.of(0.01D, 0.01D, String.format(pointFormat, "0.01", "0.01")), - Arguments.of(0.010000000000D, 0.010000000000D, String.format(pointFormat, "0.01", "0.01")), - Arguments.of(-0D, -0D, String.format(pointFormat, "-0", "-0")), - Arguments.of(-0.0D, -0.0D, String.format(pointFormat, "-0", "-0")), - Arguments.of(-0.01D, -0.01D, String.format(pointFormat, "-0.01", "-0.01")), - Arguments.of(-0.000000000000D, -0.000000000000D, String.format(pointFormat, "-0", "-0")), - Arguments.of(-0.010000000000D, -0.010000000000D, String.format(pointFormat, "-0.01", "-0.01"))); - } - - @Test - public void geoLineStringWithLessThanFourPointsThrows() { - GeoLineString lineString = new GeoLineString(Collections.singletonList(new GeoPosition(0, 0))); - - assertThrows(IllegalArgumentException.class, () -> SpatialFormatter.encodePolygon(lineString, logger)); - } - - @Test - public void nonClosingGeoLineStringThrows() { - GeoLineString lineString = new GeoLineString( - Arrays.asList(new GeoPosition(0, 0), new GeoPosition(0, 1), new GeoPosition(0, 2), new GeoPosition(0, 3))); - - assertThrows(IllegalArgumentException.class, () -> SpatialFormatter.encodePolygon(lineString, logger)); - } - - @ParameterizedTest - @MethodSource("encodeGeoLineStringPolygonSupplier") - public void encodeGeoLineStringPolygon(GeoLineString lineString, String expected) { - assertEquals(expected, SpatialFormatter.encodePolygon(lineString, logger)); - } - - static Stream encodeGeoLineStringPolygonSupplier() { - return getGeoPositionsAndStringValues().stream().map(positionsExpected -> { - GeoLineString lineString = new GeoLineString(positionsExpected.getT1()); - - return Arguments.of(lineString, positionsExpected.getT2()); - }); - } - - @Test - public void multiRingPolygonThrows() { - GeoLinearRing ring = new GeoLinearRing( - Arrays.asList(new GeoPosition(0, 0), new GeoPosition(0, 1), new GeoPosition(1, 1), new GeoPosition(0, 0))); - GeoPolygon multiRingPolygon = new GeoPolygon(Arrays.asList(ring, ring)); - - assertThrows(IllegalArgumentException.class, () -> SpatialFormatter.encodePolygon(multiRingPolygon, logger)); - } - - @ParameterizedTest - @MethodSource("encodeGeoPolygonPolygonSupplier") - public void encodeGeoPolygonPolygon(GeoPolygon polygon, String expected) { - assertEquals(expected, SpatialFormatter.encodePolygon(polygon, logger)); - } - - static Stream encodeGeoPolygonPolygonSupplier() { - return getGeoPositionsAndStringValues().stream().map(positionsExpected -> { - GeoPolygon polygon = new GeoPolygon(new GeoLinearRing(positionsExpected.getT1())); - - return Arguments.of(polygon, positionsExpected.getT2()); - }); - } - - static List, String>> getGeoPositionsAndStringValues() { - List noDecimalCoordinates - = Arrays.asList(new GeoPosition(0, 0), new GeoPosition(0, 1), new GeoPosition(1, 1), new GeoPosition(0, 0)); - String noDecimalCoordinatesString = createGeographyPolygon("0", "0", "0", "1", "1", "1", "0", "0"); - - List negativeNoDecimalCoordinates = Arrays.asList(new GeoPosition(-0D, -0D), - new GeoPosition(-0D, -1), new GeoPosition(-1, -1), new GeoPosition(-0D, -0D)); - String negativeNoDecimalCoordinatesString - = createGeographyPolygon("-0", "-0", "-0", "-1", "-1", "-1", "-0", "-0"); - - List simpleTrailingZerosCoordinates = Arrays.asList(new GeoPosition(0.0, 0.0), - new GeoPosition(0.0, 1.0), new GeoPosition(1.0, 1.0), new GeoPosition(0.0, 0.0)); - String simpleTrailingZerosCoordinatesString = createGeographyPolygon("0", "0", "0", "1", "1", "1", "0", "0"); - - List negativeSimpleTrailingZerosCoordinates = Arrays.asList(new GeoPosition(-0.0, -0.0), - new GeoPosition(-0.0, -1.0), new GeoPosition(-1.0, -1.0), new GeoPosition(-0.0, -0.0)); - String negativeSimpleTrailingZerosCoordinatesString - = createGeographyPolygon("-0", "-0", "-0", "-1", "-1", "-1", "-0", "-0"); - - List simpleNoTrailingZerosCoordinates = Arrays.asList(new GeoPosition(0.01, 0.01), - new GeoPosition(0.01, 1.01), new GeoPosition(1.01, 1.01), new GeoPosition(0.01, 0.01)); - String simpleNoTrailingZerosCoordinatesString - = createGeographyPolygon("0.01", "0.01", "0.01", "1.01", "1.01", "1.01", "0.01", "0.01"); - - List negativeSimpleNoTrailingZerosCoordinates = Arrays.asList(new GeoPosition(-0.01, -0.01), - new GeoPosition(-0.01, -1.01), new GeoPosition(-1.01, -1.01), new GeoPosition(-0.01, -0.01)); - String negativeSimpleNoTrailingZerosCoordinatesString - = createGeographyPolygon("-0.01", "-0.01", "-0.01", "-1.01", "-1.01", "-1.01", "-0.01", "-0.01"); - - List manyTrailingZerosCoordinates = Arrays.asList(new GeoPosition(0.000000000000, 0.000000000000), - new GeoPosition(0.000000000000, 1.000000000000), new GeoPosition(1.000000000000, 1.000000000000), - new GeoPosition(0.000000000000, 0.000000000000)); - String manyTrailingZerosCoordinatesString = createGeographyPolygon("0", "0", "0", "1", "1", "1", "0", "0"); - - List negativeManyTrailingZerosCoordinates = Arrays.asList( - new GeoPosition(-0.000000000000, -0.000000000000), new GeoPosition(-0.000000000000, -1.000000000000), - new GeoPosition(-1.000000000000, -1.000000000000), new GeoPosition(-0.000000000000, -0.000000000000)); - String negativeManyTrailingZerosCoordinatesString - = createGeographyPolygon("-0", "-0", "-0", "-1", "-1", "-1", "-0", "-0"); - - List complexTrailingZerosCoordinates = Arrays.asList( - new GeoPosition(0.010000000000, 0.010000000000), new GeoPosition(0.010000000000, 1.010000000000), - new GeoPosition(1.010000000000, 1.010000000000), new GeoPosition(0.010000000000, 0.010000000000)); - String complexTrailingZerosCoordinatesString - = createGeographyPolygon("0.01", "0.01", "0.01", "1.01", "1.01", "1.01", "0.01", "0.01"); - - List negativeComplexTrailingZerosCoordinates = Arrays.asList( - new GeoPosition(-0.010000000000, -0.010000000000), new GeoPosition(-0.010000000000, -1.010000000000), - new GeoPosition(-1.010000000000, -1.010000000000), new GeoPosition(-0.010000000000, -0.010000000000)); - String negativeComplexTrailingZerosCoordinatesString - = createGeographyPolygon("-0.01", "-0.01", "-0.01", "-1.01", "-1.01", "-1.01", "-0.01", "-0.01"); - - return Arrays.asList(Tuples.of(noDecimalCoordinates, noDecimalCoordinatesString), - Tuples.of(negativeNoDecimalCoordinates, negativeNoDecimalCoordinatesString), - Tuples.of(simpleTrailingZerosCoordinates, simpleTrailingZerosCoordinatesString), - Tuples.of(negativeSimpleTrailingZerosCoordinates, negativeSimpleTrailingZerosCoordinatesString), - Tuples.of(simpleNoTrailingZerosCoordinates, simpleNoTrailingZerosCoordinatesString), - Tuples.of(negativeSimpleNoTrailingZerosCoordinates, negativeSimpleNoTrailingZerosCoordinatesString), - Tuples.of(manyTrailingZerosCoordinates, manyTrailingZerosCoordinatesString), - Tuples.of(negativeManyTrailingZerosCoordinates, negativeManyTrailingZerosCoordinatesString), - Tuples.of(complexTrailingZerosCoordinates, complexTrailingZerosCoordinatesString), - Tuples.of(negativeComplexTrailingZerosCoordinates, negativeComplexTrailingZerosCoordinatesString)); - } -} diff --git a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/indexes/SynonymMapManagementTests.java b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/indexes/SynonymMapManagementTests.java deleted file mode 100644 index 1de043d6982d..000000000000 --- a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/indexes/SynonymMapManagementTests.java +++ /dev/null @@ -1,552 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -package com.azure.search.documents.indexes; - -import com.azure.core.exception.HttpResponseException; -import com.azure.core.http.rest.PagedIterable; -import com.azure.core.http.rest.Response; -import com.azure.core.test.TestMode; -import com.azure.core.util.Context; -import com.azure.search.documents.SearchTestBase; -import com.azure.search.documents.TestHelpers; -import com.azure.search.documents.indexes.models.SynonymMap; -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.Test; -import reactor.core.publisher.Mono; -import reactor.test.StepVerifier; -import reactor.util.function.Tuple2; -import reactor.util.function.Tuples; - -import java.net.HttpURLConnection; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.stream.Collectors; - -import static com.azure.search.documents.TestHelpers.assertHttpResponseException; -import static com.azure.search.documents.TestHelpers.assertObjectEquals; -import static com.azure.search.documents.TestHelpers.verifyHttpResponseError; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertInstanceOf; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.junit.jupiter.api.Assertions.assertTrue; - -public class SynonymMapManagementTests extends SearchTestBase { - private final List synonymMapsToDelete = new ArrayList<>(); - - private SearchIndexClient client; - private SearchIndexAsyncClient asyncClient; - - @BeforeAll - public static void beforeAll() { - // When running against the live service ensure all synonym maps are deleted before running these tests. - if (TEST_MODE == TestMode.PLAYBACK) { - return; // Running in PLAYBACK, no need to cleanup. - } - - SearchIndexClient cleanupClient = new SearchIndexClientBuilder().endpoint(ENDPOINT) - .credential(TestHelpers.getTestTokenCredential()) - .buildClient(); - - boolean synonymMapDeleted = false; - for (String synonymMap : cleanupClient.listSynonymMapNames()) { - cleanupClient.deleteSynonymMap(synonymMap); - synonymMapDeleted = true; - } - - if (synonymMapDeleted) { - TestHelpers.sleepIfRunningAgainstService(3000); - } - } - - @Override - protected void beforeTest() { - super.beforeTest(); - - client = getSearchIndexClientBuilder(true).buildClient(); - asyncClient = getSearchIndexClientBuilder(false).buildAsyncClient(); - } - - @Override - protected void afterTest() { - super.afterTest(); - - boolean synonymMapsDeleted = false; - for (String synonymMap : synonymMapsToDelete) { - client.deleteSynonymMap(synonymMap); - synonymMapsDeleted = true; - } - - if (synonymMapsDeleted) { - sleepIfRunningAgainstService(5000); - } - } - - @Test - public void createAndGetSynonymMapReturnsCorrectDefinitionSync() { - SynonymMap expectedSynonymMap = createTestSynonymMap(); - SynonymMap actualSynonymMap = client.createSynonymMap(expectedSynonymMap); - synonymMapsToDelete.add(actualSynonymMap.getName()); - - assertSynonymMapsEqual(expectedSynonymMap, actualSynonymMap); - - actualSynonymMap = client.getSynonymMap(expectedSynonymMap.getName()); - assertSynonymMapsEqual(expectedSynonymMap, actualSynonymMap); - } - - @Test - public void createSynonymMapReturnsCorrectDefinitionAsync() { - SynonymMap expectedSynonymMap = createTestSynonymMap(); - - StepVerifier.create(asyncClient.createSynonymMap(expectedSynonymMap)).assertNext(actual -> { - synonymMapsToDelete.add(actual.getName()); - assertSynonymMapsEqual(expectedSynonymMap, actual); - }).verifyComplete(); - - StepVerifier.create(asyncClient.getSynonymMap(expectedSynonymMap.getName())) - .assertNext(actual -> assertSynonymMapsEqual(expectedSynonymMap, actual)) - .verifyComplete(); - } - - @Test - public void createSynonymMapReturnsCorrectDefinitionWithResponseSync() { - SynonymMap expectedSynonymMap = createTestSynonymMap(); - SynonymMap actualSynonymMap = client.createSynonymMapWithResponse(expectedSynonymMap, Context.NONE).getValue(); - synonymMapsToDelete.add(actualSynonymMap.getName()); - - assertSynonymMapsEqual(expectedSynonymMap, actualSynonymMap); - - actualSynonymMap = client.getSynonymMapWithResponse(expectedSynonymMap.getName(), Context.NONE).getValue(); - assertSynonymMapsEqual(expectedSynonymMap, actualSynonymMap); - } - - @Test - public void createSynonymMapReturnsCorrectDefinitionWithResponseAsync() { - SynonymMap expectedSynonymMap = createTestSynonymMap(); - StepVerifier.create(asyncClient.createSynonymMapWithResponse(expectedSynonymMap)).assertNext(response -> { - synonymMapsToDelete.add(response.getValue().getName()); - assertSynonymMapsEqual(expectedSynonymMap, response.getValue()); - }).verifyComplete(); - - StepVerifier.create(asyncClient.getSynonymMapWithResponse(expectedSynonymMap.getName())) - .assertNext(response -> assertSynonymMapsEqual(expectedSynonymMap, response.getValue())) - .verifyComplete(); - } - - @Test - public void createSynonymMapFailsWithUsefulMessageOnUserErrorSync() { - // Create SynonymMap with invalid synonym - SynonymMap expectedSynonymMap = createTestSynonymMap().setSynonyms("a => b => c"); - - HttpResponseException ex - = assertThrows(HttpResponseException.class, () -> client.createSynonymMap(expectedSynonymMap)); - assertEquals(HttpURLConnection.HTTP_BAD_REQUEST, ex.getResponse().getStatusCode()); - } - - @Test - public void createSynonymMapFailsWithUsefulMessageOnUserErrorAsync() { - // Create SynonymMap with invalid synonym - SynonymMap expectedSynonymMap = createTestSynonymMap().setSynonyms("a => b => c"); - - StepVerifier.create(asyncClient.createSynonymMap(expectedSynonymMap)).verifyErrorSatisfies(throwable -> { - HttpResponseException ex = assertInstanceOf(HttpResponseException.class, throwable); - assertEquals(HttpURLConnection.HTTP_BAD_REQUEST, ex.getResponse().getStatusCode()); - }); - } - - @Test - public void getSynonymMapThrowsOnNotFoundSync() { - final String synonymMapName = "thisSynonymMapDoesNotExist"; - final String exceptionMessage = String.format("No synonym map with the name '%s' was found", synonymMapName); - - assertHttpResponseException(() -> client.getSynonymMap(synonymMapName), HttpURLConnection.HTTP_NOT_FOUND, - exceptionMessage); - } - - @Test - public void getSynonymMapThrowsOnNotFoundAsync() { - final String synonymMapName = "thisSynonymMapDoesNotExist"; - final String exceptionMessage = String.format("No synonym map with the name '%s' was found", synonymMapName); - - StepVerifier.create(asyncClient.getSynonymMap(synonymMapName)) - .verifyErrorSatisfies( - throwable -> verifyHttpResponseError(throwable, HttpURLConnection.HTTP_NOT_FOUND, exceptionMessage)); - } - - @Test - public void getSynonymMapThrowsOnNotFoundWithResponseSync() { - final String synonymMapName = "thisSynonymMapDoesNotExist"; - final String exceptionMessage = String.format("No synonym map with the name '%s' was found", synonymMapName); - - assertHttpResponseException(() -> client.getSynonymMapWithResponse(synonymMapName, Context.NONE), - HttpURLConnection.HTTP_NOT_FOUND, exceptionMessage); - } - - @Test - public void getSynonymMapThrowsOnNotFoundWithResponseAsync() { - final String synonymMapName = "thisSynonymMapDoesNotExist"; - final String exceptionMessage = String.format("No synonym map with the name '%s' was found", synonymMapName); - - StepVerifier.create(asyncClient.getSynonymMapWithResponse(synonymMapName)) - .verifyErrorSatisfies( - throwable -> verifyHttpResponseError(throwable, HttpURLConnection.HTTP_NOT_FOUND, exceptionMessage)); - } - - @Test - public void canUpdateSynonymMapSync() { - SynonymMap initial = createTestSynonymMap(); - client.createSynonymMap(initial); - synonymMapsToDelete.add(initial.getName()); - - SynonymMap updatedExpected = new SynonymMap(initial.getName(), "newword1,newword2"); - - SynonymMap updatedActual = client.createOrUpdateSynonymMap(updatedExpected); - assertSynonymMapsEqual(updatedExpected, updatedActual); - - PagedIterable synonymMaps = client.listSynonymMaps(); - assertEquals(1, synonymMaps.stream().count()); - } - - @Test - public void canUpdateSynonymMapAsync() { - Mono> createAndUpdateMono - = asyncClient.createSynonymMap(createTestSynonymMap()).flatMap(original -> { - synonymMapsToDelete.add(original.getName()); - - SynonymMap updatedExpected = new SynonymMap(original.getName(), "newword1,newword2"); - return asyncClient.createOrUpdateSynonymMap(updatedExpected) - .map(updateActual -> Tuples.of(updatedExpected, updateActual)); - }); - - StepVerifier.create(createAndUpdateMono) - .assertNext(synonyms -> assertSynonymMapsEqual(synonyms.getT1(), synonyms.getT2())) - .verifyComplete(); - - StepVerifier.create(asyncClient.listSynonymMaps()).expectNextCount(1).verifyComplete(); - } - - @Test - public void canUpdateSynonymMapWithResponseSync() { - SynonymMap initial = createTestSynonymMap(); - client.createSynonymMap(initial); - synonymMapsToDelete.add(initial.getName()); - - SynonymMap updatedExpected = new SynonymMap(initial.getName(), "newword1,newword2"); - - SynonymMap updatedActual - = client.createOrUpdateSynonymMapWithResponse(updatedExpected, false, Context.NONE).getValue(); - assertSynonymMapsEqual(updatedExpected, updatedActual); - - PagedIterable synonymMaps = client.listSynonymMaps(); - assertEquals(1, synonymMaps.stream().count()); - } - - @Test - public void canUpdateSynonymMapWithResponseAsync() { - Mono> createAndUpdateMono - = asyncClient.createSynonymMap(createTestSynonymMap()).flatMap(original -> { - synonymMapsToDelete.add(original.getName()); - SynonymMap updatedExpected = new SynonymMap(original.getName(), "newword1,newword2"); - - return asyncClient.createOrUpdateSynonymMapWithResponse(updatedExpected, false) - .map(response -> Tuples.of(updatedExpected, response.getValue())); - }); - - StepVerifier.create(createAndUpdateMono) - .assertNext(synonyms -> assertSynonymMapsEqual(synonyms.getT1(), synonyms.getT2())) - .verifyComplete(); - - StepVerifier.create(asyncClient.listSynonymMaps()).expectNextCount(1).verifyComplete(); - } - - @Test - public void createOrUpdateSynonymMapCreatesWhenSynonymMapDoesNotExistSync() { - SynonymMap expected = createTestSynonymMap(); - SynonymMap actual = client.createOrUpdateSynonymMap(expected); - synonymMapsToDelete.add(expected.getName()); - - assertSynonymMapsEqual(expected, actual); - } - - @Test - public void createOrUpdateSynonymMapCreatesWhenSynonymMapDoesNotExistAsync() { - SynonymMap expected = createTestSynonymMap(); - - StepVerifier.create(asyncClient.createOrUpdateSynonymMap(expected)).assertNext(actual -> { - synonymMapsToDelete.add(actual.getName()); - assertSynonymMapsEqual(expected, actual); - }).verifyComplete(); - } - - @Test - public void createOrUpdateSynonymMapCreatesWhenSynonymMapDoesNotExistWithResponseSync() { - SynonymMap expected = createTestSynonymMap(); - Response createOrUpdateResponse - = client.createOrUpdateSynonymMapWithResponse(expected, false, Context.NONE); - synonymMapsToDelete.add(expected.getName()); - - assertEquals(HttpURLConnection.HTTP_CREATED, createOrUpdateResponse.getStatusCode()); - assertSynonymMapsEqual(expected, createOrUpdateResponse.getValue()); - } - - @Test - public void createOrUpdateSynonymMapCreatesWhenSynonymMapDoesNotExistWithResponseAsync() { - SynonymMap expected = createTestSynonymMap(); - - StepVerifier.create(asyncClient.createOrUpdateSynonymMapWithResponse(expected, false)).assertNext(response -> { - synonymMapsToDelete.add(response.getValue().getName()); - - assertEquals(HttpURLConnection.HTTP_CREATED, response.getStatusCode()); - assertSynonymMapsEqual(expected, response.getValue()); - }).verifyComplete(); - } - - @Test - public void createOrUpdateSynonymMapIfNotExistsSucceedsOnNoResourceSync() { - SynonymMap synonymMap = createTestSynonymMap(); - - SynonymMap created = client.createOrUpdateSynonymMapWithResponse(synonymMap, true, Context.NONE).getValue(); - synonymMapsToDelete.add(created.getName()); - - assertNotNull(created.getETag()); - } - - @Test - public void createOrUpdateSynonymMapIfNotExistsSucceedsOnNoResourceAsync() { - SynonymMap synonymMap = createTestSynonymMap(); - - StepVerifier.create(asyncClient.createOrUpdateSynonymMapWithResponse(synonymMap, true)).assertNext(response -> { - synonymMapsToDelete.add(response.getValue().getName()); - assertNotNull(response.getValue().getETag()); - }).verifyComplete(); - } - - @Test - public void createOrUpdateSynonymMapIfExistsSucceedsOnExistingResourceSync() { - SynonymMap synonymMap = createTestSynonymMap(); - - SynonymMap original = client.createOrUpdateSynonymMapWithResponse(synonymMap, false, Context.NONE).getValue(); - synonymMapsToDelete.add(original.getName()); - - SynonymMap updated = client - .createOrUpdateSynonymMapWithResponse(original.setSynonyms("mutated1, mutated2"), false, Context.NONE) - .getValue(); - - validateETagUpdate(original.getETag(), updated.getETag()); - } - - @Test - public void createOrUpdateSynonymMapIfExistsSucceedsOnExistingResourceAsync() { - SynonymMap synonymMap = createTestSynonymMap(); - - Mono> createAndUpdateMono - = asyncClient.createOrUpdateSynonymMapWithResponse(synonymMap, false).flatMap(response -> { - SynonymMap original = response.getValue(); - synonymMapsToDelete.add(original.getName()); - - return asyncClient - .createOrUpdateSynonymMapWithResponse(original.setSynonyms("mutated1, mutated2"), false) - .map(update -> Tuples.of(original.getETag(), update.getValue().getETag())); - }); - - StepVerifier.create(createAndUpdateMono) - .assertNext(etags -> validateETagUpdate(etags.getT1(), etags.getT2())) - .verifyComplete(); - } - - @Test - public void createOrUpdateSynonymMapIfNotChangedSucceedsWhenResourceUnchangedSync() { - SynonymMap synonymMap = createTestSynonymMap(); - - SynonymMap original = client.createOrUpdateSynonymMapWithResponse(synonymMap, false, Context.NONE).getValue(); - synonymMapsToDelete.add(original.getName()); - - SynonymMap updated = client - .createOrUpdateSynonymMapWithResponse(original.setSynonyms("mutated1, mutated2"), true, Context.NONE) - .getValue(); - - validateETagUpdate(original.getETag(), updated.getETag()); - } - - @Test - public void createOrUpdateSynonymMapIfNotChangedSucceedsWhenResourceUnchangedAsync() { - SynonymMap synonymMap = createTestSynonymMap(); - - Mono> createAndUpdateMono - = asyncClient.createOrUpdateSynonymMapWithResponse(synonymMap, false).flatMap(response -> { - SynonymMap original = response.getValue(); - synonymMapsToDelete.add(original.getName()); - - return asyncClient - .createOrUpdateSynonymMapWithResponse(original.setSynonyms("mutated1, mutated2"), true) - .map(update -> Tuples.of(original.getETag(), update.getValue().getETag())); - }); - - StepVerifier.create(createAndUpdateMono) - .assertNext(etags -> validateETagUpdate(etags.getT1(), etags.getT2())) - .verifyComplete(); - } - - @Test - public void createOrUpdateSynonymMapIfNotChangedFailsWhenResourceChangedSyncAndAsync() { - SynonymMap synonymMap = createTestSynonymMap(); - - SynonymMap original = client.createOrUpdateSynonymMapWithResponse(synonymMap, false, Context.NONE).getValue(); - synonymMapsToDelete.add(original.getName()); - - SynonymMap updated = client - .createOrUpdateSynonymMapWithResponse(original.setSynonyms("mutated1, mutated2"), true, Context.NONE) - .getValue(); - - // Update and check the eTags were changed - HttpResponseException ex = assertThrows(HttpResponseException.class, - () -> client.createOrUpdateSynonymMapWithResponse(original, true, Context.NONE)); - assertEquals(HttpURLConnection.HTTP_PRECON_FAILED, ex.getResponse().getStatusCode()); - - StepVerifier.create(asyncClient.createOrUpdateSynonymMapWithResponse(original, true)) - .verifyErrorSatisfies(throwable -> { - HttpResponseException exAsync = assertInstanceOf(HttpResponseException.class, throwable); - assertEquals(HttpURLConnection.HTTP_PRECON_FAILED, exAsync.getResponse().getStatusCode()); - }); - - validateETagUpdate(original.getETag(), updated.getETag()); - } - - @Test - public void deleteSynonymMapIsIdempotentSync() { - SynonymMap synonymMap = createTestSynonymMap(); - Response deleteResponse = client.deleteSynonymMapWithResponse(synonymMap, false, Context.NONE); - assertEquals(HttpURLConnection.HTTP_NOT_FOUND, deleteResponse.getStatusCode()); - - Response createResponse = client.createSynonymMapWithResponse(synonymMap, Context.NONE); - assertEquals(HttpURLConnection.HTTP_CREATED, createResponse.getStatusCode()); - - deleteResponse = client.deleteSynonymMapWithResponse(synonymMap, false, Context.NONE); - assertEquals(HttpURLConnection.HTTP_NO_CONTENT, deleteResponse.getStatusCode()); - - deleteResponse = client.deleteSynonymMapWithResponse(synonymMap, false, Context.NONE); - assertEquals(HttpURLConnection.HTTP_NOT_FOUND, deleteResponse.getStatusCode()); - } - - @Test - public void deleteSynonymMapIsIdempotentAsync() { - SynonymMap synonymMap = createTestSynonymMap(); - - StepVerifier.create(asyncClient.deleteSynonymMapWithResponse(synonymMap, false)) - .assertNext(response -> assertEquals(HttpURLConnection.HTTP_NOT_FOUND, response.getStatusCode())) - .verifyComplete(); - - StepVerifier.create(asyncClient.createSynonymMapWithResponse(synonymMap)) - .assertNext(response -> assertEquals(HttpURLConnection.HTTP_CREATED, response.getStatusCode())) - .verifyComplete(); - - StepVerifier.create(asyncClient.deleteSynonymMapWithResponse(synonymMap, false)) - .assertNext(response -> assertEquals(HttpURLConnection.HTTP_NO_CONTENT, response.getStatusCode())) - .verifyComplete(); - - StepVerifier.create(asyncClient.deleteSynonymMapWithResponse(synonymMap, false)) - .assertNext(response -> assertEquals(HttpURLConnection.HTTP_NOT_FOUND, response.getStatusCode())) - .verifyComplete(); - } - - @Test - public void canCreateAndListSynonymMapsSyncAndAsync() { - SynonymMap synonymMap1 = createTestSynonymMap(); - SynonymMap synonymMap2 = createTestSynonymMap(); - - client.createSynonymMap(synonymMap1); - synonymMapsToDelete.add(synonymMap1.getName()); - client.createSynonymMap(synonymMap2); - synonymMapsToDelete.add(synonymMap2.getName()); - - Map expectedSynonyms = new HashMap<>(); - expectedSynonyms.put(synonymMap1.getName(), synonymMap1); - expectedSynonyms.put(synonymMap2.getName(), synonymMap2); - - Map actualSynonyms - = client.listSynonymMaps().stream().collect(Collectors.toMap(SynonymMap::getName, sm -> sm)); - - compareMaps(expectedSynonyms, actualSynonyms, (expected, actual) -> assertObjectEquals(expected, actual, true)); - - StepVerifier.create(asyncClient.listSynonymMaps().collectMap(SynonymMap::getName)) - .assertNext(actualSynonyms2 -> compareMaps(expectedSynonyms, actualSynonyms2, - (expected, actual) -> assertObjectEquals(expected, actual, true))) - .verifyComplete(); - } - - @Test - public void canListSynonymMapsWithSelectedFieldSyncAndAsync() { - SynonymMap synonymMap1 = createTestSynonymMap(); - SynonymMap synonymMap2 = createTestSynonymMap(); - - client.createSynonymMap(synonymMap1); - synonymMapsToDelete.add(synonymMap1.getName()); - client.createSynonymMap(synonymMap2); - synonymMapsToDelete.add(synonymMap2.getName()); - - Set expectedSynonymNames = new HashSet<>(Arrays.asList(synonymMap1.getName(), synonymMap2.getName())); - Set actualSynonymNames = client.listSynonymMapNames().stream().collect(Collectors.toSet()); - - assertEquals(expectedSynonymNames.size(), actualSynonymNames.size()); - assertTrue(actualSynonymNames.containsAll(expectedSynonymNames)); - - StepVerifier.create(asyncClient.listSynonymMapNames().collect(Collectors.toSet())) - .assertNext(actualSynonymNames2 -> { - assertEquals(expectedSynonymNames.size(), actualSynonymNames2.size()); - assertTrue(actualSynonymNames2.containsAll(expectedSynonymNames)); - }) - .verifyComplete(); - } - - @Test - public void deleteSynonymMapIfNotChangedWorksOnlyOnCurrentResourceSyncAndAsync() { - SynonymMap stale - = client.createOrUpdateSynonymMapWithResponse(createTestSynonymMap(), true, Context.NONE).getValue(); - - // Update the resource, the eTag will be changed - SynonymMap current = client.createOrUpdateSynonymMapWithResponse(stale, true, Context.NONE).getValue(); - - HttpResponseException ex = assertThrows(HttpResponseException.class, - () -> client.deleteSynonymMapWithResponse(stale, true, Context.NONE)); - assertEquals(HttpURLConnection.HTTP_PRECON_FAILED, ex.getResponse().getStatusCode()); - - StepVerifier.create(asyncClient.deleteSynonymMapWithResponse(stale, true)).verifyErrorSatisfies(throwable -> { - HttpResponseException exAsync = assertInstanceOf(HttpResponseException.class, throwable); - assertEquals(HttpURLConnection.HTTP_PRECON_FAILED, exAsync.getResponse().getStatusCode()); - }); - - client.deleteSynonymMapWithResponse(current, true, Context.NONE); - } - - @Test - public void deleteSynonymMapIfExistsWorksOnlyWhenResourceExistsSyncAndAsync() { - SynonymMap updated - = client.createOrUpdateSynonymMapWithResponse(createTestSynonymMap(), false, Context.NONE).getValue(); - - client.deleteSynonymMapWithResponse(updated, true, Context.NONE); - - // Try to delete again and expect to fail - HttpResponseException ex = assertThrows(HttpResponseException.class, - () -> client.deleteSynonymMapWithResponse(updated, true, Context.NONE)); - assertEquals(HttpURLConnection.HTTP_PRECON_FAILED, ex.getResponse().getStatusCode()); - - StepVerifier.create(asyncClient.deleteSynonymMapWithResponse(updated, true)).verifyErrorSatisfies(throwable -> { - HttpResponseException exAsync = assertInstanceOf(HttpResponseException.class, throwable); - assertEquals(HttpURLConnection.HTTP_PRECON_FAILED, exAsync.getResponse().getStatusCode()); - }); - } - - static void assertSynonymMapsEqual(SynonymMap expected, SynonymMap actual) { - assertEquals(expected.getName(), actual.getName()); - assertEquals(expected.getSynonyms(), actual.getSynonyms()); - } - - SynonymMap createTestSynonymMap() { - return new SynonymMap(testResourceNamer.randomName("test-synonym", 32), "word1,word2"); - } -} diff --git a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/models/IndexBatchExceptionTests.java b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/models/IndexBatchExceptionTests.java deleted file mode 100644 index 8ac5fc142868..000000000000 --- a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/models/IndexBatchExceptionTests.java +++ /dev/null @@ -1,142 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.search.documents.models; - -import com.azure.json.JsonProviders; -import com.azure.json.JsonReader; -import com.azure.search.documents.SearchDocument; -import com.azure.search.documents.indexes.models.IndexDocumentsBatch; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.parallel.Execution; -import org.junit.jupiter.api.parallel.ExecutionMode; - -import java.io.IOException; -import java.io.UncheckedIOException; -import java.util.Arrays; -import java.util.Collections; -import java.util.List; -import java.util.stream.Collectors; - -@Execution(ExecutionMode.CONCURRENT) -public class IndexBatchExceptionTests { - private static final String KEY_FIELD_NAME = "key"; - - @Test - public void clientShouldNotRetrySuccessfulBatch() { - IndexDocumentsResult result - = new IndexDocumentsResult(Arrays.asList(createSucceededResult("1"), createResult("2"))); - - assertRetryBatchEmpty(result); - } - - @Test - public void clientShouldNotRetryBatchWithAllNonRetriableFailures() { - IndexDocumentsResult result = new IndexDocumentsResult( - Arrays.asList(createFailedResult("1", 500), createFailedResult("2", 404), createFailedResult("3", 400))); - - assertRetryBatchEmpty(result); - } - - @Test - public void clientShouldNotRetryBatchWithSuccessesAndNonRetriableFailures() { - IndexDocumentsResult result - = new IndexDocumentsResult(Arrays.asList(createSucceededResult("1"), createFailedResult("2", 500), - createFailedResult("3", 404), createResult("4"), createFailedResult("5", 400))); - - assertRetryBatchEmpty(result); - } - - @Test - public void clientShouldRetryBatchWithAllRetriableFailures() { - IndexDocumentsResult result = new IndexDocumentsResult( - Arrays.asList(createFailedResult("1", 422), createFailedResult("2", 409), createFailedResult("3", 503))); - - assertRetryBatchContains(result, Arrays.asList("1", "2", "3")); - } - - @Test - public void clientShouldRetryBatchWithSomeRetriableFailures() { - IndexDocumentsResult result - = new IndexDocumentsResult(Arrays.asList(createSucceededResult("1"), createFailedResult("2", 500), - createFailedResult("3", 422), createFailedResult("4", 404), createFailedResult("5", 409), - createFailedResult("6", 400), createResult("7"), createFailedResult("8", 503))); - - assertRetryBatchContains(result, Arrays.asList("3", "5", "8")); - } - - @Test - public void clientShouldNotRetryResultWithUnexpectedStatusCode() { - IndexDocumentsResult result = new IndexDocumentsResult( - Arrays.asList(createSucceededResult("1"), createFailedResult("2", 502), createFailedResult("3", 503))); - - assertRetryBatchContains(result, Collections.singletonList("3")); - } - - private static void assertRetryBatchEmpty(IndexDocumentsResult result) { - Assertions.assertTrue(getRetryBatch(result).getActions().isEmpty()); - Assertions.assertTrue(getTypedRetryBatch(result).getActions().isEmpty()); - } - - private static void assertRetryBatchContains(IndexDocumentsResult result, List expectedKeys) { - Assertions.assertEquals(expectedKeys, - getRetryBatch(result).getActions() - .stream() - .map(IndexBatchExceptionTests::getValueFromDocHelper) - .collect(Collectors.toList())); - - Assertions.assertEquals(expectedKeys, - getTypedRetryBatch(result).getActions() - .stream() - .map(action -> action.getDocument().getHotelId()) - .collect(Collectors.toList())); - } - - public static Object getValueFromDocHelper(IndexAction action) { - if (action.getDocument() != null) { - return action.getDocument().get(KEY_FIELD_NAME); - } - // else if (action.getParamMap() != null) { - // return action.getParamMap().get(KEY_FIELD_NAME); - // } - return null; - } - - private static IndexBatchBase getRetryBatch(IndexDocumentsResult result) { - List allKeys = result.getResults().stream().map(IndexingResult::getKey).collect(Collectors.toList()); - IndexBatchException exception = new IndexBatchException(result); - - IndexDocumentsBatch originalBatch - = new IndexDocumentsBatch().addUploadActions(allKeys.stream() - .map(key -> new SearchDocument(Collections.singletonMap(KEY_FIELD_NAME, key))) - .collect(Collectors.toList())); - return exception.findFailedActionsToRetry(originalBatch, KEY_FIELD_NAME); - } - - private static IndexBatchBase getTypedRetryBatch(IndexDocumentsResult result) { - List allKeys = result.getResults().stream().map(IndexingResult::getKey).collect(Collectors.toList()); - IndexBatchException exception = new IndexBatchException(result); - IndexDocumentsBatch originalBatch = new IndexDocumentsBatch() - .addUploadActions(allKeys.stream().map(key -> new Hotel().setHotelId(key)).collect(Collectors.toList())); - return exception.findFailedActionsToRetry(originalBatch, Hotel::getHotelId); - } - - private static IndexingResult createSucceededResult(String key) { - return new IndexingResult(key, true, 200); - } - - private static IndexingResult createResult(String key) { - return new IndexingResult(key, true, 201); - } - - private IndexingResult createFailedResult(String key, int statusCode) { - String json = "{\"key\":\"" + key + "\",\"errorMessage\":\"Something went wrong\",\"statusCode\":" + statusCode - + ",\"status\":false}"; - try (JsonReader jsonReader = JsonProviders.createReader(json)) { - return IndexingResult.fromJson(jsonReader); - } catch (IOException e) { - throw new UncheckedIOException(e); - } - } -} diff --git a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/models/ScoringParameterTests.java b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/models/ScoringParameterTests.java deleted file mode 100644 index 1f944b4394b7..000000000000 --- a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/models/ScoringParameterTests.java +++ /dev/null @@ -1,81 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.search.documents.models; - -import com.azure.core.models.GeoPoint; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.parallel.Execution; -import org.junit.jupiter.api.parallel.ExecutionMode; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotEquals; -import static org.junit.jupiter.api.Assertions.assertThrows; - -@SuppressWarnings("unchecked") -@Execution(ExecutionMode.CONCURRENT) -public class ScoringParameterTests { - private static final Map FOOL_SPOTBUGS = new HashMap<>(); - - @Test - public void testConstructorWithMap() { - List parameters = new ArrayList<>(Arrays.asList("hello", "tests")); - ScoringParameter scoringParameter = new ScoringParameter("test", parameters); - List scoringParameterValues = scoringParameter.getValues(); - for (int i = 0; i < parameters.size(); i++) { - assertEquals(parameters.get(i), scoringParameterValues.get(i)); - } - parameters.add("test clone"); - assertNotEquals(parameters.size(), scoringParameterValues.size()); - scoringParameterValues.add("test getter"); - List originalValues = scoringParameter.getValues(); - assertNotEquals(originalValues.size(), scoringParameterValues.size()); - } - - @Test - public void testConstructorWithEscaper() { - String actualValue = new ScoringParameter("test", Arrays.asList("Hello, O'Brien", "Smith")).toString(); - String expectValue = "test-'Hello, O''Brien',Smith"; - assertEquals(expectValue, actualValue); - } - - @Test - public void testConstructorWithNullOrEmptyValuesList() { - assertThrows(IllegalArgumentException.class, - () -> new ScoringParameter("test", Arrays.asList("", null)).toString()); - } - - @Test - public void testConstructorWithMapNullName() { - assertThrows(NullPointerException.class, - () -> new ScoringParameter((String) FOOL_SPOTBUGS.get("name"), Arrays.asList("hello", "tests"))); - } - - @Test - public void testConstructorWithMapNullValues() { - assertThrows(NullPointerException.class, - () -> new ScoringParameter("null value", (List) FOOL_SPOTBUGS.get("values"))); - } - - @Test - public void testConstructorWithGeoPoint() { - GeoPoint geoPoint = new GeoPoint(-114, 92); - String name = "mytest"; - String expectValue = "mytest--114,92"; - String toFlattenString = new ScoringParameter(name, geoPoint).toString(); - - assertEquals(expectValue, toFlattenString); - } - - @Test - public void testConstructorWithNullGeoPoint() { - assertThrows(NullPointerException.class, - () -> new ScoringParameter("null geopoint", (GeoPoint) FOOL_SPOTBUGS.get("geoPoint"))); - } -} diff --git a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/models/SearchRequestUrlRewriterPolicyTests.java b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/models/SearchRequestUrlRewriterPolicyTests.java deleted file mode 100644 index 1e4243eafb09..000000000000 --- a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/models/SearchRequestUrlRewriterPolicyTests.java +++ /dev/null @@ -1,309 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -package com.azure.search.documents.models; - -import com.azure.core.http.HttpClient; -import com.azure.core.http.policy.FixedDelayOptions; -import com.azure.core.http.policy.RetryOptions; -import com.azure.core.test.utils.MockTokenCredential; -import com.azure.core.util.Context; -import com.azure.search.documents.SearchAsyncClient; -import com.azure.search.documents.SearchClient; -import com.azure.search.documents.SearchClientBuilder; -import com.azure.search.documents.SearchDocument; -import com.azure.search.documents.SearchRequestUrlRewriterPolicy; -import com.azure.search.documents.indexes.SearchIndexAsyncClient; -import com.azure.search.documents.indexes.SearchIndexClient; -import com.azure.search.documents.indexes.SearchIndexClientBuilder; -import com.azure.search.documents.indexes.SearchIndexerAsyncClient; -import com.azure.search.documents.indexes.SearchIndexerClient; -import com.azure.search.documents.indexes.SearchIndexerClientBuilder; -import com.azure.search.documents.indexes.models.IndexDocumentsBatch; -import com.azure.search.documents.indexes.models.SearchIndex; -import com.azure.search.documents.indexes.models.SearchIndexer; -import com.azure.search.documents.indexes.models.SearchIndexerDataSourceConnection; -import com.azure.search.documents.indexes.models.SearchIndexerSkillset; -import com.azure.search.documents.indexes.models.SynonymMap; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.parallel.Execution; -import org.junit.jupiter.api.parallel.ExecutionMode; -import org.junit.jupiter.params.ParameterizedTest; -import org.junit.jupiter.params.provider.Arguments; -import org.junit.jupiter.params.provider.MethodSource; -import reactor.core.publisher.Flux; -import reactor.core.publisher.Mono; - -import java.time.Duration; -import java.util.concurrent.Callable; -import java.util.function.Supplier; -import java.util.stream.Stream; - -import static org.junit.jupiter.api.Assertions.assertTrue; - -@Execution(ExecutionMode.CONCURRENT) -public class SearchRequestUrlRewriterPolicyTests { - @ParameterizedTest - @MethodSource("correctUrlRewriteSupplier") - public void correctUrlRewrite(Callable apiCall, String expectedUrl) { - try { - apiCall.call(); - } catch (Exception ex) { - UrlRewriteException urlRewriteException = Assertions.assertInstanceOf(UrlRewriteException.class, ex); - assertTrue(urlRewriteException.rewrittenUrl.startsWith(expectedUrl), - () -> "Expected URL to start with " + expectedUrl + " but was " + urlRewriteException.rewrittenUrl); - } - } - - public static Stream correctUrlRewriteSupplier() { - HttpClient urlRewriteHttpClient - = request -> Mono.error(new UrlRewriteException("Url rewritten", request.getUrl().toString())); - - SearchClientBuilder searchClientBuilder = new SearchClientBuilder().indexName("test") - .endpoint("https://test.search.windows.net") - .credential(new MockTokenCredential()) - .retryOptions(new RetryOptions(new FixedDelayOptions(0, Duration.ofMillis(1)))) - .addPolicy(new SearchRequestUrlRewriterPolicy()) - .httpClient(urlRewriteHttpClient); - SearchClient searchClient = searchClientBuilder.buildClient(); - SearchAsyncClient searchAsyncClient = searchClientBuilder.buildAsyncClient(); - - SearchIndexClientBuilder searchIndexClientBuilder - = new SearchIndexClientBuilder().endpoint("https://test.search.windows.net") - .credential(new MockTokenCredential()) - .retryOptions(new RetryOptions(new FixedDelayOptions(0, Duration.ofMillis(1)))) - .addPolicy(new SearchRequestUrlRewriterPolicy()) - .httpClient(urlRewriteHttpClient); - SearchIndexClient searchIndexClient = searchIndexClientBuilder.buildClient(); - SearchIndexAsyncClient searchIndexAsyncClient = searchIndexClientBuilder.buildAsyncClient(); - - SearchIndexerClientBuilder searchIndexerClientBuilder - = new SearchIndexerClientBuilder().endpoint("https://test.search.windows.net") - .credential(new MockTokenCredential()) - .retryOptions(new RetryOptions(new FixedDelayOptions(0, Duration.ofMillis(1)))) - .addPolicy(new SearchRequestUrlRewriterPolicy()) - .httpClient(urlRewriteHttpClient); - SearchIndexerClient searchIndexerClient = searchIndexerClientBuilder.buildClient(); - SearchIndexerAsyncClient searchIndexerAsyncClient = searchIndexerClientBuilder.buildAsyncClient(); - - String docsUrl = "https://test.search.windows.net/indexes/test/docs"; - - SearchIndex index = new SearchIndex("index"); - String indexUrl = "https://test.search.windows.net/indexes/index"; - - SynonymMap synonymMap = new SynonymMap("synonym"); - String synonymMapUrl = "https://test.search.windows.net/synonymmaps/synonym"; - - SearchIndexerDataSourceConnection dataSource = new SearchIndexerDataSourceConnection("datasource"); - String dataSourceUrl = "https://test.search.windows.net/datasources/datasource"; - - SearchIndexer indexer = new SearchIndexer("indexer"); - String indexerUrl = "https://test.search.windows.net/indexers/indexer"; - - SearchIndexerSkillset skillset = new SearchIndexerSkillset("skillset"); - String skillsetUrl = "https://test.search.windows.net/skillsets/skillset"; - - return Stream.of( - Arguments.of( - toCallable( - () -> searchClient.indexDocumentsWithResponse(new IndexDocumentsBatch<>(), null, Context.NONE)), - docsUrl + "/search.index"), - Arguments.of( - toCallable( - () -> searchClient.getDocumentWithResponse("test", SearchDocument.class, null, Context.NONE)), - docsUrl + "/test"), - Arguments.of(toCallable(() -> searchClient.getDocumentCountWithResponse(Context.NONE)), - docsUrl + "/$count"), - Arguments.of(toCallable(() -> searchClient.search("search", null, Context.NONE).iterator().hasNext()), - docsUrl + "/search.post.search"), - Arguments.of( - toCallable(() -> searchClient.suggest("suggest", "suggester", null, Context.NONE).iterator().hasNext()), - docsUrl + "/seach.post.suggest"), - Arguments.of(toCallable( - () -> searchClient.autocomplete("autocomplete", "suggester", null, Context.NONE).iterator().hasNext()), - docsUrl + "/search.post.autocomplete"), - - Arguments.of(toCallable(searchAsyncClient.indexDocumentsWithResponse(new IndexDocumentsBatch<>(), null)), - docsUrl + "/search.index"), - Arguments.of(toCallable(searchAsyncClient.getDocumentWithResponse("test", SearchDocument.class, null)), - docsUrl + "/test"), - Arguments.of(toCallable(searchAsyncClient.getDocumentCountWithResponse()), docsUrl + "/$count"), - Arguments.of(toCallable(searchAsyncClient.search("search", null)), docsUrl + "/search.post.search"), - Arguments.of(toCallable(searchAsyncClient.suggest("suggest", "suggester", null)), - docsUrl + "/search.post.suggest"), - Arguments.of(toCallable(searchAsyncClient.autocomplete("autocomplete", "suggester", null)), - docsUrl + "/search.post.autocomplete"), - - Arguments.of(toCallable(() -> searchIndexClient.createIndexWithResponse(index, Context.NONE)), - "https://test.search.windows.net/indexes"), - Arguments.of(toCallable(() -> searchIndexClient.getIndexWithResponse("index", Context.NONE)), indexUrl), - Arguments.of(toCallable(() -> searchIndexClient.getIndexStatisticsWithResponse("index", Context.NONE)), - indexUrl + "/search.stats"), - Arguments.of(toCallable(() -> searchIndexClient.listIndexes(Context.NONE).iterator().hasNext()), - "https://test.search.windows.net/indexes"), - Arguments.of(toCallable(() -> searchIndexClient.listIndexNames(Context.NONE).iterator().hasNext()), - "https://test.search.windows.net/indexes"), - Arguments.of( - toCallable(() -> searchIndexClient.createOrUpdateIndexWithResponse(index, false, false, Context.NONE)), - indexUrl), - Arguments.of(toCallable(() -> searchIndexClient.deleteIndexWithResponse(index, true, Context.NONE)), - indexUrl), - Arguments.of(toCallable(() -> searchIndexClient.analyzeText("index", null, Context.NONE)), - indexUrl + "/search.analyze"), - Arguments.of(toCallable(() -> searchIndexClient.createSynonymMapWithResponse(synonymMap, Context.NONE)), - "https://test.search.windows.net/synonymmaps"), - Arguments.of(toCallable(() -> searchIndexClient.getSynonymMapWithResponse("synonym", Context.NONE)), - synonymMapUrl), - Arguments.of(toCallable(() -> searchIndexClient.listSynonymMaps(Context.NONE).iterator().hasNext()), - "https://test.search.windows.net/synonymmaps"), - Arguments.of(toCallable(() -> searchIndexClient.listSynonymMapNames(Context.NONE).iterator().hasNext()), - "https://test.search.windows.net/synonymmaps"), - Arguments.of( - toCallable( - () -> searchIndexClient.createOrUpdateSynonymMapWithResponse(synonymMap, false, Context.NONE)), - synonymMapUrl), - Arguments.of( - toCallable(() -> searchIndexClient.deleteSynonymMapWithResponse(synonymMap, true, Context.NONE)), - synonymMapUrl), - Arguments.of(toCallable(() -> searchIndexClient.getServiceStatisticsWithResponse(Context.NONE)), - "https://test.search.windows.net/servicestats"), - - Arguments.of(toCallable(searchIndexAsyncClient.createIndexWithResponse(index)), - "https://test.search.windows.net/indexes"), - Arguments.of(toCallable(searchIndexAsyncClient.getIndexWithResponse("index")), indexUrl), - Arguments.of(toCallable(searchIndexAsyncClient.getIndexStatisticsWithResponse("index")), - indexUrl + "/search.stats"), - Arguments.of(toCallable(searchIndexAsyncClient.listIndexes()), "https://test.search.windows.net/indexes"), - Arguments.of(toCallable(searchIndexAsyncClient.listIndexNames()), - "https://test.search.windows.net/indexes"), - Arguments.of(toCallable(searchIndexAsyncClient.createOrUpdateIndexWithResponse(index, false, false)), - indexUrl), - Arguments.of(toCallable(searchIndexAsyncClient.deleteIndexWithResponse(index, true)), indexUrl), - Arguments.of(toCallable(searchIndexAsyncClient.analyzeText("index", null)), indexUrl + "/search.analyze"), - Arguments.of(toCallable(searchIndexAsyncClient.createSynonymMapWithResponse(synonymMap)), - "https://test.search.windows.net/synonymmaps"), - Arguments.of(toCallable(searchIndexAsyncClient.getSynonymMapWithResponse("synonym")), synonymMapUrl), - Arguments.of(toCallable(searchIndexAsyncClient.listSynonymMaps()), - "https://test.search.windows.net/synonymmaps"), - Arguments.of(toCallable(searchIndexAsyncClient.listSynonymMapNames()), - "https://test.search.windows.net/synonymmaps"), - Arguments.of(toCallable(searchIndexAsyncClient.createOrUpdateSynonymMapWithResponse(synonymMap, false)), - synonymMapUrl), - Arguments.of(toCallable(searchIndexAsyncClient.deleteSynonymMapWithResponse(synonymMap, true)), - synonymMapUrl), - Arguments.of(toCallable(searchIndexAsyncClient.getServiceStatisticsWithResponse()), - "https://test.search.windows.net/servicestats"), - Arguments.of(toCallable(() -> searchIndexerClient.createOrUpdateDataSourceConnectionWithResponse(dataSource, - true, Context.NONE)), dataSourceUrl), - Arguments.of( - toCallable(() -> searchIndexerClient.createDataSourceConnectionWithResponse(dataSource, Context.NONE)), - "https://test.search.windows.net/datasources"), - Arguments.of( - toCallable(() -> searchIndexerClient.getDataSourceConnectionWithResponse("datasource", Context.NONE)), - dataSourceUrl), - Arguments.of( - toCallable(() -> searchIndexerClient.listDataSourceConnections(Context.NONE).iterator().hasNext()), - "https://test.search.windows.net/datasources"), - Arguments.of( - toCallable(() -> searchIndexerClient.listDataSourceConnectionNames(Context.NONE).iterator().hasNext()), - "https://test.search.windows.net/datasources"), - Arguments.of( - toCallable( - () -> searchIndexerClient.deleteDataSourceConnectionWithResponse(dataSource, true, Context.NONE)), - dataSourceUrl), - Arguments.of(toCallable(() -> searchIndexerClient.createIndexerWithResponse(indexer, Context.NONE)), - "https://test.search.windows.net/indexers"), - Arguments.of( - toCallable(() -> searchIndexerClient.createOrUpdateIndexerWithResponse(indexer, false, Context.NONE)), - indexerUrl), - Arguments.of(toCallable(() -> searchIndexerClient.listIndexers(Context.NONE).iterator().hasNext()), - "https://test.search.windows.net/indexers"), - Arguments.of(toCallable(() -> searchIndexerClient.listIndexerNames(Context.NONE).iterator().hasNext()), - "https://test.search.windows.net/indexers"), - Arguments.of(toCallable(() -> searchIndexerClient.getIndexerWithResponse("indexer", Context.NONE)), - indexerUrl), - Arguments.of(toCallable(() -> searchIndexerClient.deleteIndexerWithResponse(indexer, true, Context.NONE)), - indexerUrl), - Arguments.of(toCallable(() -> searchIndexerClient.resetIndexerWithResponse("indexer", Context.NONE)), - indexerUrl + "/search.reset"), - Arguments.of(toCallable(() -> searchIndexerClient.runIndexerWithResponse("indexer", Context.NONE)), - indexerUrl + "/search.run"), - Arguments.of(toCallable(() -> searchIndexerClient.getIndexerStatusWithResponse("indexer", Context.NONE)), - indexerUrl + "/search.status"), - Arguments.of(toCallable(() -> searchIndexerClient.createSkillsetWithResponse(skillset, Context.NONE)), - "https://test.search.windows.net/skillsets"), - Arguments.of(toCallable(() -> searchIndexerClient.getSkillsetWithResponse("skillset", Context.NONE)), - skillsetUrl), - Arguments.of(toCallable(() -> searchIndexerClient.listSkillsets(Context.NONE).iterator().hasNext()), - "https://test.search.windows.net/skillsets"), - Arguments.of(toCallable(() -> searchIndexerClient.listSkillsetNames(Context.NONE).iterator().hasNext()), - "https://test.search.windows.net/skillsets"), - Arguments.of( - toCallable(() -> searchIndexerClient.createOrUpdateSkillsetWithResponse(skillset, false, Context.NONE)), - skillsetUrl), - Arguments.of(toCallable(() -> searchIndexerClient.deleteSkillsetWithResponse(skillset, true, Context.NONE)), - skillsetUrl), - - Arguments.of( - toCallable(searchIndexerAsyncClient.createOrUpdateDataSourceConnectionWithResponse(dataSource, true)), - dataSourceUrl), - Arguments.of(toCallable(searchIndexerAsyncClient.createDataSourceConnectionWithResponse(dataSource)), - "https://test.search.windows.net/datasources"), - Arguments.of(toCallable(searchIndexerAsyncClient.getDataSourceConnectionWithResponse("datasource")), - dataSourceUrl), - Arguments.of(toCallable(searchIndexerAsyncClient.listDataSourceConnections()), - "https://test.search.windows.net/datasources"), - Arguments.of(toCallable(searchIndexerAsyncClient.listDataSourceConnectionNames()), - "https://test.search.windows.net/datasources"), - Arguments.of(toCallable(searchIndexerAsyncClient.deleteDataSourceConnectionWithResponse(dataSource, true)), - dataSourceUrl), - Arguments.of(toCallable(searchIndexerAsyncClient.createIndexerWithResponse(indexer)), - "https://test.search.windows.net/indexers"), - Arguments.of(toCallable(searchIndexerAsyncClient.createOrUpdateIndexerWithResponse(indexer, false)), - indexerUrl), - Arguments.of(toCallable(searchIndexerAsyncClient.listIndexers()), - "https://test.search.windows.net/indexers"), - Arguments.of(toCallable(searchIndexerAsyncClient.listIndexerNames()), - "https://test.search.windows.net/indexers"), - Arguments.of(toCallable(searchIndexerAsyncClient.getIndexerWithResponse("indexer")), indexerUrl), - Arguments.of(toCallable(searchIndexerAsyncClient.deleteIndexerWithResponse(indexer, true)), indexerUrl), - Arguments.of(toCallable(searchIndexerAsyncClient.resetIndexerWithResponse("indexer")), - indexerUrl + "/search.reset"), - Arguments.of(toCallable(searchIndexerAsyncClient.runIndexerWithResponse("indexer")), - indexerUrl + "/search.run"), - Arguments.of(toCallable(searchIndexerAsyncClient.getIndexerStatusWithResponse("indexer")), - indexerUrl + "/search.status"), - Arguments.of(toCallable(searchIndexerAsyncClient.createSkillsetWithResponse(skillset)), - "https://test.search.windows.net/skillsets"), - Arguments.of(toCallable(searchIndexerAsyncClient.getSkillsetWithResponse("skillset")), skillsetUrl), - Arguments.of(toCallable(searchIndexerAsyncClient.listSkillsets()), - "https://test.search.windows.net/skillsets"), - Arguments.of(toCallable(searchIndexerAsyncClient.listSkillsetNames()), - "https://test.search.windows.net/skillsets"), - Arguments.of(toCallable(searchIndexerAsyncClient.createOrUpdateSkillsetWithResponse(skillset, false)), - skillsetUrl), - Arguments.of(toCallable(searchIndexerAsyncClient.deleteSkillsetWithResponse(skillset, true)), skillsetUrl), - Arguments.of(toCallable(searchIndexerAsyncClient.deleteSkillsetWithResponse(skillset, true)), skillsetUrl)); - } - - private static Callable toCallable(Supplier apiCall) { - return () -> apiCall; - } - - private static Callable toCallable(Mono apiCall) { - return apiCall::block; - } - - private static Callable toCallable(Flux apiCall) { - return apiCall::blockFirst; - } - - private static final class UrlRewriteException extends RuntimeException { - private final String rewrittenUrl; - - UrlRewriteException(String message, String rewrittenUrl) { - super(message); - - this.rewrittenUrl = rewrittenUrl; - } - } -} diff --git a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/test/environment/models/AddressCircularDependencies.java b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/test/environment/models/AddressCircularDependencies.java deleted file mode 100644 index 4aa88cdb7851..000000000000 --- a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/test/environment/models/AddressCircularDependencies.java +++ /dev/null @@ -1,32 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.search.documents.test.environment.models; - -/** - * The address model class to test circular dependencies. - */ -public class AddressCircularDependencies { - - private HotelCircularDependencies hotel; - - /** - * Get hotel address. - * - * @return the hotel address. - */ - public HotelCircularDependencies getHotel() { - return hotel; - } - - /** - * Sets hotel address. - * - * @param hotel the hotel address. - * @return The {@link AddressCircularDependencies} object itself. - */ - public AddressCircularDependencies setHotel(HotelCircularDependencies hotel) { - this.hotel = hotel; - return this; - } -} diff --git a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/test/environment/models/Author.java b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/test/environment/models/Author.java deleted file mode 100644 index 67f234a245fb..000000000000 --- a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/test/environment/models/Author.java +++ /dev/null @@ -1,31 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -package com.azure.search.documents.test.environment.models; - -import com.fasterxml.jackson.annotation.JsonProperty; - -public class Author { - @JsonProperty(value = "FirstName") - private String firstName; - - @JsonProperty(value = "LastName") - private String lastName; - - public String firstName() { - return this.firstName; - } - - public Author firstName(String firstName) { - this.firstName = firstName; - return this; - } - - public String lastName() { - return this.lastName; - } - - public Author lastName(String lastName) { - this.lastName = lastName; - return this; - } -} diff --git a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/test/environment/models/Book.java b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/test/environment/models/Book.java deleted file mode 100644 index 605194898a70..000000000000 --- a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/test/environment/models/Book.java +++ /dev/null @@ -1,57 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -package com.azure.search.documents.test.environment.models; - -import com.fasterxml.jackson.annotation.JsonProperty; - -import java.time.OffsetDateTime; - -public class Book { - @JsonProperty(value = "ISBN") - private String ISBN; - - @JsonProperty(value = "Title") - private String title; - - @JsonProperty(value = "Author") - private Author author; - - @JsonProperty(value = "PublishDate") - private OffsetDateTime publishDate; - - public String ISBN() { - return this.ISBN; - } - - public Book ISBN(String ISBN) { - this.ISBN = ISBN; - return this; - } - - public String title() { - return this.title; - } - - public Book title(String title) { - this.title = title; - return this; - } - - public Author author() { - return this.author; - } - - public Book author(Author author) { - this.author = author; - return this; - } - - public OffsetDateTime publishDate() { - return this.publishDate; - } - - public Book publishDate(OffsetDateTime publishDate) { - this.publishDate = publishDate; - return this; - } -} diff --git a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/test/environment/models/Bucket.java b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/test/environment/models/Bucket.java deleted file mode 100644 index cf3592309b5d..000000000000 --- a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/test/environment/models/Bucket.java +++ /dev/null @@ -1,32 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -package com.azure.search.documents.test.environment.models; - -import com.fasterxml.jackson.annotation.JsonProperty; - -public class Bucket { - - @JsonProperty(value = "BucketName") - private String bucketName; - - @JsonProperty(value = "Count") - private int count; - - public Bucket bucketName(String bucketName) { - this.bucketName = bucketName; - return this; - } - - public String getBucketName() { - return this.bucketName; - } - - public Bucket count(int count) { - this.count = count; - return this; - } - - public int getCount() { - return count; - } -} diff --git a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/test/environment/models/Car.java b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/test/environment/models/Car.java deleted file mode 100644 index 98e437b3bde1..000000000000 --- a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/test/environment/models/Car.java +++ /dev/null @@ -1,25 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -package com.azure.search.documents.test.environment.models; - -public class Car { - - private String color; - private String type; - - public String getColor() { - return color; - } - - public void setColor(final String color) { - this.color = color; - } - - public String getType() { - return type; - } - - public void setType(final String type) { - this.type = type; - } -} diff --git a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/test/environment/models/Entry.java b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/test/environment/models/Entry.java deleted file mode 100644 index 712ccb380477..000000000000 --- a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/test/environment/models/Entry.java +++ /dev/null @@ -1,22 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -package com.azure.search.documents.test.environment.models; - -import com.fasterxml.jackson.annotation.JsonProperty; - -import java.util.Date; - -@SuppressWarnings("ALL") -public class Entry { - - @JsonProperty - Date date; - - public Date date() { - return (date == null) ? null : (Date) date.clone(); - } - - public void date(Date date) { - this.date = (date == null) ? null : (Date) date.clone(); - } -} diff --git a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/test/environment/models/Foo.java b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/test/environment/models/Foo.java deleted file mode 100644 index a3978236379d..000000000000 --- a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/test/environment/models/Foo.java +++ /dev/null @@ -1,35 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -package com.azure.search.documents.test.environment.models; - -import com.azure.search.documents.indexes.SimpleField; - -public class Foo { - @SimpleField(isKey = true) - private String intValue; - private String stringValue; - - public Foo() { - } - - public Foo(final String intValue, final String stringValue) { - this.intValue = intValue; - this.stringValue = stringValue; - } - - public String getIntValue() { - return intValue; - } - - public void setIntValue(final String intValue) { - this.intValue = intValue; - } - - public String getStringValue() { - return stringValue; - } - - public void setStringValue(final String stringValue) { - this.stringValue = stringValue; - } -} diff --git a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/test/environment/models/Hotel.java b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/test/environment/models/Hotel.java deleted file mode 100644 index 5801f76bba82..000000000000 --- a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/test/environment/models/Hotel.java +++ /dev/null @@ -1,199 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -package com.azure.search.documents.test.environment.models; - -import com.azure.core.models.GeoPoint; -import com.azure.search.documents.indexes.FieldBuilderIgnore; -import com.azure.search.documents.indexes.SearchableField; -import com.azure.search.documents.indexes.SimpleField; -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; - -import java.util.ArrayList; -import java.util.Date; -import java.util.List; - -@SuppressWarnings("UseOfObsoleteDateTimeApi") -@JsonIgnoreProperties(ignoreUnknown = true) -public class Hotel { - @SimpleField(isKey = true, isSortable = true) - @JsonProperty(value = "HotelId") - @JsonInclude(JsonInclude.Include.NON_NULL) - private String hotelId; - - @SearchableField(isSortable = true, analyzerName = "en.lucene") - @JsonProperty(value = "HotelName") - @JsonInclude(JsonInclude.Include.NON_NULL) - private String hotelName; - - @SimpleField - @JsonProperty(value = "Description") - @JsonInclude(JsonInclude.Include.NON_NULL) - private String description; - - @FieldBuilderIgnore - @JsonProperty(value = "Description_fr") - @JsonInclude(JsonInclude.Include.NON_NULL) - private String descriptionFr; - - @SimpleField - @JsonProperty(value = "Category") - @JsonInclude(JsonInclude.Include.NON_NULL) - private String category; - - @SearchableField - @JsonProperty(value = "Tags") - @JsonInclude(JsonInclude.Include.NON_NULL) - private List tags; - - @JsonProperty(value = "ParkingIncluded") - @JsonInclude(JsonInclude.Include.NON_NULL) - private Boolean parkingIncluded; - - @JsonProperty(value = "SmokingAllowed") - @JsonInclude(JsonInclude.Include.NON_NULL) - private Boolean smokingAllowed; - - @JsonProperty(value = "LastRenovationDate") - @JsonInclude(JsonInclude.Include.NON_NULL) - private Date lastRenovationDate; - - @JsonProperty(value = "Rating") - @JsonInclude(JsonInclude.Include.NON_NULL) - private Integer rating; - - @JsonProperty(value = "Location") - @JsonInclude(JsonInclude.Include.NON_NULL) - private GeoPoint location; - - @JsonProperty(value = "Address") - @JsonInclude(JsonInclude.Include.NON_NULL) - private HotelAddress address; - - @JsonProperty(value = "Rooms") - @JsonInclude(JsonInclude.Include.NON_NULL) - private List rooms; - - public Hotel() { - this.tags = new ArrayList<>(); - this.rooms = new ArrayList<>(); - } - - public String hotelId() { - return this.hotelId; - } - - public Hotel hotelId(String hotelId) { - this.hotelId = hotelId; - return this; - } - - public String hotelName() { - return this.hotelName; - } - - public Hotel hotelName(String hotelName) { - this.hotelName = hotelName; - return this; - } - - public String description() { - return this.description; - } - - public Hotel description(String description) { - this.description = description; - return this; - } - - public String descriptionFr() { - return this.descriptionFr; - } - - public Hotel descriptionFr(String descriptionFr) { - this.descriptionFr = descriptionFr; - return this; - } - - public String category() { - return this.category; - } - - public Hotel category(String category) { - this.category = category; - return this; - } - - public List tags() { - return (this.tags == null) ? null : new ArrayList<>(this.tags); - } - - public Hotel tags(List tags) { - this.tags = (tags == null) ? null : new ArrayList<>(tags); - return this; - } - - public Boolean parkingIncluded() { - return this.parkingIncluded; - } - - public Hotel parkingIncluded(Boolean parkingIncluded) { - this.parkingIncluded = parkingIncluded; - return this; - } - - public Boolean smokingAllowed() { - return this.smokingAllowed; - } - - public Hotel smokingAllowed(Boolean smokingAllowed) { - this.smokingAllowed = smokingAllowed; - return this; - } - - public Date lastRenovationDate() { - return (this.lastRenovationDate == null) ? null : (Date) this.lastRenovationDate.clone(); - } - - public Hotel lastRenovationDate(Date lastRenovationDate) { - this.lastRenovationDate = (lastRenovationDate == null) ? null : (Date) lastRenovationDate.clone(); - return this; - } - - public GeoPoint location() { - return location; - } - - public Hotel location(GeoPoint location) { - this.location = location; - return this; - } - - public Integer rating() { - return this.rating; - } - - public Hotel rating(Integer rating) { - this.rating = rating; - return this; - } - - public HotelAddress address() { - return this.address; - } - - public Hotel address(HotelAddress address) { - this.address = address; - return this; - } - - public List rooms() { - return this.rooms; - } - - public Hotel rooms(List rooms) { - this.rooms = rooms; - return this; - } -} diff --git a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/test/environment/models/HotelAddress.java b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/test/environment/models/HotelAddress.java deleted file mode 100644 index 93a5004d7f2e..000000000000 --- a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/test/environment/models/HotelAddress.java +++ /dev/null @@ -1,80 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -package com.azure.search.documents.test.environment.models; - -import com.azure.search.documents.indexes.SearchableField; -import com.azure.search.documents.indexes.SimpleField; -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; - -public class HotelAddress { - @SimpleField(isFacetable = true) - @JsonProperty(value = "StreetAddress") - @JsonInclude(JsonInclude.Include.NON_NULL) - private String streetAddress; - - @SearchableField(isFilterable = true) - @JsonProperty(value = "City") - @JsonInclude(JsonInclude.Include.NON_NULL) - private String city; - - @SearchableField - @JsonProperty(value = "StateProvince") - @JsonInclude(JsonInclude.Include.NON_NULL) - private String stateProvince; - - @SearchableField(synonymMapNames = { "fieldbuilder" }) - @JsonProperty(value = "Country") - @JsonInclude(JsonInclude.Include.NON_NULL) - private String country; - - @SimpleField - @JsonProperty(value = "PostalCode") - @JsonInclude(JsonInclude.Include.NON_NULL) - private String postalCode; - - public String streetAddress() { - return this.streetAddress; - } - - public HotelAddress streetAddress(String streetAddress) { - this.streetAddress = streetAddress; - return this; - } - - public String city() { - return this.city; - } - - public HotelAddress city(String city) { - this.city = city; - return this; - } - - public String stateProvince() { - return this.stateProvince; - } - - public HotelAddress stateProvince(String stateProvince) { - this.stateProvince = stateProvince; - return this; - } - - public String country() { - return this.country; - } - - public HotelAddress country(String country) { - this.country = country; - return this; - } - - public String postalCode() { - return this.postalCode; - } - - public HotelAddress postalCode(String postalCode) { - this.postalCode = postalCode; - return this; - } -} diff --git a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/test/environment/models/HotelAnalyzerException.java b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/test/environment/models/HotelAnalyzerException.java deleted file mode 100644 index 4a65820f49af..000000000000 --- a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/test/environment/models/HotelAnalyzerException.java +++ /dev/null @@ -1,32 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.search.documents.test.environment.models; - -import com.azure.search.documents.indexes.SearchableField; - -public class HotelAnalyzerException extends RuntimeException { - private String tag; - - /** - * Gets the tag. - * - * @return The tag of hotel. - */ - @SearchableField(analyzerName = "en.microsoft", indexAnalyzerName = "whitespce") - public String getTag() { - return tag; - } - - /** - * Sets the pattern. - * - * @param tag The tag of hotel. - * @return the {@link HotelAnalyzerException} object itself. - */ - public HotelAnalyzerException setTag(String tag) { - this.tag = tag; - return this; - } - -} diff --git a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/test/environment/models/HotelCircularDependencies.java b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/test/environment/models/HotelCircularDependencies.java deleted file mode 100644 index a8f7cb1b884c..000000000000 --- a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/test/environment/models/HotelCircularDependencies.java +++ /dev/null @@ -1,52 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.search.documents.test.environment.models; - -/** - * The model class to test the behaviour of circular dependencies - */ -public class HotelCircularDependencies { - private AddressCircularDependencies homeAddress; - private AddressCircularDependencies billingAddress; - - /** - * Gets home address. - * - * @return home address. - */ - public AddressCircularDependencies getHomeAddress() { - return homeAddress; - } - - /** - * Sets home address. - * - * @param homeAddress Home address to set. - * @return The {@link HotelCircularDependencies} object itself. - */ - public HotelCircularDependencies setHomeAddress(AddressCircularDependencies homeAddress) { - this.homeAddress = homeAddress; - return this; - } - - /** - * Gets billing address. - * - * @return billing address. - */ - public AddressCircularDependencies getBillingAddress() { - return billingAddress; - } - - /** - * Sets billing address. - * - * @param billingAddress Billing address to set. - * @return The {@link HotelCircularDependencies} object itself. - */ - public HotelCircularDependencies setBillingAddress(AddressCircularDependencies billingAddress) { - this.billingAddress = billingAddress; - return this; - } -} diff --git a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/test/environment/models/HotelRenameProperty.java b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/test/environment/models/HotelRenameProperty.java deleted file mode 100644 index bb17db8d1695..000000000000 --- a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/test/environment/models/HotelRenameProperty.java +++ /dev/null @@ -1,46 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.search.documents.test.environment.models; - -import com.azure.search.documents.indexes.SearchableField; -import com.azure.search.documents.indexes.SimpleField; -import com.fasterxml.jackson.annotation.JsonProperty; - -public class HotelRenameProperty { - private String hotelId; - private String hotelName; - private String description; - - @SimpleField(isKey = true, isSortable = true) - @JsonProperty - public String getHotelId() { - return this.hotelId; - } - - public HotelRenameProperty setHotelId(String hotelId) { - this.hotelId = hotelId; - return this; - } - - @SearchableField(isSortable = true, analyzerName = "en.lucene") - @JsonProperty(value = "HotelName") - public String getHotelName() { - return this.hotelName; - } - - public HotelRenameProperty setHotelName(String hotelName) { - this.hotelName = hotelName; - return this; - } - - @SimpleField - public String getDescription() { - return this.description; - } - - public HotelRenameProperty setDescription(String description) { - this.description = description; - return this; - } -} diff --git a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/test/environment/models/HotelRoom.java b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/test/environment/models/HotelRoom.java deleted file mode 100644 index 150c6cde814f..000000000000 --- a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/test/environment/models/HotelRoom.java +++ /dev/null @@ -1,115 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -package com.azure.search.documents.test.environment.models; - -import com.azure.core.util.CoreUtils; -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonPropertyOrder; - -@JsonPropertyOrder({ "Description", "Description_fr", "Type", "BaseRate", "BedOptions", "BedOptions", "SleepsCount", }) -public class HotelRoom { - @JsonProperty(value = "Description") - @JsonInclude(JsonInclude.Include.NON_NULL) - private String description; - - @JsonProperty(value = "Description_fr") - @JsonInclude(JsonInclude.Include.NON_NULL) - private String descriptionFr; - - @JsonProperty(value = "Type") - @JsonInclude(JsonInclude.Include.NON_NULL) - private String type; - - @JsonProperty(value = "BaseRate") - @JsonInclude(JsonInclude.Include.NON_NULL) - private Double baseRate; - - @JsonProperty(value = "BedOptions") - @JsonInclude(JsonInclude.Include.NON_NULL) - private String bedOptions; - - @JsonProperty(value = "SleepsCount") - @JsonInclude(JsonInclude.Include.NON_NULL) - private Integer sleepsCount; - - @JsonProperty(value = "SmokingAllowed") - @JsonInclude(JsonInclude.Include.NON_NULL) - private Boolean smokingAllowed; - - @JsonProperty(value = "Tags") - @JsonInclude(JsonInclude.Include.NON_NULL) - private String[] tags; - - public String description() { - return this.description; - } - - public HotelRoom description(String description) { - this.description = description; - return this; - } - - public String descriptionFr() { - return this.descriptionFr; - } - - public HotelRoom descriptionFr(String descriptionFr) { - this.descriptionFr = descriptionFr; - return this; - } - - public String type() { - return this.type; - } - - public HotelRoom type(String type) { - this.type = type; - return this; - } - - public Double baseRate() { - return this.baseRate; - } - - public HotelRoom baseRate(Double baseRate) { - this.baseRate = baseRate; - return this; - } - - public String bedOptions() { - return this.bedOptions; - } - - public HotelRoom bedOptions(String bedOptions) { - this.bedOptions = bedOptions; - return this; - } - - public Integer sleepsCount() { - return this.sleepsCount; - } - - public HotelRoom sleepsCount(Integer sleepsCount) { - this.sleepsCount = sleepsCount; - return this; - } - - public Boolean smokingAllowed() { - return this.smokingAllowed; - } - - public HotelRoom smokingAllowed(Boolean smokingAllowed) { - this.smokingAllowed = smokingAllowed; - return this; - } - - public String[] tags() { - return CoreUtils.clone(this.tags); - } - - public HotelRoom tags(String[] tags) { - this.tags = CoreUtils.clone(tags); - return this; - } -} diff --git a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/test/environment/models/HotelSearchException.java b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/test/environment/models/HotelSearchException.java deleted file mode 100644 index 189f64a74f14..000000000000 --- a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/test/environment/models/HotelSearchException.java +++ /dev/null @@ -1,34 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.search.documents.test.environment.models; - -import com.azure.search.documents.indexes.SearchableField; - -/** - * The data object model is to test exception case. - */ -public class HotelSearchException extends RuntimeException { - private int hotelId; - - /** - * Gets hotel id. - * - * @return Get hotel id - */ - @SearchableField - public int getHotelId() { - return hotelId; - } - - /** - * Sets hotel id. - * - * @param hotelId The hotel id. - * @return the {@link HotelSearchException} object itself. - */ - public HotelSearchException setHotelId(int hotelId) { - this.hotelId = hotelId; - return this; - } -} diff --git a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/test/environment/models/HotelSearchableExceptionOnList.java b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/test/environment/models/HotelSearchableExceptionOnList.java deleted file mode 100644 index 0b3670ec2951..000000000000 --- a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/test/environment/models/HotelSearchableExceptionOnList.java +++ /dev/null @@ -1,36 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.search.documents.test.environment.models; - -import com.azure.search.documents.indexes.SearchableField; - -import java.util.ArrayList; -import java.util.List; - -/** - * Helper class on test searchable exception field. - */ -public class HotelSearchableExceptionOnList { - private List passcode; - - /** - * Gets passcode. - * @return the passcode of hotel. - */ - @SearchableField - public List getPasscode() { - return (passcode == null) ? null : new ArrayList<>(passcode); - } - - /** - * Sets passcode. - * - * @param passcode the passcode of hotel. - * @return The {@link HotelSearchableExceptionOnList} object itself. - */ - public HotelSearchableExceptionOnList setPasscode(List passcode) { - this.passcode = (passcode == null) ? null : new ArrayList<>(passcode); - return this; - } -} diff --git a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/test/environment/models/HotelTwoDimensional.java b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/test/environment/models/HotelTwoDimensional.java deleted file mode 100644 index f4a3ad1b18af..000000000000 --- a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/test/environment/models/HotelTwoDimensional.java +++ /dev/null @@ -1,35 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.search.documents.test.environment.models; - -import java.util.ArrayList; -import java.util.List; - -/** - * The class is to test unsupported two-dimensional type. - */ -public class HotelTwoDimensional { - private List> matrix; - - /** - * Gets the matrix - * - * @return The matrix of hotel. - */ - public List> getMatrix() { - return (matrix == null) ? null : new ArrayList<>(matrix); - } - - /** - * Sets the matrix. - * - * @param matrix The matrix of hotel. - * @return The {@link HotelTwoDimensional} object itself. - */ - public HotelTwoDimensional setMatrix(List> matrix) { - this.matrix = (matrix == null) ? null : new ArrayList<>(matrix); - return this; - } - -} diff --git a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/test/environment/models/HotelWithArray.java b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/test/environment/models/HotelWithArray.java deleted file mode 100644 index e789a5197fcf..000000000000 --- a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/test/environment/models/HotelWithArray.java +++ /dev/null @@ -1,23 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.search.documents.test.environment.models; - -import com.azure.core.util.CoreUtils; -import com.azure.search.documents.indexes.SearchableField; -import com.azure.search.documents.indexes.SimpleField; - -public class HotelWithArray { - private String hotelId; - private String[] tags; - - @SimpleField(isKey = true, isSortable = true) - public String getHotelId() { - return hotelId; - } - - @SearchableField - public String[] getTags() { - return CoreUtils.clone(tags); - } -} diff --git a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/test/environment/models/HotelWithEmptyInSynonymMaps.java b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/test/environment/models/HotelWithEmptyInSynonymMaps.java deleted file mode 100644 index a6239d3f1dd0..000000000000 --- a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/test/environment/models/HotelWithEmptyInSynonymMaps.java +++ /dev/null @@ -1,37 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.search.documents.test.environment.models; - -import com.azure.search.documents.indexes.SearchableField; - -import java.util.ArrayList; -import java.util.List; - -/** - * This is a class to test whether we filter out the empty String in synonymMaps. - */ -public class HotelWithEmptyInSynonymMaps { - private List tags; - - /** - * Gets the tags. - * - * @return The tags of hotel. - */ - @SearchableField(synonymMapNames = { "asynonymMaps", "", " ", "maps" }) - public List getTags() { - return (tags == null) ? null : new ArrayList<>(tags); - } - - /** - * Set the tags - * - * @param tags The tags of hotel. - * @return The {@link HotelWithEmptyInSynonymMaps} object itself. - */ - public HotelWithEmptyInSynonymMaps setTags(List tags) { - this.tags = (tags == null) ? null : new ArrayList<>(tags); - return this; - } -} diff --git a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/test/environment/models/HotelWithIgnoredFields.java b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/test/environment/models/HotelWithIgnoredFields.java deleted file mode 100644 index d30d86d411f9..000000000000 --- a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/test/environment/models/HotelWithIgnoredFields.java +++ /dev/null @@ -1,27 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.search.documents.test.environment.models; - -import com.azure.search.documents.indexes.FieldBuilderIgnore; -import com.fasterxml.jackson.annotation.JsonIgnore; - -public class HotelWithIgnoredFields { - private String hotelId; - private String hotelName; - private String notIgnoredName; - - @FieldBuilderIgnore - public String getHotelId() { - return hotelId; - } - - @JsonIgnore - public String getHotelName() { - return hotelName; - } - - public String getNotIgnoredName() { - return notIgnoredName; - } -} diff --git a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/test/environment/models/HotelWithUnsupportedField.java b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/test/environment/models/HotelWithUnsupportedField.java deleted file mode 100644 index fd9bb897e909..000000000000 --- a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/test/environment/models/HotelWithUnsupportedField.java +++ /dev/null @@ -1,27 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.search.documents.test.environment.models; - -import java.util.ArrayList; -import java.util.List; - -public class HotelWithUnsupportedField { - private String hotelId; - - private Byte someByte; - - private List someListBytes; - - public String getHotelId() { - return hotelId; - } - - public Byte getSomeByte() { - return someByte; - } - - public List getSomeListBytes() { - return (someListBytes == null) ? null : new ArrayList<>(someListBytes); - } -} diff --git a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/test/environment/models/LoudHotel.java b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/test/environment/models/LoudHotel.java deleted file mode 100644 index cecbcde46980..000000000000 --- a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/test/environment/models/LoudHotel.java +++ /dev/null @@ -1,188 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -package com.azure.search.documents.test.environment.models; - -import com.azure.core.models.GeoPoint; -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; - -import java.util.ArrayList; -import java.util.Date; -import java.util.List; - -@SuppressWarnings({ "UseOfObsoleteDateTimeApi", "unused" }) -@JsonIgnoreProperties(ignoreUnknown = true) -public class LoudHotel { - @JsonProperty(value = "HotelId") - @JsonInclude(JsonInclude.Include.NON_NULL) - private String HOTELID; - - @JsonProperty(value = "HotelName") - @JsonInclude(JsonInclude.Include.NON_NULL) - private String HOTELNAME; - - @JsonProperty(value = "Description") - private String DESCRIPTION; - - @JsonProperty(value = "Description_fr") - @JsonInclude(JsonInclude.Include.NON_NULL) - private String DESCRIPTIONFRENCH; - - @JsonProperty(value = "Category") - @JsonInclude(JsonInclude.Include.NON_NULL) - private String CATEGORY; - - @JsonProperty(value = "Tags") - @JsonInclude(JsonInclude.Include.NON_NULL) - private List TAGS; - - @JsonProperty(value = "ParkingIncluded") - @JsonInclude(JsonInclude.Include.NON_NULL) - private Boolean PARKINGINCLUDED; - - @JsonProperty(value = "SmokingAllowed") - @JsonInclude(JsonInclude.Include.NON_NULL) - private Boolean SMOKINGALLOWED; - - @JsonProperty(value = "LastRenovationDate") - @JsonInclude(JsonInclude.Include.NON_NULL) - private Date LASTRENOVATIONDATE; - - @JsonProperty(value = "Rating") - @JsonInclude(JsonInclude.Include.NON_NULL) - private Integer RATING; - - @JsonProperty(value = "Location") - private GeoPoint LOCATION; - - @JsonProperty(value = "Address") - @JsonInclude(JsonInclude.Include.NON_NULL) - private HotelAddress ADDRESS; - - @JsonProperty(value = "Rooms") - @JsonInclude(JsonInclude.Include.NON_NULL) - private List ROOMS; - - public LoudHotel() { - this.TAGS = new ArrayList<>(); - this.ROOMS = new ArrayList<>(); - } - - public String HOTELID() { - return this.HOTELID; - } - - public LoudHotel HOTELID(String hotelId) { - this.HOTELID = hotelId; - return this; - } - - public String HOTELNAME() { - return this.HOTELNAME; - } - - public LoudHotel HOTELNAME(String hotelName) { - this.HOTELNAME = hotelName; - return this; - } - - public String DESCRIPTION() { - return this.DESCRIPTION; - } - - public LoudHotel DESCRIPTION(String description) { - this.DESCRIPTION = description; - return this; - } - - public String DESCRIPTIONFRENCH() { - return this.DESCRIPTIONFRENCH; - } - - public LoudHotel DESCRIPTIONFRENCH(String descriptionFr) { - this.DESCRIPTIONFRENCH = descriptionFr; - return this; - } - - public String CATEGORY() { - return this.CATEGORY; - } - - public LoudHotel CATEGORY(String category) { - this.CATEGORY = category; - return this; - } - - public List TAGS() { - return (this.TAGS) == null ? null : new ArrayList<>(this.TAGS); - } - - public LoudHotel TAGS(List tags) { - this.TAGS = (tags == null) ? null : new ArrayList<>(tags); - return this; - } - - public Boolean PARKINGINCLUDED() { - return this.PARKINGINCLUDED; - } - - public LoudHotel PARKINGINCLUDED(Boolean parkingIncluded) { - this.PARKINGINCLUDED = parkingIncluded; - return this; - } - - public Boolean SMOKINGALLOWED() { - return this.SMOKINGALLOWED; - } - - public LoudHotel SMOKINGALLOWED(Boolean smokingAllowed) { - this.SMOKINGALLOWED = smokingAllowed; - return this; - } - - public Date LASTRENOVATIONDATE() { - return (this.LASTRENOVATIONDATE == null) ? null : (Date) this.LASTRENOVATIONDATE.clone(); - } - - public LoudHotel LASTRENOVATIONDATE(Date lastRenovationDate) { - this.LASTRENOVATIONDATE = (lastRenovationDate == null) ? null : (Date) lastRenovationDate.clone(); - return this; - } - - public Integer RATING() { - return this.RATING; - } - - public LoudHotel RATING(Integer rating) { - this.RATING = rating; - return this; - } - - public GeoPoint LOCATION() { - return this.LOCATION; - } - - public LoudHotel LOCATION(GeoPoint location) { - this.LOCATION = location; - return this; - } - - public HotelAddress ADDRESS() { - return this.ADDRESS; - } - - public LoudHotel ADDRESS(HotelAddress address) { - this.ADDRESS = address; - return this; - } - - public List ROOMS() { - return (this.ROOMS == null) ? null : new ArrayList<>(this.ROOMS); - } - - public LoudHotel ROOMS(List rooms) { - this.ROOMS = (rooms == null) ? null : new ArrayList<>(rooms); - return this; - } -} diff --git a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/test/environment/models/ModelWithPrimitiveCollections.java b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/test/environment/models/ModelWithPrimitiveCollections.java deleted file mode 100644 index 37b220739947..000000000000 --- a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/test/environment/models/ModelWithPrimitiveCollections.java +++ /dev/null @@ -1,111 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -package com.azure.search.documents.test.environment.models; - -import com.azure.core.models.GeoPoint; -import com.azure.core.util.CoreUtils; -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import com.fasterxml.jackson.annotation.JsonProperty; - -import java.time.OffsetDateTime; - -@SuppressWarnings("unused") -@JsonIgnoreProperties(ignoreUnknown = true) -public class ModelWithPrimitiveCollections { - - @JsonProperty(value = "Key") - private String key; - - @JsonProperty(value = "Bools") - private Boolean[] bools; - - @JsonProperty(value = "Dates") - private OffsetDateTime[] dates; - - @JsonProperty(value = "Doubles") - private Double[] doubles; - - @JsonProperty(value = "Ints") - private int[] ints; - - @JsonProperty(value = "Longs") - private Long[] longs; - - @JsonProperty(value = "Points") - private GeoPoint[] points; - - @JsonProperty(value = "Strings") - private String[] strings; - - public String key() { - return this.key; - } - - public ModelWithPrimitiveCollections key(String key) { - this.key = key; - return this; - } - - public ModelWithPrimitiveCollections bools(Boolean[] bools) { - this.bools = CoreUtils.clone(bools); - return this; - } - - public Boolean[] bools() { - return CoreUtils.clone(bools); - } - - public ModelWithPrimitiveCollections dates(OffsetDateTime[] dates) { - this.dates = CoreUtils.clone(dates); - return this; - } - - public OffsetDateTime[] dates() { - return CoreUtils.clone(dates); - } - - public ModelWithPrimitiveCollections doubles(Double[] doubles) { - this.doubles = CoreUtils.clone(doubles); - return this; - } - - public Double[] doubles() { - return CoreUtils.clone(doubles); - } - - public ModelWithPrimitiveCollections ints(int[] ints) { - this.ints = CoreUtils.clone(ints); - return this; - } - - public int[] ints() { - return CoreUtils.clone(ints); - } - - public ModelWithPrimitiveCollections longs(Long[] longs) { - this.longs = CoreUtils.clone(longs); - return this; - } - - public Long[] longs() { - return CoreUtils.clone(longs); - } - - public ModelWithPrimitiveCollections points(GeoPoint[] points) { - this.points = CoreUtils.clone(points); - return this; - } - - public GeoPoint[] points() { - return CoreUtils.clone(points); - } - - public ModelWithPrimitiveCollections strings(String[] strings) { - this.strings = CoreUtils.clone(strings); - return this; - } - - public String[] strings() { - return CoreUtils.clone(strings); - } -} diff --git a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/test/environment/models/NonNullableModel.java b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/test/environment/models/NonNullableModel.java deleted file mode 100644 index bbc5918c8b54..000000000000 --- a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/test/environment/models/NonNullableModel.java +++ /dev/null @@ -1,88 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -package com.azure.search.documents.test.environment.models; - -import com.azure.core.util.CoreUtils; -import com.fasterxml.jackson.annotation.JsonProperty; - -import java.util.Date; - -@SuppressWarnings("UseOfObsoleteDateTimeApi") -public class NonNullableModel { - - @JsonProperty(value = "Key") - private String key; - - @JsonProperty(value = "Rating") - private int rating; - - @JsonProperty(value = "Count") - private long count; - - @JsonProperty(value = "IsEnabled") - private boolean isEnabled; - - @JsonProperty(value = "Ratio") - private double ratio; - - @JsonProperty(value = "StartDate") - private Date startDate; - - @JsonProperty(value = "EndDate") - private Date endDate; - - @JsonProperty(value = "TopLevelBucket") - private Bucket topLevelBucket; - - @JsonProperty(value = "Buckets") - private Bucket[] buckets; - - public String key() { - return key; - } - - public NonNullableModel key(String key) { - this.key = key; - return this; - } - - public NonNullableModel rating(int rating) { - this.rating = rating; - return this; - } - - public NonNullableModel count(long count) { - this.count = count; - return this; - } - - public NonNullableModel isEnabled(boolean enabled) { - isEnabled = enabled; - return this; - } - - public NonNullableModel ratio(double ratio) { - this.ratio = ratio; - return this; - } - - public NonNullableModel startDate(Date startDate) { - this.startDate = (startDate == null) ? null : (Date) startDate.clone(); - return this; - } - - public NonNullableModel endDate(Date endDate) { - this.endDate = (endDate == null) ? null : (Date) endDate.clone(); - return this; - } - - public NonNullableModel topLevelBucket(Bucket topLevelBucket) { - this.topLevelBucket = topLevelBucket; - return this; - } - - public NonNullableModel buckets(Bucket[] buckets) { - this.buckets = CoreUtils.clone(buckets); - return this; - } -} diff --git a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/test/environment/models/VectorHotel.java b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/test/environment/models/VectorHotel.java deleted file mode 100644 index f4c4547a6a2b..000000000000 --- a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/test/environment/models/VectorHotel.java +++ /dev/null @@ -1,215 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.search.documents.test.environment.models; - -import com.azure.core.models.GeoPoint; -import com.azure.search.documents.VectorSearchEmbeddings; -import com.azure.search.documents.indexes.FieldBuilderIgnore; -import com.azure.search.documents.indexes.SearchableField; -import com.azure.search.documents.indexes.SimpleField; -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; - -import java.util.ArrayList; -import java.util.Date; -import java.util.List; - -@SuppressWarnings("UseOfObsoleteDateTimeApi") -@JsonIgnoreProperties(ignoreUnknown = true) -public class VectorHotel { - @SimpleField(isKey = true, isSortable = true) - @JsonProperty(value = "HotelId") - @JsonInclude(JsonInclude.Include.NON_NULL) - private String hotelId; - - @SearchableField(isSortable = true, analyzerName = "en.lucene") - @JsonProperty(value = "HotelName") - @JsonInclude(JsonInclude.Include.NON_NULL) - private String hotelName; - - @SimpleField - @JsonProperty(value = "Description") - @JsonInclude(JsonInclude.Include.NON_NULL) - private String description; - - @FieldBuilderIgnore - @JsonProperty(value = "Description_fr") - @JsonInclude(JsonInclude.Include.NON_NULL) - private String descriptionFr; - - @FieldBuilderIgnore - @JsonProperty(value = "DescriptionVector") - @JsonInclude(JsonInclude.Include.NON_NULL) - private List descriptionVector = VectorSearchEmbeddings.DEFAULT_VECTORIZE_DESCRIPTION; // Default DescriptionVector: "Hotel" - - @SimpleField - @JsonProperty(value = "Category") - @JsonInclude(JsonInclude.Include.NON_NULL) - private String category; - - @SearchableField - @JsonProperty(value = "Tags") - @JsonInclude(JsonInclude.Include.NON_NULL) - private List tags; - - @JsonProperty(value = "ParkingIncluded") - @JsonInclude(JsonInclude.Include.NON_NULL) - private Boolean parkingIncluded; - - @JsonProperty(value = "SmokingAllowed") - @JsonInclude(JsonInclude.Include.NON_NULL) - private Boolean smokingAllowed; - - @JsonProperty(value = "LastRenovationDate") - @JsonInclude(JsonInclude.Include.NON_NULL) - private Date lastRenovationDate; - - @JsonProperty(value = "Rating") - @JsonInclude(JsonInclude.Include.NON_NULL) - private Integer rating; - - @JsonProperty(value = "Location") - @JsonInclude(JsonInclude.Include.NON_NULL) - private GeoPoint location; - - @JsonProperty(value = "Address") - @JsonInclude(JsonInclude.Include.NON_NULL) - private HotelAddress address; - - @JsonProperty(value = "Rooms") - @JsonInclude(JsonInclude.Include.NON_NULL) - private List rooms; - - public VectorHotel() { - this.tags = new ArrayList<>(); - this.rooms = new ArrayList<>(); - } - - public String hotelId() { - return this.hotelId; - } - - public VectorHotel hotelId(String hotelId) { - this.hotelId = hotelId; - return this; - } - - public String hotelName() { - return this.hotelName; - } - - public VectorHotel hotelName(String hotelName) { - this.hotelName = hotelName; - return this; - } - - public String description() { - return this.description; - } - - public VectorHotel description(String description) { - this.description = description; - return this; - } - - public String descriptionFr() { - return this.descriptionFr; - } - - public VectorHotel descriptionFr(String descriptionFr) { - this.descriptionFr = descriptionFr; - return this; - } - - public List descriptionVector() { - return (this.descriptionVector == null) ? null : new ArrayList<>(this.descriptionVector); - } - - public VectorHotel descriptionVector(List descriptionVector) { - this.descriptionVector = (descriptionVector == null) ? null : new ArrayList<>(descriptionVector); - return this; - } - - public String category() { - return this.category; - } - - public VectorHotel category(String category) { - this.category = category; - return this; - } - - public List tags() { - return (this.tags == null) ? null : new ArrayList<>(this.tags); - } - - public VectorHotel tags(List tags) { - this.tags = (tags == null) ? null : new ArrayList<>(tags); - return this; - } - - public Boolean parkingIncluded() { - return this.parkingIncluded; - } - - public VectorHotel parkingIncluded(Boolean parkingIncluded) { - this.parkingIncluded = parkingIncluded; - return this; - } - - public Boolean smokingAllowed() { - return this.smokingAllowed; - } - - public VectorHotel smokingAllowed(Boolean smokingAllowed) { - this.smokingAllowed = smokingAllowed; - return this; - } - - public Date lastRenovationDate() { - return (this.lastRenovationDate == null) ? null : (Date) this.lastRenovationDate.clone(); - } - - public VectorHotel lastRenovationDate(Date lastRenovationDate) { - this.lastRenovationDate = (lastRenovationDate == null) ? null : (Date) lastRenovationDate.clone(); - return this; - } - - public GeoPoint location() { - return location; - } - - public VectorHotel location(GeoPoint location) { - this.location = location; - return this; - } - - public Integer rating() { - return this.rating; - } - - public VectorHotel rating(Integer rating) { - this.rating = rating; - return this; - } - - public HotelAddress address() { - return this.address; - } - - public VectorHotel address(HotelAddress address) { - this.address = address; - return this; - } - - public List rooms() { - return this.rooms; - } - - public VectorHotel rooms(List rooms) { - this.rooms = rooms; - return this; - } -} diff --git a/sdk/search/azure-search-documents/src/test/resources/BooksIndexData.json b/sdk/search/azure-search-documents/src/test/resources/BooksIndexData.json deleted file mode 100644 index f244f619ac17..000000000000 --- a/sdk/search/azure-search-documents/src/test/resources/BooksIndexData.json +++ /dev/null @@ -1,41 +0,0 @@ -{ - "name": "books", - "fields": [ - { - "name": "ISBN", - "type": "Edm.String", - "key": true - }, - { - "name": "Title", - "type": "Edm.String", - "searchable": true - }, - { - "name": "Author", - "type": "Edm.ComplexType", - "fields": [ - { - "name": "FirstName", - "type": "Edm.String" - }, - { - "name": "LastName", - "type": "Edm.String" - } - ] - }, - { - "name": "PublishDate", - "type": "Edm.DateTimeOffset" - } - ], - "suggesters": [ - { - "name": "sg", - "sourceFields": [ - "Title" - ] - } - ] -} diff --git a/sdk/search/azure-search-documents/src/test/resources/HotelsDataArray.json b/sdk/search/azure-search-documents/src/test/resources/HotelsDataArray.json deleted file mode 100644 index 183f69b7c99f..000000000000 --- a/sdk/search/azure-search-documents/src/test/resources/HotelsDataArray.json +++ /dev/null @@ -1,242 +0,0 @@ -[ - { - "HotelId": "1", - "HotelName": "Fancy Stay", - "Description": "Best hotel in town if you like luxury hotels. They have an amazing infinity pool, a spa, and a really helpful concierge. The location is perfect -- right downtown, close to all the tourist attractions. We highly recommend this hotel.", - "Description_fr": "Meilleur hôtel en ville si vous aimez les hôtels de luxe. Ils ont une magnifique piscine à débordement, un spa et un concierge très utile. L'emplacement est parfait – en plein centre, à proximité de toutes les attractions touristiques. Nous recommandons fortement cet hôtel.", - "Category": "Luxury", - "Tags": [ - "pool", - "view", - "wifi", - "concierge" - ], - "ParkingIncluded": false, - "SmokingAllowed": false, - "LastRenovationDate": "2010-06-27T00:00:00Z", - "Rating": 5, - "Location": { - "type": "Point", - "coordinates": [ - -122.131577, - 47.678581 - ] - } - }, - { - "HotelId": "2", - "HotelName": "Roach Motel", - "Description": "Cheapest hotel in town. Infact, a motel.", - "Description_fr": "Hôtel le moins cher en ville. Infact, un motel.", - "Category": "Budget", - "Tags": [ - "motel", - "budget" - ], - "ParkingIncluded": true, - "SmokingAllowed": true, - "LastRenovationDate": "1982-04-28T00:00:00Z", - "Rating": 1, - "Location": { - "type": "Point", - "coordinates": [ - -122.131577, - 49.678581 - ] - } - }, - { - "HotelId": "3", - "HotelName": "EconoStay", - "Description": "Very popular hotel in town", - "Description_fr": "Hôtel le plus populaire en ville", - "Category": "Budget", - "Tags": [ - "wifi", - "budget" - ], - "ParkingIncluded": true, - "SmokingAllowed": false, - "LastRenovationDate": "1995-07-01T00:00:00Z", - "Rating": 4, - "Location": { - "type": "Point", - "coordinates": [ - -122.131577, - 49.678581 - ] - } - }, - { - "HotelId": "4", - "HotelName": "Express Rooms", - "Description": "Pretty good hotel", - "Description_fr": "Assez bon hôtel", - "Category": "Budget", - "Tags": [ - "wifi", - "budget" - ], - "ParkingIncluded": true, - "SmokingAllowed": false, - "LastRenovationDate": "1995-07-01T00:00:00Z", - "Rating": 4, - "Location": { - "type": "Point", - "coordinates": [ - -122.131577, - 48.678581 - ] - } - }, - { - "HotelId": "5", - "HotelName": "Comfy Place", - "Description": "Another good hotel", - "Description_fr": "Un autre bon hôtel", - "Category": "Budget", - "Tags": [ - "wifi", - "budget" - ], - "ParkingIncluded": true, - "SmokingAllowed": false, - "LastRenovationDate": "2012-08-12T00:00:00Z", - "Rating": 4, - "Location": { - "type": "Point", - "coordinates": [ - -122.131577, - 48.678581 - ] - } - }, - { - "HotelId": "6", - "Description": "Surprisingly expensive. Model suites have an ocean-view.", - "LastRenovationDate": null - }, - { - "HotelId": "7", - "HotelName": "Modern Stay", - "Description": "Modern architecture, very polite staff and very clean. Also very affordable.", - "Description_fr": "Architecture moderne, personnel poli et très propre. Aussi très abordable." - }, - { - "HotelId": "8", - "Description": "Has some road noise and is next to the very police station. Bathrooms had morel coverings.", - "Description_fr": "Il y a du bruit de la route et se trouve à côté de la station de police. Les salles de bain avaient des revêtements de morilles." - }, - { - "HotelId": "9", - "HotelName": "Secret Point Motel", - "Description": "The hotel is ideally located on the main commercial artery of the city in the heart of New York. A few minutes away is Time's Square and the historic centre of the city, as well as other places of interest that make New York one of America's most attractive and cosmopolitan cities.", - "Description_fr": "L'hôtel est idéalement situé sur la principale artère commerciale de la ville en plein cœur de New York. A quelques minutes se trouve la place du temps et le centre historique de la ville, ainsi que d'autres lieux d'intérêt qui font de New York l'une des villes les plus attractives et cosmopolites de l'Amérique.", - "Category": "Boutique", - "Tags": [ - "pool", - "air conditioning", - "concierge" - ], - "ParkingIncluded": false, - "LastRenovationDate": "1970-01-18T00:00:00Z", - "Rating": 4, - "Address": { - "StreetAddress": "677 5th Ave", - "City": "New York", - "StateProvince": "NY", - "PostalCode": "10022", - "Country": "USA" - }, - "Location": { - "type": "Point", - "coordinates": [ - -73.975403, - 40.760586 - ] - }, - "Rooms": [ - { - "Description": "Budget Room, 1 Queen Bed (Cityside)", - "Description_fr": "Chambre Économique, 1 grand lit (côté ville)", - "Type": "Budget Room", - "BaseRate": 9.69, - "BedOptions": "1 Queen Bed", - "SleepsCount": 2, - "SmokingAllowed": true, - "Tags": [ - "vcr/dvd" - ] - }, - { - "Description": "Budget Room, 1 King Bed (Mountain View)", - "Description_fr": "Chambre Économique, 1 très grand lit (Mountain View)", - "Type": "Budget Room", - "BaseRate": 8.09, - "BedOptions": "1 King Bed", - "SleepsCount": 2, - "SmokingAllowed": true, - "Tags": [ - "vcr/dvd", - "jacuzzi tub" - ] - } - ] - }, - { - "HotelId": "10", - "HotelName": "Countryside Hotel", - "Description": "Save up to 50% off traditional hotels. Free WiFi, great location near downtown, full kitchen, washer & dryer, 24\/7 support, bowling alley, fitness center and more.", - "Description_fr": "Économisez jusqu'à 50% sur les hôtels traditionnels. WiFi gratuit, très bien situé près du centre-ville, cuisine complète, laveuse & sécheuse, support 24\/7, bowling, centre de fitness et plus encore.", - "Category": "Budget", - "Tags": [ - "24-hour front desk service", - "coffee in lobby", - "restaurant" - ], - "ParkingIncluded": false, - "SmokingAllowed": true, - "LastRenovationDate": "1999-09-06T00:00:00Z", - "Rating": 3, - "Address": { - "StreetAddress": "6910 Fayetteville Rd", - "City": "Durham", - "StateProvince": "NC", - "PostalCode": "27713", - "Country": "USA" - }, - "Location": { - "type": "Point", - "coordinates": [ - -78.940483, - 35.904160 - ] - }, - "Rooms": [ - { - "Description": "Suite, 1 King Bed (Amenities)", - "Description_fr": "Suite, 1 très grand lit (Services)", - "Type": "Suite", - "BaseRate": 2.44, - "BedOptions": "1 King Bed", - "SleepsCount": 2, - "SmokingAllowed": true, - "Tags": [ - "coffee maker" - ] - }, - { - "Description": "Budget Room, 1 Queen Bed (Amenities)", - "Description_fr": "Chambre Économique, 1 grand lit (Services)", - "Type": "Budget Room", - "BaseRate": 7.69, - "BedOptions": "1 Queen Bed", - "SleepsCount": 2, - "SmokingAllowed": false, - "Tags": [ - "coffee maker" - ] - } - ] - } -] diff --git a/sdk/search/azure-search-documents/src/test/resources/HotelsDataArrayWithoutFr.json b/sdk/search/azure-search-documents/src/test/resources/HotelsDataArrayWithoutFr.json deleted file mode 100644 index ba703d05fbbe..000000000000 --- a/sdk/search/azure-search-documents/src/test/resources/HotelsDataArrayWithoutFr.json +++ /dev/null @@ -1,242 +0,0 @@ -[ - { - "HotelId": "1", - "HotelName": "Fancy Stay", - "Description": "Best hotel in town if you like luxury hotels. They have an amazing infinity pool, a spa, and a really helpful concierge. The location is perfect -- right downtown, close to all the tourist attractions. We highly recommend this hotel.", - "Description_fr": "", - "Category": "Luxury", - "Tags": [ - "pool", - "view", - "wifi", - "concierge" - ], - "ParkingIncluded": false, - "SmokingAllowed": false, - "LastRenovationDate": "2010-06-27T00:00:00Z", - "Rating": 5, - "Location": { - "type": "Point", - "coordinates": [ - -122.131577, - 47.678581 - ] - } - }, - { - "HotelId": "2", - "HotelName": "Roach Motel", - "Description": "Cheapest hotel in town. Infact, a motel.", - "Description_fr": "", - "Category": "Budget", - "Tags": [ - "motel", - "budget" - ], - "ParkingIncluded": true, - "SmokingAllowed": true, - "LastRenovationDate": "1982-04-28T00:00:00Z", - "Rating": 1, - "Location": { - "type": "Point", - "coordinates": [ - -122.131577, - 49.678581 - ] - } - }, - { - "HotelId": "3", - "HotelName": "EconoStay", - "Description": "Very popular hotel in town", - "Description_fr": "", - "Category": "Budget", - "Tags": [ - "wifi", - "budget" - ], - "ParkingIncluded": true, - "SmokingAllowed": false, - "LastRenovationDate": "1995-07-01T00:00:00Z", - "Rating": 4, - "Location": { - "type": "Point", - "coordinates": [ - -122.131577, - 49.678581 - ] - } - }, - { - "HotelId": "4", - "HotelName": "Express Rooms", - "Description": "Pretty good hotel", - "Description_fr": "", - "Category": "Budget", - "Tags": [ - "wifi", - "budget" - ], - "ParkingIncluded": true, - "SmokingAllowed": false, - "LastRenovationDate": "1995-07-01T00:00:00Z", - "Rating": 4, - "Location": { - "type": "Point", - "coordinates": [ - -122.131577, - 48.678581 - ] - } - }, - { - "HotelId": "5", - "HotelName": "Comfy Place", - "Description": "Another good hotel", - "Description_fr": "", - "Category": "Budget", - "Tags": [ - "wifi", - "budget" - ], - "ParkingIncluded": true, - "SmokingAllowed": false, - "LastRenovationDate": "2012-08-12T00:00:00Z", - "Rating": 4, - "Location": { - "type": "Point", - "coordinates": [ - -122.131577, - 48.678581 - ] - } - }, - { - "HotelId": "6", - "Description": "Surprisingly expensive. Model suites have an ocean-view.", - "LastRenovationDate": null - }, - { - "HotelId": "7", - "HotelName": "Modern Stay", - "Description": "Modern architecture, very polite staff and very clean. Also very affordable.", - "Description_fr": "" - }, - { - "HotelId": "8", - "Description": "Has some road noise and is next to the very police station. Bathrooms had morel coverings.", - "Description_fr": "" - }, - { - "HotelId": "9", - "HotelName": "Secret Point Motel", - "Description": "The hotel is ideally located on the main commercial artery of the city in the heart of New York. A few minutes away is Time's Square and the historic centre of the city, as well as other places of interest that make New York one of America's most attractive and cosmopolitan cities.", - "Description_fr": "", - "Category": "Boutique", - "Tags": [ - "pool", - "air conditioning", - "concierge" - ], - "ParkingIncluded": false, - "LastRenovationDate": "1970-01-18T00:00:00Z", - "Rating": 4, - "Address": { - "StreetAddress": "677 5th Ave", - "City": "New York", - "StateProvince": "NY", - "PostalCode": "10022", - "Country": "USA" - }, - "Location": { - "type": "Point", - "coordinates": [ - -73.975403, - 40.760586 - ] - }, - "Rooms": [ - { - "Description": "Budget Room, 1 Queen Bed (Cityside)", - "Description_fr": "", - "Type": "Budget Room", - "BaseRate": 9.69, - "BedOptions": "1 Queen Bed", - "SleepsCount": 2, - "SmokingAllowed": true, - "Tags": [ - "vcr/dvd" - ] - }, - { - "Description": "Budget Room, 1 King Bed (Mountain View)", - "Description_fr": "", - "Type": "Budget Room", - "BaseRate": 8.09, - "BedOptions": "1 King Bed", - "SleepsCount": 2, - "SmokingAllowed": true, - "Tags": [ - "vcr/dvd", - "jacuzzi tub" - ] - } - ] - }, - { - "HotelId": "10", - "HotelName": "Countryside Hotel", - "Description": "Save up to 50% off traditional hotels. Free WiFi, great location near downtown, full kitchen, washer & dryer, 24\/7 support, bowling alley, fitness center and more.", - "Description_fr": "", - "Category": "Budget", - "Tags": [ - "24-hour front desk service", - "coffee in lobby", - "restaurant" - ], - "ParkingIncluded": false, - "SmokingAllowed": true, - "LastRenovationDate": "1999-09-06T00:00:00Z", - "Rating": 3, - "Address": { - "StreetAddress": "6910 Fayetteville Rd", - "City": "Durham", - "StateProvince": "NC", - "PostalCode": "27713", - "Country": "USA" - }, - "Location": { - "type": "Point", - "coordinates": [ - -78.940483, - 35.904160 - ] - }, - "Rooms": [ - { - "Description": "Suite, 1 King Bed (Amenities)", - "Description_fr": "", - "Type": "Suite", - "BaseRate": 2.44, - "BedOptions": "1 King Bed", - "SleepsCount": 2, - "SmokingAllowed": true, - "Tags": [ - "coffee maker" - ] - }, - { - "Description": "Budget Room, 1 Queen Bed (Amenities)", - "Description_fr": "", - "Type": "Budget Room", - "BaseRate": 7.69, - "BedOptions": "1 Queen Bed", - "SleepsCount": 2, - "SmokingAllowed": false, - "Tags": [ - "coffee maker" - ] - } - ] - } -] diff --git a/sdk/search/azure-search-documents/src/test/resources/HotelsTestsIndexData.json b/sdk/search/azure-search-documents/src/test/resources/HotelsTestsIndexData.json deleted file mode 100644 index cde4185af1b6..000000000000 --- a/sdk/search/azure-search-documents/src/test/resources/HotelsTestsIndexData.json +++ /dev/null @@ -1,233 +0,0 @@ -{ - "name": "hotels", - "fields": [ - { - "name": "HotelId", - "type": "Edm.String", - "key": true, - "filterable": true, - "sortable": true, - "facetable": true - }, - { - "name": "HotelName", - "type": "Edm.String", - "searchable": true, - "filterable": true, - "sortable": true, - "facetable": false - }, - { - "name": "Description", - "type": "Edm.String", - "searchable": true, - "filterable": false, - "sortable": false, - "facetable": false, - "analyzer": "en.lucene" - }, - { - "name": "Description_fr", - "type": "Edm.String", - "searchable": true, - "filterable": false, - "sortable": false, - "facetable": false, - "analyzer": "fr.lucene" - }, - { - "name": "Category", - "type": "Edm.String", - "searchable": true, - "filterable": true, - "sortable": true, - "facetable": true - }, - { - "name": "Tags", - "type": "Collection(Edm.String)", - "searchable": true, - "filterable": true, - "facetable": true - }, - { - "name": "ParkingIncluded", - "type": "Edm.Boolean", - "filterable": true, - "sortable": true, - "facetable": true - }, - { - "name": "SmokingAllowed", - "type": "Edm.Boolean", - "filterable": true, - "sortable": true, - "facetable": true - }, - { - "name": "LastRenovationDate", - "type": "Edm.DateTimeOffset", - "filterable": true, - "sortable": true, - "facetable": true - }, - { - "name": "Rating", - "type": "Edm.Int32", - "filterable": true, - "sortable": true, - "facetable": true - }, - { - "name": "Address", - "type": "Edm.ComplexType", - "fields": [ - { - "name": "StreetAddress", - "type": "Edm.String", - "searchable": true - }, - { - "name": "City", - "type": "Edm.String", - "searchable": true, - "filterable": true, - "sortable": true, - "facetable": true - }, - { - "name": "StateProvince", - "type": "Edm.String", - "searchable": true, - "filterable": true, - "sortable": true, - "facetable": true - }, - { - "name": "PostalCode", - "type": "Edm.String", - "searchable": true, - "filterable": true, - "sortable": true, - "facetable": true - }, - { - "name": "Country", - "type": "Edm.String", - "searchable": true, - "filterable": true, - "sortable": true, - "facetable": true - } - ] - }, - { - "name": "Location", - "type": "Edm.GeographyPoint", - "filterable": true, - "sortable": true - }, - { - "name": "Rooms", - "type": "Collection(Edm.ComplexType)", - "fields": [ - { - "name": "Description", - "type": "Edm.String", - "searchable": true, - "filterable": false, - "sortable": false, - "facetable": false, - "analyzer": "en.lucene" - }, - { - "name": "Description_fr", - "type": "Edm.String", - "searchable": true, - "filterable": false, - "sortable": false, - "facetable": false, - "analyzer": "fr.lucene" - }, - { - "name": "Type", - "type": "Edm.String", - "searchable": true, - "filterable": false, - "facetable": false - }, - { - "name": "BaseRate", - "type": "Edm.Double", - "filterable": true, - "facetable": true - }, - { - "name": "BedOptions", - "type": "Edm.String", - "searchable": true, - "filterable": true, - "facetable": true - }, - { - "name": "SleepsCount", - "type": "Edm.Int32", - "filterable": true, - "facetable": true - }, - { - "name": "SmokingAllowed", - "type": "Edm.Boolean", - "filterable": true, - "facetable": true - }, - { - "name": "Tags", - "type": "Collection(Edm.String)", - "searchable": true, - "filterable": true, - "facetable": true - } - ] - } - ], - "suggesters": [ - { - "name": "sg", - "sourceFields": [ - "Description", "HotelName" - ] - } - ], - "scoringProfiles": - [ - { - "name": "nearest", - "functions": [ - { - "type": "distance", - "fieldName": "Location", - "boost": 2.0, - "distance": { - "referencePointParameter": "myloc", - "boostingDistance": 100.0 - } - } - ], - "functionAggregation": "sum" - }, - { - "name": "text", - "functions": [ - { - "type": "tag", - "boost": 2, - "fieldName":"Tags", - "tag": { - "tagsParameter" : "mytag" - } - } - ] - } - ] -} diff --git a/sdk/search/azure-search-documents/src/test/resources/SmallHotelsDataArray.json b/sdk/search/azure-search-documents/src/test/resources/SmallHotelsDataArray.json deleted file mode 100644 index c7ab7ee5d79d..000000000000 --- a/sdk/search/azure-search-documents/src/test/resources/SmallHotelsDataArray.json +++ /dev/null @@ -1,82 +0,0 @@ -[ - { - "HotelId": "1", - "HotelName": "Fancy Stay", - "Description": "Best hotel in town if you like luxury hotels. They have an amazing infinity pool, a spa, and a really helpful concierge. The location is perfect -- right downtown, close to all the tourist attractions. We highly recommend this hotel.", - "Description_fr": "Meilleur hôtel en ville si vous aimez les hôtels de luxe. Ils ont une magnifique piscine à débordement, un spa et un concierge très utile. L'emplacement est parfait – en plein centre, à proximité de toutes les attractions touristiques. Nous recommandons fortement cet hôtel.", - "Category": "Luxury", - "Tags": [ - "pool", - "view", - "wifi", - "concierge" - ], - "ParkingIncluded": false, - "SmokingAllowed": false, - "LastRenovationDate": "2010-06-27T00:00:00Z", - "Rating": 5, - "Location": { - "type": "Point", - "coordinates": [ - -122.131577, - 47.678581 - ] - } - }, - { - "HotelId": "2", - "HotelName": "Secret Point Motel", - "Description": "The hotel is ideally located on the main commercial artery of the city in the heart of New York. A few minutes away is Time's Square and the historic centre of the city, as well as other places of interest that make New York one of America's most attractive and cosmopolitan cities.", - "Description_fr": "L'hôtel est idéalement situé sur la principale artère commerciale de la ville en plein cœur de New York. A quelques minutes se trouve la place du temps et le centre historique de la ville, ainsi que d'autres lieux d'intérêt qui font de New York l'une des villes les plus attractives et cosmopolites de l'Amérique.", - "Category": "Boutique", - "Tags": [ - "pool", - "air conditioning", - "concierge" - ], - "ParkingIncluded": false, - "LastRenovationDate": "1970-01-18T00:00:00Z", - "Rating": 4, - "Address": { - "StreetAddress": "677 5th Ave", - "City": "New York", - "StateProvince": "NY", - "PostalCode": "10022", - "Country": "USA" - }, - "Location": { - "type": "Point", - "coordinates": [ - -73.975403, - 40.760586 - ] - }, - "Rooms": [ - { - "Description": "Budget Room, 1 Queen Bed (Cityside)", - "Description_fr": "Chambre Économique, 1 grand lit (côté ville)", - "Type": "Budget Room", - "BaseRate": 9.69, - "BedOptions": "1 Queen Bed", - "SleepsCount": 2, - "SmokingAllowed": true, - "Tags": [ - "vcr/dvd" - ] - }, - { - "Description": "Budget Room, 1 King Bed (Mountain View)", - "Description_fr": "Chambre Économique, 1 très grand lit (Mountain View)", - "Type": "Budget Room", - "BaseRate": 8.09, - "BedOptions": "1 King Bed", - "SleepsCount": 2, - "SmokingAllowed": true, - "Tags": [ - "vcr/dvd", - "jacuzzi tub" - ] - } - ] - } -] diff --git a/sdk/search/azure-search-documents/src/test/resources/VectorSearchEmbeddings.json b/sdk/search/azure-search-documents/src/test/resources/VectorSearchEmbeddings.json deleted file mode 100644 index 88898b452b9f..000000000000 --- a/sdk/search/azure-search-documents/src/test/resources/VectorSearchEmbeddings.json +++ /dev/null @@ -1,18458 +0,0 @@ -{ - "HOTEL1_VECTORIZE_DESCRIPTION": [ - -0.009445918, - -0.030015873, - 0.035673045, - 0.014168876, - -0.007413142, - -0.023268789, - 0.003706571, - 0.041347515, - 0.029254664, - -0.007486668, - -0.024358703, - 0.018044123, - -0.005380367, - -0.03529244, - 0.022230776, - 0.019653045, - -0.0483714, - -0.00083257287, - 0.016936911, - 0.011072137, - -0.020898659, - 0.015699945, - -0.0075904694, - -0.014220777, - 0.008481431, - 0.020915959, - -0.041520517, - -0.004528331, - 0.00765967, - 0.027022935, - 0.015803747, - -0.01050123, - 0.03129609, - -0.007006587, - -0.0100427745, - 0.019635744, - 0.015630744, - 0.021971272, - 0.023095787, - -0.0072141895, - 0.022628682, - 0.03466963, - -0.015379891, - -0.015423141, - 0.010864535, - -0.008131101, - -0.010605032, - 0.023545593, - 0.0123264035, - 0.010821285, - -0.018805334, - -0.008472781, - 0.0017862472, - -0.011418141, - -0.025119912, - 0.023113087, - 0.0029129237, - -0.033251014, - 0.014151576, - -0.018580431, - 0.013373066, - 0.026330927, - -0.0036871084, - 0.008485756, - -0.025154512, - 0.010544481, - -0.0022706531, - 0.01291461, - -0.0042839656, - -0.0022274028, - 0.02096786, - 0.009177764, - -0.023683995, - -0.00040655505, - -0.008533331, - 0.005458218, - -0.014333228, - -0.013762321, - -0.013442267, - 0.007806722, - -0.0008368979, - -0.01285406, - -0.009575669, - 0.02899516, - -0.00520304, - -0.0034254426, - -0.0009569181, - 7.832402E-05, - 0.02010285, - 0.049617015, - 0.021417666, - 0.0030102374, - 0.0070541627, - 0.013632569, - -0.007006587, - -0.0159681, - 0.013399016, - 0.0044504805, - -0.011184589, - 0.025552418, - 0.018857235, - -0.0049392115, - 0.026434729, - -0.0008006756, - 0.014904135, - -0.03454853, - 0.016919611, - -0.016746609, - 0.029202763, - 0.008529006, - -0.02646933, - -0.0063232286, - -0.026884533, - 0.008066225, - -0.023891596, - -0.009740021, - -0.03626125, - 0.004727284, - -0.032749306, - 0.01620165, - 0.022299977, - -0.0072098644, - 0.019877948, - 0.004072038, - -0.02899516, - -0.022144275, - -0.013165464, - -0.00039249862, - -0.014558131, - -0.011790097, - -0.012153401, - -0.0010293628, - -0.04186652, - -0.0048094597, - 0.035050236, - 0.012975161, - -0.026763432, - 0.0072877156, - -0.001752728, - -0.020587256, - 0.0030426753, - -0.016296802, - 0.005687446, - -0.00044007422, - 0.014160226, - -0.036745656, - -0.0042839656, - 0.03404682, - -0.014194827, - 0.029202763, - -0.015578844, - -0.0019484367, - 0.02816475, - -0.0076856203, - 0.0067341086, - -0.0046278075, - -0.006530831, - -0.000783916, - 0.0145321805, - 0.017326165, - -0.029150862, - 0.0029691495, - -0.005869098, - 0.0023679668, - 0.008689033, - -0.00765102, - -0.021348465, - -0.0013083287, - -0.014385128, - -0.00012373709, - 0.01684176, - 0.017871123, - -0.011677645, - 0.049444016, - 0.02657313, - 0.009999524, - -0.0020327752, - 0.00886636, - 0.0053414414, - -0.004305591, - 0.0066389577, - -0.0241857, - 0.050862633, - -0.013329816, - 0.0031378265, - 0.015137688, - -0.0031140386, - 0.017836522, - 0.0052722404, - 0.023666695, - -0.011963098, - 0.006115626, - -0.024635507, - -0.01932434, - -0.003505456, - 0.02249028, - -0.021988573, - 0.004584557, - 0.0089442115, - -0.011980399, - 0.0006925492, - 0.004645108, - 0.017516468, - 0.006288628, - 0.019168638, - -0.019168638, - 0.0017429966, - 0.021088962, - -0.012464805, - -0.011625744, - -0.029704468, - 0.0019268114, - 0.014618682, - 0.016469805, - -0.003838485, - -0.009895723, - -0.0075428938, - -0.0043293787, - -0.007828347, - 0.001448893, - 0.013130863, - 0.006755734, - 0.019462742, - -0.018199826, - -0.03788747, - 0.013926673, - 0.008926911, - 0.00035357315, - -0.009938974, - 0.023839695, - 0.0040136497, - -0.0051943897, - 0.011833347, - -0.03357972, - 0.023614794, - 0.0027096462, - -0.005306841, - 0.01365852, - -0.0077634715, - -0.016980162, - -0.015146338, - -0.0161757, - -0.013442267, - -0.019428141, - -0.001046663, - -0.009195064, - 0.022628682, - 0.0403095, - 0.014566781, - 0.0027399214, - -0.022594081, - -0.0008666326, - -0.002007906, - -0.033908423, - 0.006699508, - 0.010959686, - -0.017750021, - 0.021486867, - -0.013987224, - 0.003927149, - -0.018234426, - 0.008490081, - 0.002163608, - 0.0017397528, - -0.0046148323, - -0.0039833747, - -0.023251489, - 0.0063837795, - -0.004182327, - -0.024254901, - -0.017429966, - -0.023130387, - 0.020431554, - -0.03688406, - 0.013848822, - 0.0021463078, - -0.007888898, - -0.03357972, - 0.007849973, - -0.00029950996, - 0.0063102534, - -0.046952784, - 0.0320054, - 0.0241857, - -0.0072012143, - -2.9481324E-05, - -0.003135664, - -0.026330927, - -0.011392192, - 0.01927244, - 0.0050905882, - 0.005397667, - -0.018130625, - -0.006349179, - -0.0242203, - 0.026019523, - 0.016608207, - -0.019601144, - 0.027524643, - -0.0067341086, - 0.016391953, - 0.009195064, - 0.01127109, - -0.005959924, - -0.017352115, - 0.009419967, - 0.01766352, - 0.017274264, - 0.0050473376, - -0.008221927, - 0.0025561068, - -0.00682061, - 0.008139751, - -0.0011861459, - -0.020587256, - -0.025483217, - -0.019774146, - 0.012707008, - -0.05307706, - 0.0015353941, - 0.027022935, - 0.018199826, - 0.0033065036, - 0.0120669, - 0.0048051346, - -0.032645505, - 0.0006665989, - 0.018857235, - -0.020033648, - -0.011919848, - 0.051969845, - 0.029462267, - 0.02250758, - 0.0036092573, - -0.045464966, - -0.0032740657, - -0.017957624, - 0.0069892867, - 0.008468456, - -0.0013321165, - 0.007560194, - -0.022732483, - 0.009774622, - 0.01285406, - 0.014142926, - -0.007183914, - -0.025742719, - 0.010985636, - 0.022126975, - 0.0063232286, - 0.0055101183, - -0.0040547377, - -0.01283676, - 0.016270852, - 0.00322649, - -0.016417904, - 0.0011958773, - -0.004536981, - -0.04158972, - -0.02333799, - -0.01524149, - -0.034323625, - -0.0058301724, - 0.01039743, - 0.013632569, - 0.023753196, - -0.038441077, - 0.0039898623, - 0.016668757, - 0.016971512, - -0.014350528, - -0.014341878, - 0.021763671, - -0.010293628, - -0.00072714966, - 0.028493455, - 0.018718833, - 0.0009163708, - 0.007404492, - -0.01928974, - 0.007573169, - 0.009506468, - -0.017602969, - -0.043042935, - 0.036745656, - -0.01683311, - -0.0019722246, - -0.02100246, - -0.017326165, - 0.00521169, - 0.010778034, - -0.029271964, - 0.003382192, - 0.00081256946, - 0.007871598, - 0.005730696, - 0.0036049322, - -0.0075818193, - 0.022005873, - -0.012559956, - 0.02562162, - -0.03463503, - 0.0077029206, - -0.03626125, - 0.016331403, - -0.040447902, - -0.023493692, - -0.039098486, - -0.005380367, - 0.0019873623, - 0.0319881, - -0.0022749782, - -0.0071190386, - 0.0009082613, - 0.0028285852, - 0.03934069, - -0.00724879, - -0.0054365927, - -0.0004089879, - 0.010302278, - 0.012499405, - 0.02505071, - -0.012499405, - 0.00073039345, - 0.008027299, - 0.0011569519, - 0.016236251, - -0.018666932, - -0.018078724, - -0.025189113, - -0.0043531666, - -0.00561392, - 0.01613245, - 0.005492818, - -0.040171098, - 0.03458313, - 0.0027766845, - 0.0009617838, - 0.014783034, - -0.0040136497, - -0.0161411, - -0.03795667, - -0.002240378, - -0.0007147151, - 0.028510755, - 0.020223951, - 0.029566068, - 0.032766607, - 0.01291461, - 0.00054765993, - -0.012655107, - 0.010103325, - -0.004722959, - 0.01284541, - -0.019895248, - 0.011340291, - -0.0029258989, - -0.0071060634, - 0.009947624, - -0.010700183, - 0.014757084, - 0.010310928, - 0.011582494, - -0.01286271, - 0.033458617, - -0.028735656, - 0.0029280614, - 0.018891836, - -0.0063318787, - 0.029669868, - -0.035569243, - -0.014073725, - 0.029116262, - 0.00603345, - 0.01681581, - -0.038406476, - 0.0069676614, - 0.029583368, - 0.013148163, - -0.026244426, - 0.000515222, - -0.011729546, - -0.006336204, - -0.007132014, - -0.0017332652, - -0.64827365, - -0.020691058, - -0.009990874, - -0.009861123, - -0.00967947, - -0.0051684394, - 0.012378304, - -0.04266233, - 0.084217444, - -0.0056744707, - 0.01856313, - -0.030292677, - -0.005453893, - 0.03460043, - -0.018891836, - 0.032057296, - -0.013442267, - -0.0029604994, - 0.030725181, - -0.0049478617, - -0.005955599, - 0.0047402587, - -0.0056614955, - -0.028441554, - -0.0022274028, - 0.014004524, - 0.004043925, - -0.017767321, - -0.006898461, - -0.010103325, - 0.005077613, - 0.02567352, - 0.0029691495, - -0.0056441952, - -0.036538053, - -0.0072271647, - 0.022922784, - -0.0014770059, - 0.018995635, - 0.009869773, - 0.013009761, - -0.0135633685, - -0.072314896, - 0.00058171974, - 0.0052765654, - -0.013900722, - -0.026106024, - 0.023182288, - 0.0015689132, - -0.0051814145, - -0.009835172, - 0.02252488, - -0.008550631, - 0.023770496, - 0.008909611, - 0.015518293, - 0.0015808071, - 0.0067470837, - -0.02020665, - -0.007573169, - -0.01291461, - -0.018390128, - -0.0010536913, - 0.007884573, - 0.021348465, - -0.009169114, - 0.034929134, - -0.011322991, - -0.016193, - -0.013269265, - -0.007067138, - -0.002117114, - 0.010034124, - 0.024029998, - 0.01703206, - 0.0094891675, - 0.007932149, - 0.009731371, - 0.00010380129, - 0.003468693, - 0.019860648, - 0.018372828, - 0.027092136, - 0.023926197, - 0.012490755, - -0.010812635, - 0.014082375, - -0.007720221, - 0.21673709, - 0.0068076346, - 0.0021409015, - 0.16552846, - -0.013416316, - -0.018286327, - 0.022005873, - 0.024600906, - -0.01127109, - 0.0028739981, - 0.0040742005, - 0.0027723594, - -0.012430204, - 0.027645744, - 0.022715183, - 0.033406716, - 0.026832633, - -0.011418141, - 0.023130387, - -0.0063837795, - -0.010025474, - 0.01611515, - -0.007841323, - -0.035015635, - 3.2049324E-05, - 0.019601144, - 0.034271725, - -0.031849697, - 0.0007433686, - -0.02904706, - -0.0014045612, - -0.013502818, - 0.012412904, - -0.023268789, - 0.01851123, - -0.0002438249, - -0.009073962, - 0.007867273, - -0.036849458, - 0.011824697, - 0.010916436, - -0.0070411875, - 0.027974447, - -0.03541354, - -0.0067946594, - 0.011028887, - -0.018372828, - -0.012378304, - 0.005856123, - 0.0049305614, - 0.010847235, - 0.006336204, - 0.024029998, - 0.019497342, - -0.030898184, - 0.011963098, - 0.0042839656, - 0.027836045, - 0.031797796, - 0.029150862, - 0.008883661, - -0.0240992, - 0.0402057, - -0.013442267, - 0.015604794, - -0.023234189, - 0.008265178, - -0.010553131, - 0.002380942, - -0.0067903344, - 0.007015237, - 0.0024847435, - 0.012508055, - 0.016340053, - 0.021088962, - 0.0018597731, - -0.0008931236, - -0.0026534204, - -0.011418141, - 0.0013504981, - 0.04262773, - 0.0037779345, - 0.014065075, - 0.011470042, - -0.0026988336, - 0.0016067575, - -0.00062118587, - -4.1527273E-05, - 0.023043886, - -0.026711531, - -0.0006038856, - -0.021902071, - -0.0024285177, - -0.023701295, - -0.011859298, - -0.009264265, - -0.004128264, - 0.018113324, - 0.0040201372, - -0.017784622, - 0.013312516, - 0.014592731, - -0.0021203577, - 0.0014597056, - -0.008472781, - -0.036572654, - -0.011971748, - 0.0070282123, - 0.0160892, - -0.006029125, - -0.0037714469, - 0.026417429, - 0.0077807717, - 0.003090251, - 0.01127974, - 0.00885771, - -0.010786684, - 0.00842088, - 0.005717721, - 0.0055274186, - 0.008442505, - 0.009065312, - -0.018874535, - -0.006894136, - -0.019774146, - -0.0013991549, - 0.014238077, - -0.0123264035, - -0.0029604994, - 0.0058431476, - -0.008745259, - 0.0055879694, - 0.0074477424, - 0.022715183, - -0.0013591482, - 0.014653282, - -0.006046425, - 0.009151814, - -0.015933499, - 0.012369654, - -0.022230776, - -0.016616857, - -0.0051251887, - -0.0061415765, - 0.010233077, - -0.019756846, - -0.019774146, - -0.015129038, - 0.02498151, - -0.0050473376, - 0.009246965, - 0.006180502, - 0.007988375, - 0.022144275, - 0.019722246, - 0.0050949133, - 0.0074520675, - -0.01928974, - -0.0046105073, - -0.013027062, - -0.0087322835, - 0.012611857, - -0.01051853, - 0.022213476, - 0.009091263, - -0.018632332, - 0.010146576, - -0.008256528, - -0.01930704, - -0.02984287, - -0.018666932, - 0.01844203, - -0.04657218, - 0.021417666, - -0.03127879, - -0.039790496, - 0.02731704, - -0.011677645, - -0.09016872, - 0.028060948, - 0.0043531666, - -0.008304103, - -0.028891359, - 0.014696533, - 0.0028134475, - 0.016495755, - 0.0240992, - -0.004327216, - 0.013364416, - 0.025535118, - 0.011504643, - 0.008468456, - 0.0077807717, - -0.003533569, - 0.0026036825, - -0.009004761, - -0.0085938815, - 0.0021019762, - 0.030742481, - 0.012153401, - -0.016028648, - 0.01047528, - -0.009082613, - -0.006708158, - -0.01691096, - -0.024843108, - 0.011694945, - 0.017516468, - -0.0038428102, - 0.008433855, - -0.012767559, - 0.018320927, - 0.023043886, - 0.0033194788, - -0.012447504, - 0.007914849, - 0.0027031587, - -0.002417705, - 0.0064962306, - 0.0039422866, - -0.030344578, - 0.01609785, - 0.0028999485, - 0.0146705825, - -0.018822635, - -0.021538768, - -0.00040628473, - 0.020518055, - 0.011504643, - 0.018217126, - 0.0056744707, - 0.00042358495, - -0.002244703, - -0.0067427587, - 0.004223415, - 0.007547219, - -0.001970062, - 0.023268789, - 0.010959686, - -0.005882073, - 0.0005136001, - -0.008827435, - 0.02020665, - -0.018857235, - -0.006708158, - -0.024843108, - -0.014999286, - -0.0007887817, - 0.003693596, - 0.001736509, - 0.0024977184, - -0.009030712, - 0.023735896, - -0.01595945, - -0.013243315, - 0.0044504805, - 0.013537418, - -0.018649632, - 0.014341878, - -0.017750021, - 0.028233951, - -0.030898184, - -0.016279502, - -0.011989049, - -0.01292326, - 0.025915721, - 0.009774622, - 0.022715183, - 0.012516705, - -0.04677978, - 0.01050123, - -0.013243315, - -0.01844203, - 0.004597532, - -0.026313627, - 0.016642807, - 0.0053457664, - 0.017300215, - 0.009835172, - 0.0483368, - -0.023476392, - -0.005004087, - 0.013087613, - -0.0069763116, - 0.026261726, - -0.03070788, - -0.009073962, - -0.014973336, - 0.0075126183, - 0.020656457, - -0.023441792, - -0.030379178, - 0.0053457664, - -0.0072704153, - -0.01527609, - 0.0018997799, - -0.0020446691, - 0.007958099, - -0.0017040712, - -0.009117213, - -0.00043034286, - -0.017905723, - -0.0030686257, - 0.0031010634, - 0.030846283, - 0.008714983, - -0.0075255935, - 0.02082946, - -0.002445818, - 0.00039574242, - 0.0025388065, - -0.009964923, - -0.029150862, - -0.015051187, - 0.021556068, - 0.024635507, - 0.008048925, - 0.0028047974, - 0.016443854, - 0.012655107, - -0.0013677982, - 0.012663757, - -0.0012488592, - 0.0107347835, - 0.026971035, - -0.004536981, - 0.004121776, - 0.015864298, - -0.004649433, - -0.0033605667, - 0.02565622, - -0.005484168, - 0.025742719, - -0.0011342453, - 0.0043661417, - 0.022126975, - -0.0038190226, - -0.0068076346, - -0.008628482, - -0.020639157, - 0.013874772, - -0.0095583685, - 0.02494691, - 0.010172526, - -0.020293152, - -0.041797318, - 0.007802397, - -0.022092374, - 0.005159789, - -0.013727721, - 0.004895961, - -0.001613245, - -0.0042515276, - -0.02103706, - 0.007261765, - 0.008706333, - -0.0036265575, - -0.0018446355, - 0.011054837, - -0.010276328, - 0.0023895921, - 0.01286271, - -0.014540831, - 0.004011487, - 0.0065524564, - -0.008537656, - 0.019030236, - 0.00482676, - 0.017334815, - -0.016244901, - 0.017135862, - -0.024773907, - -0.002417705, - 0.0033605667, - 0.00044548055, - 0.014713833, - 0.010795334, - 0.016936911, - -0.0081786765, - 3.5377587E-05, - 0.0048570354, - -0.024497105, - -0.013796922, - -0.0061372514, - 0.0063708043, - -0.006587057, - -0.0024198676, - -0.006223752, - -0.007871598, - 0.0022101025, - 0.005700421, - 0.012802159, - -0.009731371, - 0.0058258474, - 0.029202763, - -0.007166614, - -0.009298866, - -0.013900722, - 0.016487105, - 0.029098962, - 0.017499167, - -0.025241014, - 0.039721295, - 0.02010285, - -0.009463218, - 0.0023917546, - -0.01534529, - -0.009186414, - 0.018891836, - -0.009056662, - -0.017222364, - 0.018424729, - 0.0241511, - -0.016253551, - 0.058993734, - 0.0049219113, - -0.01937624, - 0.011409491, - -0.022905484, - 0.0012412905, - 0.028891359, - -0.013528768, - -0.009324816, - 0.013390366, - 0.13639489, - -0.0242203, - 0.0321957, - -0.0070930882, - 0.0070455126, - -0.011504643, - -0.022801684, - 0.0077115707, - -0.005319816, - 0.003111876, - 0.0044634556, - 0.0074607176, - -0.012646457, - 0.005683121, - 0.014333228, - -0.029704468, - 0.019082136, - 0.004731609, - -0.00040304093, - 0.013805572, - -0.015068487, - 0.0010012499, - -0.006189152, - -0.010648282, - 0.009740021, - 0.024289502, - 0.021538768, - -0.024825808, - -0.0021841521, - 0.022248076, - -0.008074875, - 0.035673045, - -0.0013775296, - 0.0052765654, - -0.020898659, - -0.00766832, - -0.0057523213, - -0.00076769706, - 0.013520118, - -0.015673995, - 0.015942149, - 0.004173677, - 0.02731704, - 0.0045586065, - 0.0037930722, - -0.0017700283, - -0.0070368624, - -0.008892311, - 0.021331165, - -0.003706571, - 0.019116737, - 0.035084836, - -0.028649155, - 0.01700611, - -0.00563987, - -0.008667408, - -0.00885771, - -0.04158972, - -0.00043169444, - 0.0004292616, - -0.0077115707, - -0.00019462741, - -0.021953972, - -0.00140348, - -0.00966217, - 0.002159283, - -0.04594937, - -0.011963098, - -0.003103226, - -0.022594081, - 0.011037537, - -0.043492742, - -0.0120669, - 0.028510755, - 0.011089438, - -0.00015570193, - 0.007728871, - 0.01685041, - -0.01364122, - -0.020691058, - 0.0015775634, - 0.039928894, - 0.05238505, - -0.000825004, - -0.0005487412, - -0.011132688, - 0.004485081, - -0.026901834, - -0.009964923, - 0.032541703, - -0.010155226, - 0.015630744, - -0.010613682, - -0.009800572, - 0.039790496, - -0.008425205, - 0.035603844, - -0.008598207, - -0.013918023, - 0.017222364, - -0.0040504127, - -0.029341165, - -0.011046187, - 0.002171177, - -0.00024747418, - 0.029566068, - 0.0030426753, - -4.954383E-06, - -0.013433617, - -0.023995398, - -0.010388779, - 0.00023936469, - -0.019255139, - -0.018684233, - 0.024722008, - -0.0030707882, - 0.030967385, - -0.030984685, - 0.012473455, - -0.0021365765, - -0.0070238872, - -0.011919848, - -0.008810135, - 0.008952862, - -0.0012650782, - 0.012698358, - -0.0032524404, - 0.0028545354, - 0.0028675105, - -0.019601144, - -0.013009761, - 0.014212127, - -0.0020295314, - 0.020448854, - -0.0018619356, - -0.015500993, - -0.00032978534, - 0.009480517, - 0.0039249863, - -0.008356004, - 0.01679851, - -0.0010131438, - 0.018597731, - 0.01207555, - -0.0058344975, - 0.0028523728, - -0.03295691, - 0.01597675, - -0.010605032, - 0.022905484, - 0.06331879, - 0.031105787, - -0.039652094, - 0.01845933, - 0.0067816842, - 0.003922824, - -0.012482105, - 0.0027009961, - 0.03288771, - -0.023562893, - 0.009982224, - -0.0063967546, - 0.0032762282, - -0.025189113, - -0.0005876667, - -0.01699746, - 0.012611857, - -0.0051814145, - 0.004085013, - -0.02255948, - -0.0005487412, - 0.01686771, - 0.0034816682, - -0.0062453775, - 0.020033648, - -0.0009390773, - -0.014774384, - -0.023735896, - -0.014627332, - -0.0045542815, - -0.029462267, - 0.0037779345, - 0.0025431316, - -0.029237363, - 0.02982557, - 0.005985874, - -0.02894326, - -0.012508055, - 0.0023398541, - 0.018805334, - -0.00071687764, - -0.01768947, - -0.009307516, - -0.0007974318, - 0.024808507, - 0.014073725, - -0.04774859, - -0.0006271328, - 0.004753234, - 0.0032113525, - 0.005696096, - -0.00026815332, - -0.01051853, - 0.0069200858, - 0.004480756, - 0.021832872, - -0.024860408, - -0.03622665, - -0.0042363903, - 0.0034016548, - 0.009039362, - 0.0048051346, - 0.0077634715, - 0.0020511567, - 0.042420126, - -0.017161813, - -0.012594556, - 0.03143449, - -0.012637807, - 0.005739346, - 0.0034622054, - 0.027490042, - 0.011098088, - -0.0038730856, - 0.001986281, - -0.030811682, - 0.0096275695, - 0.03539624, - -0.024722008, - -0.014783034, - -0.010985636, - -0.0049262363, - 0.03465233, - -0.013104913, - -0.006275653, - -0.019168638, - 0.017179113, - 0.014212127, - 0.01528474, - 0.0012704845, - -0.01601135, - 0.00443318, - -0.0066389577, - -0.02250758, - 0.020708358, - 0.015059837, - 0.010068725, - 0.013373066, - -0.011072137, - -0.0025928698, - 0.011426792, - -0.00484406, - -0.048406, - 0.042939134, - -0.008217602, - -0.032039996, - -0.00362007, - 0.0077115707, - -0.022784384, - -0.0014099675, - -0.021365765, - -0.009610269, - 0.015673995, - -0.0013667169, - 0.00762507, - 0.009307516, - -0.024445204, - 0.006098326, - 0.021279264, - -0.0029431991, - -0.0020533192, - -0.020535355, - -0.0113575915, - -0.0001406994, - 0.035638444, - -0.013027062, - -0.0067816842, - 0.0028999485, - -0.0055749943, - 0.009099913, - 0.019635744, - 0.0045542815, - -0.00093529286, - -0.003784422, - -0.003377867, - 0.0019376241, - -0.019116737, - 0.005683121, - 0.016573606, - 0.008074875, - 0.022282677, - -0.0048656855, - 0.015924849, - -0.010224427, - 0.032610904, - 0.02249028, - -0.021556068, - -0.008273828, - 0.022991985, - 0.017239664, - -0.024410604, - -0.005553369, - 0.016625507, - -0.018891836, - -0.014160226, - -0.0109423855, - 0.018978335, - -0.0014661932, - 0.0037930722, - -0.000964487, - -0.00029248177, - 0.012975161, - -0.009411317, - -0.010622332, - 0.023407191, - 0.015397191, - -0.017352115, - -0.0013386041, - -0.01761162, - 7.649939E-05, - -0.0018846422, - 0.01765487, - -0.012594556, - 0.016063249, - 0.0029950996, - 0.015483692, - -0.026227126, - 0.0011407329, - 0.009714071, - -0.01930704, - -0.008399255, - 0.004173677, - 0.009913024, - 0.0135633685, - 0.02570812, - -0.006405405, - -0.010293628, - -0.014592731, - -0.010319578, - 0.0020262876, - -0.022645982, - -0.0053544166, - 0.022005873, - 0.011712246, - -0.019012935, - 0.003739009, - 0.0016792021, - 0.0008217602, - -0.0036308826, - -0.0161411, - 0.0027615468, - -0.014981986, - 0.021590669, - 0.011617094, - -0.019255139, - 0.02577732, - 0.024064599, - -0.001567832, - 0.024791207, - -0.015622094, - -0.014748434, - -0.018199826, - 0.0042515276, - -0.008005675, - -0.007573169, - -8.433855E-05, - -0.0012045274, - 0.025984922, - 0.009740021, - -0.014990636, - -0.002906436, - -0.038095072, - -0.011617094, - -0.005877748, - 0.012681058, - -0.030292677, - -0.0021246825, - 0.039133087, - -0.023545593, - -0.043215938, - 0.0039249863, - 0.033372115, - 0.021988573, - -0.04598397, - -0.012663757, - 0.005389017, - -0.01448893, - -0.0049521867, - -0.0323687, - 0.009342116, - -0.012291803, - -0.0037498216, - 0.0020511567, - -0.016400604, - 0.007499643, - 0.01849393, - 0.012023649, - 0.0029583368, - 0.011521943, - 0.042385526, - -0.016019998, - 0.012802159, - 0.00403095, - 0.0027334339, - -0.0049262363, - 0.017300215, - 0.011573844, - 0.026071424, - -0.010207127, - -0.008836085, - -0.024877708, - 0.0070325374, - -0.0242203, - 0.034790732, - -0.018044123, - 0.0058215223, - 0.0001747592, - 0.024497105, - 0.0045499564, - -0.02652123, - 0.005553369, - 0.027213238, - 0.01288866, - -0.011054837, - -0.012784859, - 0.010933735, - -0.011132688, - 0.007746171, - 0.020742958, - 0.0049781366, - -0.018251726, - 0.004206115, - 0.0030361877, - -0.01124514, - -0.0060723755, - 0.0017808409, - 0.028770257, - 0.020068249, - 0.016080549, - -0.0065567815, - -0.009852473, - 0.016193, - -0.0036438578, - 0.026936434, - 0.0033173163, - 4.5176537E-05, - 0.014618682, - 0.012213952, - -0.01767217, - -0.006366479, - 0.0015894573, - -0.006297278, - -0.0082478775, - 0.0026101698, - 0.011089438, - 0.0319708, - 0.015077137, - 0.02167717, - -0.043215938, - 0.015734546, - 0.009757321, - -0.0002461226, - 0.0039206613, - 0.02169447, - -0.038510278, - -0.004822435, - 0.016651457, - 0.00963622, - 0.02252488, - -0.006522181, - 0.009324816, - -0.015777797, - 0.0109423855, - -0.0023376916, - -0.036157448, - 0.015094438, - 0.018269027, - 0.01847663, - -0.006535156, - 0.0026772083, - 0.009938974, - 0.021434966, - -0.019774146, - -0.00320919, - -0.0015224189, - -0.0006168608, - -0.0040612253, - -0.00422774, - 0.011729546, - 0.0028912984, - 0.034479327, - 0.006764384, - 0.018943734, - -0.018666932, - 0.0075385687, - 0.007374217, - -0.009835172, - 0.0047445837, - 0.013770971, - 0.010890486, - 0.0047402587, - 0.025587019, - 0.024704708, - -0.0162103, - 0.0031594518, - 0.008213277, - 0.0068681855, - -0.037368465, - -0.02986017, - -0.015639395, - 0.015950799, - 0.0120842, - 0.0031572892, - 0.0028588604, - -0.027524643, - 0.01616705, - -0.04273153, - 0.0034838307, - 0.023822395, - 0.0016381141, - 0.0006325391, - 0.02498151, - -0.0036092573, - -0.00966217, - 0.003948774, - -0.038198873, - 0.02738624, - 0.01599405, - 0.02567352, - 0.018839935, - 0.004848385, - 0.0052808905, - 0.002651258, - 0.0012856222, - 0.0109423855, - 0.011418141, - -0.031659395, - 0.0029777994, - 0.0012088525 - ], - "HOTEL2_VECTORIZE_DESCRIPTION": [ - -0.030168112, - -0.0051525193, - 0.0054855207, - 0.0024885093, - 0.007146027, - -0.011835044, - 0.016722063, - 0.03483013, - -0.002125133, - -0.013671051, - -0.009477035, - 0.021996083, - 0.01067404, - 0.010953041, - 0.027396103, - -0.0065565244, - -0.0267481, - -0.0025515095, - -0.0010215038, - -0.0057240212, - -0.019566074, - 0.014832055, - -0.026172098, - -0.008725532, - 0.020682078, - 0.0051885196, - -0.012393046, - -0.016506061, - -0.022680085, - -0.012888048, - 0.0063270237, - -0.018756071, - 0.019764073, - -0.0020621328, - -0.00077062787, - 0.021042079, - -0.0083115315, - 0.020106075, - 0.0036540136, - -0.009513035, - 0.009252035, - -0.009414035, - -0.015480058, - -0.007146027, - -0.010269038, - -0.01861207, - 0.0025245096, - 0.025830097, - 0.0003366575, - -0.0019147572, - -0.047052175, - -0.034308128, - 0.026244098, - 0.005094019, - -0.025146093, - 0.020214075, - 0.023652088, - -0.027432103, - 0.036486138, - -0.0141390525, - 0.004261516, - 0.052200194, - 0.025092093, - -0.012726048, - 0.021780081, - 0.017793067, - 0.012996049, - 0.017622067, - -0.014832055, - 0.019422073, - 0.0015783809, - -0.031230116, - -0.041148152, - -0.0031567619, - -0.007231527, - 0.0075690285, - -0.014544055, - -0.008797533, - -0.0016515062, - 0.017019063, - -0.00083925313, - -0.008784032, - 0.006363024, - 0.014499054, - 0.0067500253, - -0.016290061, - -0.025668096, - -0.0008285656, - 0.017802067, - 0.01076404, - 0.00036281385, - -0.0016458812, - -0.0073350277, - -0.008779533, - 0.005652021, - -0.010089038, - -0.0051255194, - -0.039204147, - 0.033372127, - -0.0019428823, - 0.011007041, - -0.005103019, - 0.010134038, - 0.0073530274, - -1.7701239E-05, - -0.01076404, - 0.01073704, - -0.01068304, - -0.005053519, - 0.011097042, - 0.014409054, - -0.0077850292, - -0.0078030294, - 0.033624128, - -0.010521039, - -0.003937515, - -0.032742124, - 0.026532099, - -0.03477613, - 0.007222527, - 0.024480091, - -0.024300091, - 0.010377039, - 0.014328053, - -0.005634021, - -0.015282057, - -0.024318092, - -0.00789303, - -0.0099090375, - -0.027288102, - 0.025812097, - 0.008739033, - -0.010890041, - 0.01590306, - 0.0017966317, - -0.00802803, - -0.0054405206, - 0.012816048, - 0.018126069, - 0.0029317609, - 0.012915049, - 0.012690048, - -0.0036022635, - 0.009567035, - 0.015336057, - 0.0008566907, - 0.0025470096, - 0.019548073, - 0.0065385243, - 0.022500085, - 0.01631706, - -0.009378036, - 0.02363409, - -0.0017606316, - -0.012483046, - -0.009765036, - -0.028314106, - -0.03220212, - 0.014040053, - 0.018000068, - -0.016308062, - -0.042084157, - -0.0022488835, - 0.02152808, - -0.008527532, - 0.009243035, - -0.017649066, - -0.033336125, - -0.010017037, - -0.01062904, - 0.018243069, - 0.034146126, - -0.01074604, - 0.028872108, - 0.014265053, - 0.004833018, - -0.01601106, - -0.011961045, - -0.008860533, - 0.01632606, - 0.0126000475, - -0.010845041, - 0.036666136, - 0.0109440405, - 0.021762082, - -0.014535055, - 0.017046064, - 0.011961045, - 0.012492047, - -0.0018236318, - -0.029106108, - -0.011187042, - -0.055440206, - -0.007776029, - 0.008266531, - 0.0042390157, - -0.016560063, - 0.0065610246, - 0.02160008, - -0.020700077, - -0.010890041, - -0.0033817627, - 0.0014163803, - 0.01888207, - -0.0116460435, - -0.019620074, - -0.019278072, - 0.017109064, - -0.013725052, - -0.0032287622, - -0.020484077, - 0.009693036, - 0.030060112, - 0.011799044, - -0.011268042, - -0.015129057, - -0.02381409, - 0.022392083, - -0.010494039, - 0.014787056, - -0.0052110194, - 0.00071044016, - 0.022140082, - -0.022428084, - -0.0018157568, - 0.022716084, - -0.03241812, - 0.00013507082, - 0.009396035, - 0.004599017, - -0.009891037, - -0.022050083, - -0.00089269085, - -0.007227027, - 0.024948094, - 0.03137412, - 0.0065340246, - 0.001878757, - -0.014418054, - 0.007528528, - -0.01069204, - -0.01610106, - -0.011043041, - -0.019926075, - -0.0118980445, - -0.0060255225, - 0.02921411, - 0.014949056, - 0.0073890276, - -0.007236027, - -0.0072540273, - 0.03459613, - 0.01638006, - -0.015129057, - -0.0018236318, - 0.030744115, - -0.017766066, - 0.013626051, - 0.018387068, - 0.011763044, - -0.047808178, - -0.006889526, - 0.023292087, - 0.0009911287, - -0.002115008, - -0.009783037, - 0.0046800175, - 0.017622067, - -0.009112534, - -0.011592044, - -0.023742089, - -0.006106523, - 0.024606092, - 0.0028777607, - 0.025326096, - -0.0062955236, - -0.022248084, - -0.00050231436, - -0.010926041, - 0.0035167632, - 0.004815018, - -0.033732127, - 0.03780014, - 0.0044730166, - -0.00060975226, - -0.009360035, - 0.019926075, - -0.005782522, - -0.019170072, - 0.0041782656, - -0.033138122, - 0.020052075, - -0.024390092, - 0.0020610078, - 0.017244065, - -0.022554085, - 0.025956098, - -0.031338118, - 0.030852115, - -0.0070830267, - 0.021096079, - 0.017676067, - 0.013023049, - 0.0018056318, - -0.004243516, - 0.02403009, - 0.0049365186, - 0.013005049, - -0.022122083, - -0.009882037, - -0.009157535, - -0.0024840094, - 0.004779018, - 0.0019361322, - -0.012681047, - 0.0076365285, - -0.017847067, - 0.022302084, - -0.0267481, - -0.0016458812, - 0.02921411, - 0.011295042, - 0.014751055, - -0.021816082, - -0.018468069, - -0.016344061, - 0.008334031, - 0.0025785097, - -0.016344061, - 0.031518117, - 0.03411013, - 0.0266581, - 0.0015052556, - 0.023544088, - -0.018396068, - 0.01866607, - 0.00060806476, - 0.02433609, - 0.0062325234, - 0.0040455153, - 0.005098519, - 0.011943045, - -0.005094019, - -0.004509017, - -0.0047250176, - 0.003165762, - -0.028746108, - 0.0011013792, - 0.0148410555, - 0.012456046, - 0.01574106, - -0.0037980143, - -0.0007042526, - -0.0054765204, - 0.0020058826, - 0.017838066, - -0.0003228762, - 0.01332905, - -0.015498058, - 0.00020461014, - -0.030312113, - -0.036036134, - 0.010575039, - -0.016686063, - 0.009045034, - 0.012069046, - -0.019278072, - 0.0005861272, - 0.02950211, - 0.0155700585, - 0.00065531494, - -0.027918104, - -0.0071190265, - -0.010485039, - 0.0269641, - -0.0094590355, - -0.012339046, - 0.015156057, - 0.01902607, - -0.023094086, - 0.010053038, - -0.017145064, - -0.012960048, - -0.019206071, - 0.012024045, - -0.017703066, - -0.0040770154, - -0.0089550335, - -0.023796089, - -0.009819036, - -0.0013556301, - 0.0019766325, - -0.02921411, - -0.011493043, - -0.0055530206, - -0.0036832637, - 0.0044077663, - -0.013869052, - 0.016497063, - 0.007393528, - 0.007632029, - -0.0028102605, - -0.0059355223, - -0.020772077, - -0.020736078, - -0.012699047, - -0.022032082, - -0.011556043, - 0.0038992646, - -0.0002953136, - 0.038952146, - -0.0022657586, - -0.011853044, - 0.018153068, - -0.025056094, - 0.017397065, - -0.009018034, - -0.025380095, - -0.025308095, - 0.017208064, - -0.002940761, - 0.0070830267, - 0.016569061, - 0.019548073, - 0.019242072, - 0.016362062, - 0.007128027, - -0.008545532, - -0.011124042, - -0.03240012, - -0.019872075, - -0.014994056, - -0.02134808, - 0.012717048, - -0.016902063, - 0.011709044, - -0.02901611, - 0.0031702619, - 0.035748135, - -0.024516093, - -0.023040086, - -0.0012352546, - -0.022968085, - 0.0040747654, - -0.0029250109, - 0.0070830267, - 0.035478134, - 0.0057420214, - 0.016623063, - -0.006358524, - -0.0148410555, - -0.006979526, - -0.01063804, - -0.009549036, - 0.0116730435, - -0.030312113, - 0.05119219, - 0.003480763, - -0.0076455288, - -0.01619106, - 0.020412076, - 0.0138600515, - 0.016749064, - 0.00097594113, - 0.02984411, - -0.03711614, - -0.0025627597, - 0.0017808817, - -0.0033997628, - 0.0123480465, - -0.0141120525, - -0.0114210425, - 0.030366113, - 0.008973033, - 0.0123480465, - -0.0060165226, - -0.0145890545, - -0.0052695195, - -0.006979526, - -0.0051885196, - -0.0022230083, - 0.0049905186, - 0.014634055, - -0.017460065, - -0.019278072, - -0.6145943, - -0.020286076, - 0.019674074, - -0.006331524, - -0.01567806, - 0.008469032, - 0.009747037, - -0.0023220086, - 0.08863233, - -0.0048420182, - 0.02136608, - 0.0010513164, - 0.008365531, - 0.0035482633, - -0.004203016, - 0.014409054, - 0.013806052, - -0.0052875197, - 0.0071685268, - -0.0034020126, - 0.01644306, - -0.012654047, - 0.0036607636, - -0.022284083, - -0.006678025, - 0.01336505, - 0.0073485277, - -0.02368809, - -0.038736146, - -0.004185016, - -0.0037665141, - 0.024912093, - 0.02386809, - -0.0057420214, - 0.005886022, - -0.009153035, - 0.012510046, - 0.013266049, - 0.0012993799, - -0.023310088, - 0.011727043, - -0.007258527, - -0.025794096, - 0.015723059, - -0.0022736336, - 0.0131040495, - -0.0071640266, - 0.01870207, - 0.028854107, - -0.016713062, - -0.007159527, - 0.015156057, - 0.0033165123, - 0.03999615, - 0.024318092, - -0.010134038, - -0.006691525, - 0.012384047, - -0.0030217613, - -0.013230049, - -0.005859022, - -0.028188106, - -0.018918071, - 0.01622706, - 0.00065868994, - 0.022986086, - 0.04258816, - 0.01330205, - -0.00814053, - 0.014166053, - -0.003705764, - 0.027504103, - 0.0057870215, - 0.035604134, - 0.0050040185, - 0.0057510217, - -0.007038026, - 0.0050220187, - -0.017298065, - 0.0006035648, - 0.023544088, - 0.0062640235, - 0.01597506, - -0.0070650266, - -0.039780147, - 0.013995052, - 0.03454213, - -0.059400223, - 0.23875289, - -0.028746108, - 0.0016346311, - 0.20203276, - -0.021564081, - -0.016938064, - 0.004527017, - 0.02932211, - -0.03513613, - -0.0009793162, - -0.022212083, - -0.0008026905, - 0.0062055234, - -0.004097265, - -0.0032782622, - 0.01330205, - -0.024588091, - -0.01059304, - 0.0018922571, - -0.011088042, - -0.016902063, - -0.016506061, - -0.0038925146, - -0.03277812, - -0.013077049, - -0.0028642607, - 0.029808111, - -0.023436088, - 0.009189035, - -0.01584906, - 0.02129408, - 0.0061920234, - 0.013113049, - -0.054648206, - 0.0042052655, - -0.004864518, - -0.01606506, - -0.0052875197, - -0.004286266, - 0.012051045, - -0.01575006, - -0.006997526, - 0.0038565143, - -0.027288102, - -0.009297035, - 0.005089519, - -0.02401209, - -0.019908074, - -0.0009174409, - 0.012951048, - 0.009342035, - 0.008586032, - 0.038916145, - 0.01055704, - 0.008572532, - 0.021096079, - -0.011754044, - -0.004245766, - 0.047304176, - 0.017793067, - 0.0073125274, - -0.01608306, - -0.009396035, - -0.0010260039, - 0.005976022, - -0.011727043, - -0.0039060146, - -0.009702036, - -0.004333516, - 0.011061042, - -0.01585806, - 0.00792903, - -0.0029092608, - 0.014904056, - 0.012231045, - 0.014373054, - -0.0017392565, - 0.015777059, - 0.004617017, - 0.008320531, - 0.015219057, - -0.0033097623, - 0.015273057, - 0.011547043, - 0.00531002, - -0.01334705, - 0.0054765204, - 0.023166087, - 0.010134038, - -0.019458072, - 0.016236061, - -0.04514417, - -0.02386809, - -0.0082260305, - -0.013293049, - -0.025650095, - -0.023832088, - 0.055800207, - -0.010080038, - -0.03173412, - -0.009288034, - 3.8144673E-05, - 0.0058500217, - 0.014328053, - -0.0023062585, - -0.03988815, - 0.0025020093, - 0.009081034, - 0.015948059, - 0.0008319406, - 0.02111408, - 0.0057195215, - 0.010872041, - 0.009216035, - 0.017919067, - 0.015336057, - -0.009171034, - 0.008230531, - 0.016290061, - 0.0034110127, - -0.0007436278, - 0.00539552, - -0.0012600047, - 0.00265726, - -0.017775066, - 0.009342035, - 0.03267012, - -0.0044302666, - 0.017370066, - 0.01843207, - -0.0030915115, - -0.0058365217, - -0.012465047, - 0.019314073, - 0.017550066, - 0.013734051, - -0.021852082, - 0.00803253, - -0.016425062, - 0.0268381, - -0.02170808, - -0.012078045, - 0.020124076, - -0.030024113, - 0.007492528, - 0.009954037, - 0.0044122664, - -0.010107038, - 0.025776096, - 0.03220212, - -0.0056745214, - -0.019980075, - -0.0028125106, - 0.013536051, - -0.010998041, - 0.002387259, - -0.013653051, - -0.00267526, - 0.011484043, - -0.01866607, - -0.0005653146, - 0.0050355187, - -0.0068715257, - 0.005913022, - 0.010125038, - 0.013644051, - 0.0024930094, - 0.0017662566, - 0.026478099, - -0.0008319406, - -0.009747037, - -0.01593006, - -0.016812064, - 0.02147408, - -0.039348148, - -0.017172065, - 0.028656106, - -0.020484077, - -0.09460835, - 0.035910133, - 0.024876093, - 0.010188038, - -0.036270134, - 0.008217031, - -0.012564047, - 0.0065520247, - 0.027288102, - -0.014760056, - 0.0033187624, - -0.0035010132, - 0.046188172, - 0.0042075156, - -0.005859022, - -0.016308062, - -0.015192057, - -0.013023049, - -0.002900261, - 0.00792003, - 0.0099090375, - -0.023184087, - -0.00029728236, - -0.0038182642, - 0.0054495204, - -0.0006508149, - -0.013005049, - -0.008320531, - 0.0057375217, - -0.006673525, - -0.005607021, - 0.015255057, - -0.025470095, - -0.001332005, - 0.004482017, - -0.010242038, - 0.0001245239, - -0.018261068, - 0.02152808, - -0.00081112806, - -0.008685033, - 0.022104083, - -0.03267012, - 0.007528528, - 0.032976124, - -0.008203531, - -0.018198067, - 0.013707051, - -0.01055704, - 0.027936105, - 0.018405069, - 0.028584108, - -0.005548521, - -0.023184087, - -0.009999038, - 0.0076995287, - -0.01868407, - 0.00803253, - -0.0113940425, - 0.025794096, - 0.008185531, - -0.0020463828, - -0.009702036, - -0.01343705, - 0.038700145, - 0.006345024, - -0.0035752633, - -0.01071004, - 0.0025605096, - -0.009216035, - -0.0052740197, - 0.0035235132, - -0.003705764, - 0.013779052, - 0.014454054, - -0.01584906, - 0.027648104, - -0.013725052, - 0.005049019, - -0.012816048, - -0.020016074, - -0.00540002, - 0.020934079, - 0.0019293822, - 0.0027720104, - 0.017127065, - -0.01616406, - 0.004243516, - -0.0118710445, - 0.019044071, - 0.03519013, - -0.030312113, - 0.017361065, - -0.0010648165, - -0.011466043, - -0.0020362576, - -0.011718044, - 0.032616124, - 0.02376009, - -0.011331042, - -0.01080004, - 0.007852529, - 0.011700043, - -0.0062595233, - -0.010935041, - -0.016812064, - 0.04309216, - 0.0010873165, - -0.01868407, - 0.006480024, - 0.011223042, - -0.0008060655, - 0.019278072, - -0.018180069, - 0.013914052, - -0.009189035, - -0.019188073, - 0.00787503, - 0.007542028, - 0.005926522, - 0.012438047, - -0.025056094, - -0.018468069, - -0.010296038, - -0.015660059, - 0.021024078, - -0.021672081, - -0.011907045, - 0.038916145, - -0.009450035, - 0.010989041, - 0.0077850292, - 0.015435058, - 0.0013545051, - 0.016551062, - -0.011961045, - 0.031302117, - -0.004468517, - 0.009279035, - 0.0067635253, - 0.00093262846, - 0.026586099, - 0.0150930565, - 0.025722096, - -0.0270361, - -0.0036292635, - 0.036792137, - -0.028296106, - 0.0029700112, - 0.02435409, - 0.011709044, - 0.013185049, - 0.027324103, - 0.004581017, - -0.004362766, - -0.040824153, - 0.0018843821, - 0.023310088, - -0.0014557554, - -0.0070740264, - -0.035604134, - -0.0070335264, - 0.008212531, - 0.010881041, - 0.0034942632, - 0.008433032, - -0.027018102, - -0.014265053, - 0.01573206, - -0.03207612, - 0.002427759, - -0.014058053, - 0.022176083, - 0.01062004, - 0.017703066, - -0.021618081, - 0.019314073, - 0.014517054, - -0.0057555214, - 0.012213046, - -0.009855037, - -0.02388609, - -0.006151523, - 0.011583043, - -0.00814053, - 0.0014962556, - 0.012303046, - -0.01053004, - 0.004565267, - 0.03992415, - 0.0011790044, - -0.025884097, - -0.0051255194, - -0.0054990207, - -0.021636082, - -0.023490088, - -0.007560028, - 0.02124008, - 0.025812097, - 0.012861048, - -0.012618047, - -0.012726048, - 0.012870048, - 0.007011026, - -0.010539039, - -0.011637043, - -0.02138408, - 0.01343705, - 0.011097042, - 0.002439009, - 0.004869018, - -0.0011373792, - -0.01346405, - -0.008428532, - -0.012690048, - 0.032238122, - 0.023166087, - 0.021960082, - 0.016722063, - -0.011124042, - 0.022356084, - 0.0145890545, - -0.01870207, - -0.020790078, - 0.023364088, - -0.00529202, - 0.01644306, - -0.0054630204, - -0.035442133, - 0.0065025245, - 0.01605606, - 0.008680533, - -0.020088075, - -0.017631065, - 0.029736111, - -0.0265501, - 0.044928167, - 0.0034132628, - -0.010989041, - 0.041832156, - -0.0003256887, - -0.009513035, - 0.02160008, - 0.025146093, - -0.0009556911, - 0.016758062, - 0.15062456, - -0.016920064, - 0.04784418, - -0.020070076, - 0.012114045, - -0.008239531, - 0.0052695195, - 0.018918071, - 0.016002059, - -0.0014006302, - -0.018810071, - -0.00038925145, - -0.0047835177, - -0.019620074, - 0.011844045, - 0.009711036, - -0.003719264, - -0.018108068, - -0.011160042, - 0.0060300226, - 0.00792453, - -0.022158083, - -0.030798115, - 0.013986052, - 0.017199064, - 0.015633058, - 0.01591206, - -0.00063168985, - -0.0009961912, - -0.005854522, - -0.03708014, - 0.008397032, - -0.024300091, - -0.020232076, - -0.017208064, - 0.02415609, - -0.004214266, - -0.009270035, - -0.014022052, - -0.012321047, - -0.0076095285, - -0.0072855274, - 0.004581017, - 0.0064260243, - -0.0037980143, - 0.007186527, - -0.007825529, - -0.0096570365, - 0.015228057, - -0.011097042, - 0.025722096, - 0.046188172, - -0.01626306, - 0.01080004, - 0.009630036, - 0.0014917556, - 0.00092362845, - -0.030276114, - 0.011376043, - -0.011547043, - -0.0019665074, - -0.0106650395, - -0.03204012, - 0.007560028, - -0.015183057, - 0.00026915726, - -0.033894125, - 0.006165023, - -0.01601106, - -0.0014771306, - 0.0035257633, - -0.019152071, - 0.0268201, - 0.024588091, - 0.036810137, - 0.0033345125, - 0.005620521, - -0.00023104774, - -0.010836041, - 0.0076365285, - 0.006417024, - 0.016461061, - 0.041472156, - 0.029934112, - -0.014706055, - 0.017154064, - -0.024822094, - -0.025596095, - 0.025128094, - 0.018189069, - -0.014697055, - 0.006363024, - 0.011151042, - -0.0054900204, - 0.022662085, - -0.014553054, - 0.011691044, - 0.011430043, - -0.004797018, - 0.03207612, - -0.0006997526, - 0.011844045, - -0.010782041, - -0.037728142, - 0.008541032, - 0.029934112, - 0.007780529, - 0.016659062, - -0.022356084, - -0.022122083, - 0.0065385243, - 0.00267526, - -0.015192057, - -0.0266221, - 0.014508055, - 0.020250076, - 0.009369035, - -0.03465013, - 0.014229054, - -0.01628106, - -0.0068580257, - 0.012807048, - -0.0036585138, - -0.019962074, - -0.010224038, - 0.03540613, - -0.000263251, - 0.023706088, - 0.024822094, - -0.019098071, - -0.015597058, - 0.008352031, - 0.015426057, - 0.006939026, - 0.025524095, - 0.0032287622, - 0.027288102, - 0.040968154, - -0.009585036, - 0.0031747618, - 0.034398127, - -0.004171516, - 0.006759025, - -0.022968085, - -0.029988112, - -0.013122049, - 0.004986019, - 0.01897207, - 0.041724157, - -0.0029812611, - 0.06552024, - 0.015498058, - -0.00801453, - 0.029772112, - -0.009576036, - 0.020556077, - -0.0020632576, - -0.011007041, - 0.010539039, - 0.0031567619, - 0.0015322558, - -0.0062505235, - -0.0143370535, - 0.008761533, - -0.0024592592, - -0.0025717595, - -0.0039262646, - 0.0040432652, - -0.0019980075, - 0.032688122, - 0.027288102, - -0.011313043, - 0.0041422653, - -0.022608085, - 0.008176531, - -0.0054090205, - -0.015363057, - -0.008797533, - -0.0071190265, - 0.018918071, - -0.03425413, - -0.009486035, - -0.005143519, - -0.041508157, - 0.043776162, - 0.003195012, - -0.022464084, - 0.0041962657, - -0.035964135, - -0.024264092, - 0.0008808783, - 0.016416062, - -0.029700112, - -0.0068130256, - 0.012582047, - 0.015399057, - -0.013851052, - -0.0077265287, - 0.015642058, - 0.00532802, - -0.0010226289, - -0.025110094, - -0.0057645217, - -0.00805053, - 0.011682044, - 0.0007779404, - 0.013716051, - -0.028314106, - 0.010899041, - -0.016704062, - 0.00027056353, - -0.008856033, - 0.019818075, - -0.014382054, - 0.0043380163, - -0.013158049, - -0.015237057, - 0.021096079, - 0.0046800175, - 0.0071820267, - 0.0052110194, - -0.00132638, - 0.024192091, - 0.0060390225, - 0.018324068, - -0.040716153, - 0.006385524, - -0.014823056, - 0.00017071939, - -0.0012026295, - -0.0035167632, - -0.0053010196, - 0.0076050283, - -0.018414069, - -0.008482532, - -0.010926041, - 0.008874034, - 0.009486035, - 0.03207612, - 0.0025582595, - 0.0005017519, - -0.002891261, - -0.030258114, - 0.00037209515, - 0.022878086, - 0.027828105, - 0.033642124, - 0.036288135, - -0.020556077, - 0.004909518, - 0.017316066, - -0.022320084, - -0.015246057, - -0.0057780216, - -0.0030892615, - 0.0072675273, - 0.004882518, - -0.010224038, - -0.0013668801, - 0.0057555214, - -0.02919611, - -0.012798048, - 0.03479413, - -0.0060165226, - 0.02446209, - -0.006943526, - -0.011907045, - -0.009216035, - 0.02131208, - 0.0044482667, - -0.00065193995, - 0.012051045, - 0.0007211277, - -0.012915049, - 0.045900173, - -0.02440809, - 0.0070155263, - 0.03267012, - -0.0013972552, - 0.0062775235, - -0.00037097014, - -0.018414069, - -0.009810037, - 0.04233616, - 0.01861207, - -0.0014670055, - -0.01585806, - 0.03227412, - 0.017514065, - 0.0094050355, - 0.040500153, - -0.015408058, - 0.009216035, - 0.02428209, - 0.03794414, - 0.004560767, - 0.006448524, - 0.0150930565, - 0.00803703, - 0.004617017, - -0.042192157, - 0.014526054, - 0.0035235132, - 0.009855037, - -0.024390092, - 0.010368039, - 0.011025041, - -0.019620074, - 0.010251039, - 0.007798529, - -0.01890007, - 0.01061104, - -0.014706055, - 0.010107038, - 0.035586134, - 0.010044037, - -0.0038070143, - -0.004878018, - -0.009747037, - -0.031752117, - 0.015579058, - 0.023454087, - -0.040968154, - 0.00076106534, - -0.015876058, - 0.01346405, - -0.016731063, - -0.050328188, - 0.00525152, - -0.03157212, - -0.027792104, - 0.0017865067, - 0.023094086, - 0.0007385653, - 0.03960015, - -0.0048915185, - -0.007006526, - -0.031014116, - 0.010080038, - 0.010107038, - -0.017604066, - -0.020718077, - 0.018198067, - 0.019494073, - -0.009270035, - -0.0026055097, - -0.02124008, - -0.0010839415, - -0.0266581, - -0.024894092, - 0.011556043, - -0.013995052, - 0.02948411, - -0.0031027617, - -0.004288516, - 0.027180102, - 0.008653533, - 0.012447046, - 0.042156156, - -0.012303046, - -0.01614606, - -0.014787056, - 0.0113940425, - -0.0070650266, - 0.012636047, - -0.0026122597, - -0.00043368913, - -0.0010468165, - -0.01059304, - 0.0068535255, - -0.012924048, - -0.028926108, - -0.021078078, - -0.0138600515, - 0.011565044, - -0.0270361, - 0.03178812, - -0.0013511301, - -0.0010125038, - -0.013761052, - -0.010323038, - 0.010323038, - 0.0014703805, - -0.03169812, - 0.019314073, - 0.012681047, - -0.004290766, - -0.004779018, - -0.032904122, - -0.0076140286, - -0.0015457558, - -0.0029970112, - -0.013878052, - -0.013014048, - -0.03173412, - 0.043272164, - 0.0035145131, - -0.01606506, - -0.014967056, - 0.019620074, - -0.021960082, - 0.019278072, - -0.014661055, - 0.0114210425, - -0.0070695262, - 0.006651025, - -0.00053156447, - 0.035442133, - -0.011583043, - -0.012051045, - -0.0062190234, - -0.019854074, - -0.031104116, - 0.010170038, - 0.023724088, - -0.0017077564, - 0.027144102, - 0.017856067, - -0.004016265, - 0.0055125207, - -0.01058404, - -0.009702036, - 0.009729036, - -0.0050085187, - -0.027252102, - -0.024876093, - -0.020538077, - -0.01913407, - 0.0057015214, - -0.0038047642, - 0.007884029, - -0.01578606, - -0.0062640235, - 0.006372024, - 0.003762014, - -0.014958056, - 0.018198067, - 0.012897048, - 0.03150012, - 0.002173508, - -0.028476106, - 0.025578097, - 0.016488062, - 0.002907011, - -0.008554532, - -0.021204079, - 0.022068083, - -0.012960048, - 0.01079104, - 0.0029857613, - 0.012789048, - -0.0072990274, - -0.0534602, - 0.019242072, - -0.0055980207, - -0.012888048, - 0.014625055, - 0.007555528, - 0.004547267, - 0.010989041, - 0.011862044, - 0.012825048, - 0.01850407, - 0.038556144, - 0.002092508, - -0.027576104, - -0.005134519, - 0.0266581, - 0.000115945746, - 0.0058050216, - -0.011052041, - -0.0074070278, - -0.007528528, - 0.033966128, - -0.022266082, - -0.035802133, - 0.0027180102, - 0.014436054, - -0.0051525193, - 0.016641062, - 0.03465013, - 0.027558103, - -0.0067860256, - 0.0051525193, - 0.007227027, - -0.011223042, - 0.013824052, - -0.00027070413, - 0.018405069, - 0.009864037, - 0.041148152, - -0.003705764, - 0.0065610246, - 0.00092025346, - 0.0017583816, - 0.010377039, - -0.032706123, - 0.027882105, - 0.007758029, - -0.027882105, - 0.01063804, - 0.016371062, - 0.007528528, - -0.025722096, - -0.008932534, - 0.0038700146, - 0.01335605, - -0.010287038, - 0.0043695164, - -0.043812163, - 0.014679055, - -0.013896052, - -0.008352031, - -0.007528528, - -0.016920064, - -0.019152071, - -0.033498127, - -0.00060581474, - 0.033336125, - 0.019224072, - -0.010404039, - 0.022734085, - 0.006664525, - -0.009378036, - 0.0045630173, - -0.0046800175, - -0.008262031, - -0.0106650395, - 0.019404072, - -0.000333845, - 0.0059355223, - -0.0026370098, - -0.004999519, - 0.016713062, - 0.03135612, - 0.01866607, - -0.006597025, - 0.004554017, - 0.02152808 - ], - "HOTEL3_VECTORIZE_DESCRIPTION": [ - -0.0026168018, - -0.024089903, - 0.03355637, - 0.003290724, - -0.011909716, - 0.0025469302, - -0.010115596, - 0.028183023, - 0.006770777, - -0.0040638186, - -0.01943781, - 0.018437069, - 0.0054094093, - -0.0012351484, - -0.0010734296, - 0.02033938, - -0.029932065, - 0.0005471392, - 0.011792512, - -0.010638504, - -0.013748915, - 0.018193645, - -0.007595712, - -0.0043816213, - 0.019131277, - 0.019744344, - -0.03768555, - -0.0026415947, - 0.008758735, - 0.0010159547, - -0.009214027, - -0.017319124, - 0.017084718, - 0.004728725, - -0.031266384, - 0.0036243042, - 0.00014720918, - 0.030563163, - -0.0011111828, - -0.0056032464, - 0.024107933, - 0.015452879, - -0.020321347, - 0.002970667, - -0.022052359, - -0.010521301, - -0.0036400815, - 0.0003454133, - 0.00380011, - 0.019600093, - -0.008871431, - -0.013721867, - 0.015606145, - -0.027209328, - -0.021926139, - 0.007059279, - 0.006468752, - -0.030977882, - 0.009754968, - -0.007794057, - 0.015515989, - 0.033358023, - 0.025604537, - -0.018896868, - -0.011233539, - -0.00041810225, - 0.0041832766, - 0.008154685, - 3.6062727E-05, - 0.012504751, - 0.01969025, - -0.0072170533, - -0.022142515, - -0.010494254, - -0.0024567733, - 0.01275719, - -0.014830797, - -0.020988507, - -0.005495058, - 0.014488201, - -0.017715815, - 0.0058647012, - -0.0054499796, - 0.03397109, - -0.0018662461, - -0.012090029, - -0.016363462, - -0.0046340604, - 0.007424414, - 0.030220566, - 0.0216737, - 0.023873527, - 0.027317517, - 0.015479926, - 0.010395082, - -0.0069060125, - -0.008100591, - -0.011026179, - 0.023278492, - 0.03436778, - 0.01574138, - 0.009953313, - -0.007199022, - -0.007365812, - -0.0014515248, - 0.008154685, - 0.0128203, - -0.0069285515, - 0.009232058, - 0.0033403102, - -0.013406319, - -0.016958497, - -0.021727793, - 0.017256016, - -0.013388287, - -0.0016352193, - -0.0011844352, - -0.0026213096, - -0.00958367, - 0.023981715, - 0.004931578, - 0.0033605956, - 0.012594908, - 0.016760152, - -0.019473873, - 0.003739254, - -0.023044083, - -0.023783369, - -0.004809866, - -0.021799918, - -0.001869627, - 0.005472519, - -0.008569405, - 0.0021615098, - 0.021908106, - -0.006797824, - -0.005468011, - 0.0054770266, - -0.005048782, - 0.007586696, - -0.01269408, - 0.0017231222, - -0.0123244375, - 0.005057798, - 0.01016969, - -0.014776703, - -0.011603183, - 0.021835981, - -0.014830797, - 0.024919344, - 0.005012719, - 0.01572335, - 0.019113246, - -0.023765337, - -0.0067797927, - -0.031699136, - 0.00042627272, - -0.030058283, - 0.020411504, - 0.025893038, - -0.025135722, - -0.022250703, - -0.0109179905, - 0.0120539665, - 0.015101267, - 0.021114727, - -0.013451397, - 0.00089198904, - -0.009745952, - -0.008488265, - 0.028471524, - 0.019365685, - 0.007843643, - 0.03606273, - 0.020249221, - 0.009511544, - -0.007000677, - -0.01254983, - -0.014136589, - -0.0049721487, - -0.01645362, - -0.016579838, - 0.03676595, - -0.018256756, - 0.020970477, - -0.004343305, - 0.00014791354, - 0.013189943, - 0.02062788, - 0.031699136, - 0.012892425, - 0.0043500667, - -0.028417429, - -0.009214027, - -0.002612294, - -0.0076498063, - 0.0056573404, - 0.012594908, - 0.011125351, - -0.03534147, - -0.008961588, - -0.0012035936, - 0.0031216799, - 0.005810607, - -0.0070773102, - -0.028507587, - -0.009101331, - 0.028183023, - -0.013784978, - -0.01559713, - -0.019275527, - -0.007852659, - 0.04204914, - 0.019365685, - -0.0037482698, - -0.0032681846, - -0.039596874, - 0.011431885, - -0.0042080698, - 0.0167872, - 0.007798565, - 0.008334998, - 0.030382847, - -0.02551438, - -0.010025438, - 0.027335547, - -0.004769296, - -0.0017817242, - -0.011197477, - 0.011368775, - -0.006383103, - -0.015101267, - 0.015840553, - -0.021331104, - 0.025856975, - 0.005639309, - 0.024757063, - 0.024180058, - -0.030256629, - -0.0075280946, - -0.015768427, - -0.004796343, - -0.00601346, - -0.012847347, - -0.012477703, - -0.011648261, - 0.028940339, - 0.033646524, - -0.0025920086, - 0.0145873735, - -0.018482149, - 0.020700006, - 0.010566379, - 0.005747497, - 0.011116336, - 0.032474488, - -0.02432431, - -0.020141033, - -0.012712112, - 0.0056032464, - -0.045366913, - -0.005179509, - 0.023585023, - -0.006775285, - 0.0020285284, - -0.0046566, - -0.026470043, - 0.006464244, - -0.0079338, - -0.01315388, - -0.002384648, - -0.018950963, - 0.02973372, - -0.01639051, - 0.022034327, - 0.006545385, - -0.010908975, - -0.008465725, - -0.0008164827, - -0.024288246, - 0.016138071, - -0.02683067, - 0.027660113, - 0.014361981, - 0.005873717, - -0.0027587987, - -0.014533279, - -0.013162896, - -0.038010117, - 0.017427314, - -0.024180058, - 0.0010672313, - -0.0189149, - -0.02856168, - 0.005292205, - 0.0074965395, - 0.023783369, - -0.018860806, - 0.010593426, - -0.008614484, - 0.0061847577, - 0.013766946, - 0.011233539, - 0.014830797, - -0.012306406, - 0.0040119784, - 0.014064464, - 0.009736937, - -0.0035792256, - 0.0149119375, - -0.013730884, - -0.023657149, - 0.012558845, - -0.0003039975, - -0.012468688, - -0.0090337135, - -0.017571565, - 0.020862289, - -0.03251055, - -0.01877065, - 0.026001226, - 0.008447694, - 0.020573786, - 0.01016969, - 0.002977429, - -0.02088032, - 0.003398912, - 0.0005860193, - -0.02353093, - 0.01743633, - 0.031536855, - 0.010719646, - 0.010990116, - 0.025334066, - -0.016336415, - 0.0038925207, - -0.00040542395, - 0.0060179676, - -0.008591945, - 0.0019090706, - 0.042806458, - -0.017634673, - 0.016273307, - -0.0037076992, - 0.0044582547, - -0.0045439037, - -0.017869081, - 0.008357537, - 0.009227551, - 0.0039894395, - 0.014722609, - -0.013839072, - -0.0067933165, - 0.020663943, - 0.013685805, - -0.021078665, - -0.0076633296, - 0.0016498698, - -0.030761506, - 0.0057655284, - -0.013830056, - -0.037901927, - 0.006035999, - -0.012676049, - 0.018950963, - 0.013514508, - -0.030040253, - 0.0076723453, - 0.0064326893, - -0.00812313, - -0.016624918, - -0.0030563162, - -0.016111024, - 0.00078380085, - -0.017986285, - 0.007117881, - 0.00618025, - -0.009935281, - 0.004480794, - -0.015984803, - 0.0119007, - -0.011233539, - -0.019059151, - -0.0430589, - -3.5428813E-05, - -0.008100591, - -0.013262068, - -0.008010433, - -0.01058441, - 0.0015721095, - -0.011864637, - -0.023603056, - -0.0063876105, - 0.010133627, - 0.0032478995, - -0.0013489714, - -0.0083936, - -0.015092252, - 0.021421261, - -0.00532376, - 0.0074379374, - -0.008041988, - 0.025712725, - -0.024396434, - -0.009277137, - -0.042698268, - -0.0372528, - -0.018175615, - 0.009096823, - 0.0067347144, - 0.0149660325, - 0.0019744344, - -0.0010463826, - 0.02050166, - 0.0113507435, - 0.024630843, - -0.013406319, - -0.02064591, - -0.015633192, - 0.013902182, - -0.0044627627, - 0.021132758, - -0.0277683, - -0.011305666, - 0.004568697, - -0.013262068, - -0.0030766015, - -0.024558717, - -0.04349165, - -0.00883086, - -0.0043387967, - -0.007280163, - -0.0026213096, - 0.01943781, - -0.02181795, - 0.01440706, - -0.011702355, - -0.0066941436, - 0.0042644176, - -0.009565638, - -0.030887727, - 0.005305729, - -0.015092252, - 0.0014571596, - 0.023476835, - 0.011188461, - 0.035611942, - 0.021998264, - 2.8420529E-05, - 0.018202662, - -0.013262068, - -0.0023981715, - -0.018301833, - -0.014578357, - 0.008235825, - 0.0077579943, - 0.041796703, - 0.004142706, - -0.011206493, - -0.0035499248, - 0.020411504, - 0.004931578, - -0.0016746629, - -0.018824743, - 0.026506105, - -0.056149665, - 0.0037775708, - 0.0114589315, - -0.000404297, - 0.00874972, - -0.007915769, - -0.008930033, - 0.02908459, - -0.0036062729, - 0.0066986517, - -0.013812025, - -0.007257624, - -0.0061306637, - 0.013081755, - -0.022557236, - -0.0073297494, - 0.004422192, - 0.0018313103, - -0.015506973, - 0.0004079596, - -0.65086013, - -0.020898351, - 0.0049676406, - 0.0028219083, - -0.0076362826, - -0.023657149, - 0.0061667264, - -0.01929356, - 0.089724064, - 0.0006395499, - 0.02749783, - -0.017066685, - 0.003344818, - 0.027948614, - -0.014271825, - 0.039055932, - -0.004314004, - 0.0040457873, - 0.0037054452, - 0.009818078, - 0.0056212777, - -0.007352289, - 0.008127637, - -0.015822522, - -0.035846353, - 0.013920213, - -7.6421995E-05, - -0.024504624, - -0.017463377, - 0.010061501, - 0.005332776, - 0.00945745, - 0.016065946, - -0.0024973438, - -0.010737677, - -0.0022888563, - 0.028219085, - -0.028453492, - 0.039669, - 0.0011297776, - 0.0029098114, - -0.0032952318, - -0.08662267, - 0.010034454, - 0.0005491114, - -0.015552051, - -0.033538338, - 0.014100526, - -0.013081755, - -0.003973662, - -0.014821781, - 0.011603183, - 0.007541618, - 0.023891557, - 0.01578646, - -0.0027971154, - 0.004316258, - 0.00454165, - -0.018464116, - -0.033376053, - -0.012576876, - 0.001388415, - 0.00086268806, - 0.0054364563, - -0.015552051, - 0.021277009, - 0.039091997, - 0.0044920635, - -0.0023080145, - -0.014686546, - -0.015813505, - -0.009872172, - 0.01826577, - 0.025802882, - 0.009096823, - 0.037757676, - -0.01064752, - 0.0015563321, - -0.019383715, - -0.032149922, - 0.030977882, - 0.0012554337, - 0.030779539, - 0.026920827, - 0.011422869, - 0.007915769, - 0.02062788, - -0.009074284, - 0.22661819, - -0.0061081247, - -0.024666905, - 0.2142126, - 0.0068158554, - -0.003746016, - 0.016579838, - 0.0070547713, - 0.0061577107, - 0.017147828, - 0.00482339, - 0.0039308374, - -0.022683457, - 0.029571436, - 0.017896129, - 0.0031690123, - 0.0019304829, - -0.0039669, - 0.007559649, - 0.0062794224, - -0.009962329, - 0.015588114, - 0.0029548898, - -0.050920572, - -0.0009381944, - -0.010331972, - 0.032835115, - -0.0286879, - 0.02895837, - -0.029679624, - 0.011684324, - -0.00037302385, - 0.02432431, - -0.03142867, - 0.007969863, - -0.01626429, - 0.007960848, - -0.0066670966, - -0.025063597, - -0.005404901, - 0.007852659, - -0.026253665, - 0.00572045, - -0.018860806, - -0.011215508, - -0.005747497, - -0.011846606, - -0.025298003, - 0.011089289, - 0.0019023089, - -0.02457675, - -0.012937504, - 0.024757063, - 0.028886246, - -0.014993079, - 0.02551438, - 0.0028579712, - 0.034403842, - 0.034349747, - 0.01931159, - 0.009209519, - -0.015633192, - 0.016904404, - 0.010097564, - 0.0022933641, - -0.011558104, - 0.013397303, - 0.0050893524, - 0.014470169, - 0.0022539205, - 0.0096287485, - -0.0017456614, - 0.008411631, - 0.0152365025, - 0.004456001, - 0.019654186, - 0.00674373, - 0.0077579943, - 0.0057159425, - 0.006491291, - 0.009709889, - -0.009745952, - 0.017328141, - 0.0026438488, - 0.0077219317, - -0.012333453, - 0.03305149, - 0.005733974, - 0.017796956, - -0.03279905, - -0.0069826455, - -0.033430148, - -0.0059368266, - -0.017562548, - -0.02538816, - -0.045547225, - -0.0109720845, - 0.047891304, - -0.011990857, - -0.014551311, - -0.003987185, - 0.01077374, - 0.013198959, - -0.0015664748, - -0.0071268966, - -0.054418657, - -0.006153203, - 0.020285284, - 0.006924044, - -0.0023147764, - 0.020718036, - 0.016588856, - 0.013902182, - 0.011927747, - -0.010025438, - 0.0020386712, - 0.017310109, - 0.003653605, - 0.013703836, - 0.0048008505, - 0.0005316435, - 0.0060855853, - -0.017778926, - -0.012099045, - -0.021962201, - -0.013956276, - 0.035503756, - 0.0076678377, - 0.008930033, - 0.011918732, - -0.009403356, - 0.016588856, - 0.005733974, - 0.010467207, - 0.0027993692, - -8.910029E-05, - -0.002377886, - -0.0008615611, - -0.036964297, - 0.012035935, - -0.009367294, - -0.014488201, - -0.0047467565, - -0.013974307, - -0.0031397112, - -0.007987894, - -0.026920827, - 0.009854141, - 0.019600093, - 0.0052336035, - 0.0067076674, - -0.010133627, - 0.008362045, - 0.036838077, - -5.9975417E-05, - 0.0061171404, - 0.023350617, - -0.002923335, - 0.0074424455, - 0.002355347, - -0.0122162495, - 0.008984127, - -0.00021637637, - -0.014001354, - -0.0008266253, - -0.0047197095, - 0.010557364, - 0.012189202, - -0.017201921, - -0.022809675, - -0.0021795412, - 0.0073567964, - -0.029463248, - 0.028760025, - -0.025676662, - -0.04006569, - 0.013983322, - -0.036261074, - -0.09578261, - 0.024107933, - 0.013974307, - -0.010404097, - -0.024180058, - 0.011305666, - 0.0028016232, - 0.0031126642, - 0.03674792, - 0.0115671195, - -0.0021457323, - 0.029643562, - 0.013757931, - 0.007947324, - -0.0030495543, - 0.0061171404, - -0.008348522, - -0.022034327, - 0.017589595, - 0.006342532, - 0.021655668, - 0.016273307, - -0.007843643, - -0.0039037904, - -0.0027024506, - -0.011828574, - -0.013478445, - 0.005697911, - 0.017364204, - 0.008713657, - -0.009024697, - 0.0042306087, - -0.024937376, - 0.0146955615, - 0.0114409, - -0.0027813378, - 0.009854141, - 0.0092500895, - 0.018464116, - 0.0017490423, - 0.0022223657, - 0.035593912, - -0.026686419, - 0.007086326, - 0.009926266, - 0.01832888, - -0.019365685, - -0.014821781, - 0.015885632, - 0.012829316, - -0.0001522805, - 0.033412118, - 0.0027452752, - -0.0009956694, - 0.015506973, - 0.003998455, - 0.009177964, - 0.010485238, - -0.0027903535, - 0.044212904, - -0.008483756, - -0.0024702968, - 0.0026821655, - 0.010782756, - 0.00035386553, - -0.006121648, - -0.0065904637, - -0.009529576, - -0.019852532, - -0.0016262037, - 0.005391378, - 0.013514508, - 0.013649742, - -0.009295168, - 0.023422742, - -0.016074961, - 0.0026190556, - 0.021060633, - 0.012594908, - -0.0048910077, - 0.009132885, - -0.004534888, - 0.02511769, - -0.0117294025, - 0.00906076, - -0.015173392, - -0.01474064, - 0.008150176, - 0.005111892, - -0.005359823, - 0.02735358, - -0.025045564, - -0.0029639055, - -0.010512285, - -0.004138198, - 0.0256406, - -0.016579838, - -0.0016566316, - -0.000516993, - 0.028579712, - -0.0096287485, - 0.021457324, - -0.0113507435, - -0.010719646, - 0.011828574, - 0.00043613362, - 0.038839556, - 0.002492836, - 0.0020634641, - -0.023062114, - 0.038839556, - 0.011332712, - -0.018554274, - -0.016552793, - 0.005693403, - -0.0063650715, - -0.024558717, - -0.011738418, - 0.0039826776, - 0.001672409, - -0.0022043341, - -0.008073543, - -0.016444603, - -0.0037189687, - 0.011720386, - 0.011071257, - 0.029805845, - 0.021457324, - 0.013054707, - -0.012017904, - -0.0015270312, - 0.0011551343, - -0.0008711403, - -0.010422128, - 0.009150917, - -0.016697044, - 0.015633192, - 0.0019981004, - 0.022178577, - 0.01672409, - 0.017878097, - 0.017472392, - -0.00482339, - 0.027750269, - 0.011927747, - 0.006319993, - 0.046088167, - -0.016065946, - 0.0035476708, - 0.01810349, - -0.008096082, - -0.015326659, - 0.035918478, - 0.003572464, - 0.011017163, - -0.025189815, - 0.006775285, - 0.017111765, - -0.014082495, - -0.027606018, - -0.01553402, - -0.03263677, - 0.015651224, - -0.016120039, - -0.004397399, - 0.018806713, - -0.016507713, - -0.024883281, - 0.024288246, - -0.0033200248, - 0.00720353, - -0.024486592, - 0.016841294, - 0.0072125457, - 0.036964297, - -0.0064507206, - 0.0038091256, - -0.0087091485, - -3.1695756E-05, - -0.012639986, - -0.0028579712, - -0.01751747, - 0.0030270151, - 0.006329009, - -5.071321E-05, - -0.0009984868, - 0.016336415, - -0.0077444706, - -0.0042576557, - 0.031771265, - 0.0238014, - -0.031825356, - 0.006865442, - -0.023566993, - -0.015678272, - -0.017319124, - 0.0064326893, - 0.042265516, - 0.026379885, - 0.011909716, - -0.02645201, - -0.01196381, - -0.025189815, - 0.008564898, - -0.005364331, - -0.011134367, - 0.0024522655, - -0.002664134, - 0.009119363, - -0.019419778, - 0.008975111, - -0.009421388, - 0.010178705, - -0.0028557172, - -0.017003575, - 0.012901441, - 0.024612812, - -0.043599837, - 0.012351484, - 0.0017794702, - 0.007586696, - 0.027515862, - -0.008141161, - -0.0143169025, - 0.019365685, - 0.021781888, - 0.0020533216, - 0.007762502, - -0.0074965395, - -0.0083936, - 0.0256406, - -0.0115671195, - -0.0008531089, - 0.011152399, - 0.021331104, - -0.028183023, - 0.029553406, - -0.0041517215, - -0.017950222, - 0.0075776805, - -0.026073352, - -0.004167499, - 0.015083236, - 0.00038654736, - -0.01058441, - 0.00229111, - 0.12953731, - -0.013397303, - 0.015678272, - -0.0167872, - 0.0053958856, - 0.0044672703, - -0.008357537, - -0.008132145, - -0.00093537703, - -0.010566379, - -0.018193645, - 0.0068068397, - 0.0067527457, - 0.0019045628, - -0.006396626, - -0.009881187, - -0.018932933, - -0.0076498063, - 0.01578646, - 0.010764725, - 0.01031394, - 0.0073342575, - -0.013830056, - 0.00515697, - 0.028435461, - 0.0039285836, - -0.0078075808, - -0.015831538, - -0.0011833083, - 0.012252312, - -0.020663943, - -0.011062242, - -0.0020206396, - 0.014884891, - -0.013442382, - 0.0065318616, - 0.00300673, - 0.0009466466, - 0.008695625, - -0.0062118047, - -0.010205752, - 0.0005195287, - 0.016967513, - 0.0050037033, - -0.012243296, - -0.015065204, - -0.0057159425, - -0.032149922, - 0.012414594, - 0.0072125457, - 0.032997396, - 0.022376923, - -0.012477703, - 0.021944169, - -0.013108801, - -0.013063723, - -0.017959239, - -0.030815601, - -0.0046250448, - -0.021637637, - -0.005959366, - -0.0095746545, - -0.042842522, - 0.020772131, - 0.00039556305, - -0.013397303, - -0.020213159, - -0.017508455, - -0.00021778507, - -0.004329781, - 0.008041988, - -0.0059909206, - 0.012775221, - 0.021944169, - 0.0020206396, - 0.0090878075, - 0.0023147764, - 0.0071854987, - -0.002549184, - -0.00057165057, - -0.00086832285, - 0.032582674, - 0.024504624, - 0.020159066, - 0.007938308, - 0.005098368, - 0.0066716047, - -0.02390959, - -0.0007832374, - 0.038551055, - -0.019329622, - 0.0020476868, - 0.016219212, - -0.0014267317, - 0.0117294025, - -0.02219661, - 0.0072666397, - 0.01699456, - -0.011035195, - 0.0274798, - 0.013325178, - 0.0026573723, - -0.0040773423, - -0.016651964, - -0.023566993, - 0.032204017, - -0.001644235, - 0.0040187403, - -0.018878838, - -0.018734587, - 0.00691052, - 0.001475191, - -0.024829188, - -0.0117294025, - 0.027029015, - -0.0013805263, - 0.02670445, - -0.0146955615, - 0.013433366, - 0.005652833, - 0.004647584, - 0.002887272, - -0.022376923, - -0.0039781695, - -0.0065138303, - 0.01996072, - -0.0016239497, - 0.0039894395, - 0.019618124, - -0.001160769, - -0.013397303, - -0.0027633065, - -0.0010430017, - 0.02102457, - 0.013397303, - 0.00674373, - 0.013397303, - 0.006991661, - 0.026776575, - -0.012522782, - 0.023026051, - 0.0006040507, - 0.008186239, - -0.016669996, - -0.0036220502, - 0.024143996, - -0.007226069, - 0.013361241, - 0.011116336, - 0.011044211, - 0.0655981, - 0.028579712, - -0.049405936, - 0.0069871536, - -0.004419938, - 0.015056189, - -0.0021299548, - 0.008866923, - 0.007280163, - -0.022809675, - 0.0044334615, - -0.017165858, - -0.02749783, - -0.023891557, - -0.00070096925, - -0.017274046, - 0.010133627, - 0.015642209, - 0.012775221, - -0.005639309, - -0.0062163128, - 0.008181731, - -0.013622696, - -0.012802268, - 0.022178577, - -0.016706059, - -0.006229836, - -0.01077374, - -0.012955535, - 0.01713881, - -0.03793799, - -0.00030005316, - -0.00266188, - -0.019113246, - 0.010728662, - 0.0018583575, - -0.031176228, - 0.005558168, - -0.020573786, - 0.0037843324, - -0.009241074, - -0.014244777, - -0.005842162, - -0.0029098114, - 0.022593299, - -0.0147496555, - -0.031356543, - -0.0064597363, - 0.009322215, - -0.012531798, - -0.029697657, - -0.013406319, - -0.013721867, - -0.012423609, - 0.012090029, - 0.0149119375, - -0.010151658, - -0.04947806, - 0.0032704386, - 0.005238111, - 0.0023057607, - 0.015047173, - 0.0024500117, - 0.00019017454, - 0.033916995, - 0.0013230513, - -0.009863156, - 0.026001226, - -0.0023125224, - -0.007888721, - -0.0067347144, - 0.047566738, - 0.023566993, - -0.013289115, - 0.009259106, - -0.011197477, - 0.0021051618, - 0.010241815, - -0.02010497, - -0.0032366298, - 0.009944297, - -0.00714042, - 0.010061501, - 0.0028962877, - -0.008700133, - -0.01824774, - 0.021781888, - 0.010494254, - 0.022034327, - 0.024017777, - 0.005129923, - -0.0025536919, - -0.008289919, - -0.012071998, - 0.0121080605, - 0.041688513, - 0.01751747, - 0.006951091, - -0.03187945, - -0.005278682, - 0.0075641572, - -0.00998036, - -0.037324924, - 0.018202662, - -0.015795475, - -0.021403229, - -0.0045844745, - -0.017192906, - -0.00469717, - -0.02551438, - -0.021457324, - -0.007839136, - 0.028633805, - -0.016579838, - 0.0033403102, - 0.007505555, - -0.023278492, - -0.017571565, - -0.016679011, - 0.002833178, - -0.011873653, - -0.0007421033, - 0.014668515, - 0.0035814797, - 0.04096726, - -0.009056252, - 0.0062253284, - 0.0045867283, - 0.0068474105, - 0.017246999, - 0.011242555, - 0.0012914964, - -0.006937567, - 0.029571436, - 0.015227486, - 0.024666905, - 0.00016749447, - 0.0031059023, - 0.013505491, - 0.01758058, - 0.030581193, - 0.0016949482, - 0.016579838, - 0.016886372, - 0.0167872, - 0.012405578, - 0.0031059023, - 0.0026821655, - 0.004963133, - 0.008483756, - -0.023332585, - 0.015308628, - -0.008884954, - -0.009791031, - -0.0042734332, - -0.02710114, - 0.011981841, - -0.01745436, - 0.0149660325, - -0.004674631, - -0.019600093, - 0.010304924, - 0.008713657, - 0.0056167697, - 0.027840426, - 0.002752037, - -0.0030134916, - 0.0092500895, - 0.0013636219, - -0.031230323, - 0.01640854, - 0.031284418, - -0.013974307, - -0.0013377018, - -0.0055987383, - 0.009430403, - -0.016679011, - -0.014325919, - 0.008952572, - -0.016814247, - -0.0046340604, - 0.009349262, - 0.003374119, - 0.006896997, - 0.037360985, - -0.0071539436, - 0.0051344307, - -0.021240946, - -0.00799691, - 0.009268121, - -0.010034454, - 1.343548E-05, - 0.020447567, - 0.02616351, - -0.022665424, - -0.0028579712, - 0.0007714043, - 0.001785105, - -0.024757063, - -0.031969607, - -0.00031132277, - -0.025802882, - 0.0027317517, - -0.0030202535, - -0.02419809, - 0.017256016, - 0.040498443, - -0.0055175973, - 0.029012464, - -0.001444763, - -0.010124611, - -0.011341728, - 0.0052606505, - 0.010386066, - -0.009754968, - 0.0043230196, - 0.003980424, - 0.0072441003, - -0.0024702968, - 0.0001800319, - 0.009890203, - -0.022539204, - -0.030436942, - -0.011287633, - -0.013198959, - -0.0053823623, - -0.005328268, - 0.012459672, - -0.013289115, - -0.021403229, - 0.005697911, - 0.006536369, - 0.027822394, - -0.030635288, - 0.012153139, - 0.012739158, - -0.011260587, - -0.010800787, - -0.02922884, - 0.0153446905, - -0.015552051, - -0.011260587, - -0.020447567, - -0.013352225, - 0.014569342, - 0.048973184, - 0.0020014814, - -0.018824743, - -0.006035999, - 0.031158198, - -0.018608367, - 0.0063380245, - -0.005806099, - -0.004000709, - -0.013595648, - 0.021240946, - 0.019906625, - 0.017427314, - -0.016769169, - 0.013180927, - -0.015525004, - 0.0005324887, - -0.050019003, - 0.017174874, - 0.010800787, - 0.005265158, - 0.03142867, - 0.010854881, - 0.002238143, - -0.00141997, - 0.009664811, - 0.0124867195, - 0.021944169, - 0.00906076, - -0.02987797, - 0.003739254, - -0.005580707, - 0.00720353, - 0.0216737, - 0.027317517, - -0.01163023, - 0.0075235865, - -0.005440964, - -0.0024838203, - 0.00092016306, - -0.019708281, - 0.022467079, - 0.008465725, - 0.0048549445, - 0.007474, - -0.027317517, - 0.016805232, - -0.008772259, - 0.01474064, - 0.011621214, - 0.011927747, - 0.031013945, - 0.0021378435, - -0.008528835, - 0.01624626, - 0.004314004, - -0.0016307115, - -0.025027532, - -0.0016555046, - -0.0034034199, - 0.02088032, - 0.016498698, - 0.014416075, - -0.01810349, - -0.0061306637, - 0.01474064, - 0.0027948613, - 0.0078751985, - 0.020141033, - -0.029300965, - -0.012784237, - 0.00368516, - 0.022701487, - 0.027155234, - -0.002131082, - 0.00133094, - -0.0163274, - -0.0023869018, - 0.00077196775, - -0.056906983, - -0.00064743863, - 0.0042847027, - 0.015416816, - -0.0030991407, - -0.009331231, - 0.01764369, - 0.024125965, - 0.01275719, - -0.02033938, - -0.0016284576, - 0.0045168567, - -0.0050803367, - -0.0019890848, - -0.0021164312, - 0.00050403294, - 0.035125095, - 0.004059311, - 0.0146414675, - 0.013099786, - 0.0008553628, - 0.026379885, - -0.020573786, - 0.019005058, - -0.0016036645, - -0.005580707, - 0.0063650715, - 0.016679011, - 0.010286893, - -0.006067554, - 0.0048278975, - 0.011125351, - 0.013812025, - -0.026884764, - -0.015056189, - -0.029643562, - 0.02152945, - -0.0010525809, - 0.013730884, - -0.02152945, - -0.03555785, - 0.011008148, - -0.046701234, - -0.008366553, - 0.037865866, - 0.0069330595, - -0.005724958, - 0.042229455, - -0.0057835598, - -0.009592686, - 0.015173392, - -0.015795475, - 0.005048782, - -0.025135722, - 0.011612198, - 0.0019631647, - 0.017274046, - 0.030743476, - -0.014055449, - 0.0052020485, - 0.0095746545, - -0.00082155404, - -0.021439292, - 0.029156715, - -0.0067256987 - ], - "HOTEL4_VECTORIZE_DESCRIPTION": [ - -0.025342932, - -0.015438392, - 0.0065736533, - -0.015209284, - -0.009367015, - -0.019544723, - 0.000929652, - 0.04948745, - 0.017861655, - 0.011948893, - -0.009851668, - -0.0019331034, - -0.0071596424, - 0.004007197, - -0.010265826, - 0.010494934, - -0.037291825, - -0.0036282865, - 0.003916875, - 0.015235719, - -0.0090233525, - 0.011587606, - 0.006586871, - -0.0071552363, - 0.0071640485, - 0.017429873, - -0.021765314, - -0.022135412, - -0.007860186, - 0.00016646169, - 0.013490969, - -0.0165575, - 0.03255104, - 0.012794832, - -0.00571009, - 0.018945515, - -0.0038419743, - 0.022276402, - 0.0054237046, - 0.007908652, - 0.022681747, - 0.009032165, - -0.016407698, - -0.013217801, - 0.00085475115, - -0.02382729, - 0.011807903, - 0.025219565, - -0.005110883, - -0.004317815, - -0.034789253, - -0.0066133067, - 0.015632253, - 0.00441034, - -0.00981642, - 0.019491851, - 0.017747102, - -0.02250551, - 0.0031039803, - -0.016945222, - 0.011878397, - 0.0077015725, - 0.017676607, - -0.010750478, - -0.02430313, - 0.00077654584, - 0.001984873, - 0.012680277, - -0.01868116, - 0.0050712298, - 0.0122925555, - -0.0051549426, - -0.016707301, - -0.0108121615, - -0.0059391987, - 0.02033779, - -0.009018946, - -0.02520194, - -0.0067058313, - 0.039935384, - -0.030489063, - -0.017324131, - 0.00035688063, - 0.030259954, - -0.008877956, - -0.020496404, - -0.015737996, - 0.01713027, - 0.0033881632, - 0.029466886, - 0.022487886, - 0.038772218, - 0.015429581, - -0.014689383, - 0.02953738, - -0.0226465, - -0.0071552363, - -0.011675725, - 0.017808784, - -0.0049654874, - 0.008287561, - 0.010688796, - -0.010468499, - 0.007058306, - 0.018469675, - -0.01438978, - 0.028109858, - -0.0024408873, - 0.004987517, - 0.0021842418, - -0.012944633, - -0.012680277, - -0.008847116, - 0.025695406, - -0.0096930545, - -0.010327509, - 0.0019154798, - 0.0108121615, - -0.021483334, - 0.014495523, - 0.01825819, - -0.011252755, - 0.014380968, - -0.010741667, - -0.02863857, - -0.0013250846, - -0.016011164, - -0.007639889, - -0.020972244, - -0.0351946, - -0.0013955795, - 0.012151565, - -0.028268471, - -0.011481863, - 0.005009547, - -0.0036150687, - -0.008785432, - -0.007375533, - -0.0007517625, - -0.015746808, - -0.0010888164, - -0.013861068, - 0.004705537, - -0.0060361293, - 0.015491263, - -0.009966223, - 0.004117345, - 0.0076487013, - -0.014592453, - 0.027915997, - 0.0026766048, - 0.0019463212, - -0.0024254667, - -0.015526511, - 0.003797915, - -0.0026479661, - -0.030876784, - -0.028938174, - 0.020126306, - 0.015579382, - -0.03732707, - -0.0007385447, - 0.006736673, - 0.0118872095, - 0.029290648, - 0.0077808793, - -0.016672054, - 0.012239684, - -0.0063533564, - -0.0032361583, - 0.027757384, - 0.026946692, - 0.011622854, - 0.04071083, - 0.008424145, - -0.0020168163, - 0.016487004, - -0.018222943, - -0.003196505, - 0.0023439568, - -0.0064899405, - 0.0009274491, - 0.034701135, - 0.009322956, - -0.006119842, - 0.015323838, - 0.0024981645, - 0.010080776, - 0.011649289, - 0.030876784, - 0.0046306364, - -0.011957704, - -0.027140552, - -0.010019094, - -0.014953739, - -0.006719049, - -0.002998238, - 0.0074900873, - 0.019773832, - -0.02906154, - -0.004586577, - -0.023844915, - -0.004590983, - 0.018839773, - -0.003599648, - -0.009419886, - 0.00839771, - 0.008512264, - -0.016169777, - 0.0012865327, - -0.025871644, - -0.0060361293, - 0.026699958, - -0.003938905, - -0.0085739475, - 0.0028330155, - -0.0015068294, - 0.010724043, - -0.012909386, - 0.010212955, - 0.004586577, - 0.015500075, - 0.019157, - -0.024585111, - -0.024514616, - 0.02751065, - -0.028814808, - -0.015500075, - -0.011243943, - -0.011614041, - -0.0034278166, - -0.003463064, - -0.0062916735, - -0.024320755, - 0.01684829, - 0.013552653, - 0.0069129104, - -0.0029740054, - -0.01260097, - 0.031458367, - -0.009305332, - -0.0040182117, - -0.013552653, - -0.024549862, - 0.0075561767, - -0.0112175075, - 0.014654136, - 0.018698784, - 0.007741226, - -0.013041564, - -0.017059775, - 0.01438978, - 0.0038089298, - -0.010160083, - 0.010195331, - 0.034806877, - -0.031299755, - 0.010336321, - -0.008988105, - -0.0011356295, - -0.036040537, - -0.009463945, - 0.0031480398, - -0.0056263776, - 0.008794244, - -0.015244531, - -0.020126306, - 0.012971069, - -0.009384639, - -0.032004703, - -0.013482157, - 0.00053146575, - 0.0226465, - -0.0052386555, - 0.028673816, - 0.021624323, - -0.010239391, - -0.007591424, - -0.002537818, - -0.0050139525, - 0.0041459836, - -0.030823912, - 0.027669264, - 0.008763403, - 0.013085623, - 0.004987517, - -0.006401822, - -0.02981936, - -0.01490968, - 0.019773832, - -0.033608463, - 0.006194743, - -0.011032458, - -0.018363932, - -0.011658101, - 0.013605524, - 0.0275459, - 0.006199149, - 0.028885303, - -0.021712441, - 0.01901601, - 0.013358791, - 0.024778971, - 0.023950657, - -0.010785726, - 0.019491851, - 0.022998974, - -0.0050932597, - 0.017095024, - 0.025466297, - -0.00076332805, - 0.023157587, - -0.0023439568, - -0.004974299, - -0.0038155387, - -0.0106359245, - -0.0029828171, - 0.019685712, - -0.04236746, - -0.01599354, - 0.023439568, - 0.01802908, - 0.004855339, - 0.005313556, - -0.002537818, - -0.021412838, - 0.029942727, - 0.002066383, - -0.006582465, - -0.006780732, - 0.027281541, - 0.014451463, - 0.004939052, - 0.017852845, - -0.012063446, - 0.018769277, - -0.015015422, - 0.026946692, - 0.011340873, - 0.014786314, - 0.018134823, - -0.017570864, - -0.008027611, - -0.00015021481, - -0.004643854, - -0.008168601, - -0.019809078, - -0.008410928, - 0.010221766, - 0.012997505, - 0.00056781474, - -0.0035732123, - -0.0045293, - 0.015808491, - 0.017544428, - -0.011851962, - -0.014680572, - -0.0044367756, - -0.038137764, - -0.01226612, - -0.02180056, - -0.008283156, - 0.011340873, - -0.011834338, - -0.005128507, - 0.01146424, - -0.027581146, - 0.01675136, - -0.0012656045, - 0.004705537, - -0.020108681, - -0.0073094442, - -0.017773537, - -0.006860039, - 0.0031105892, - 0.0007010942, - 0.015940668, - -0.009287708, - -0.009939787, - -0.0058995453, - 0.020108681, - -0.007534147, - 0.0031788812, - -0.03982964, - 0.01240711, - -0.011834338, - -0.00077213993, - -0.008684096, - 0.008869145, - -0.010468499, - -0.00665296, - -0.006066971, - -0.025448674, - -0.013059188, - -0.003998385, - -0.00893964, - 0.01424879, - -0.015729183, - 0.019033635, - 0.00043343374, - -0.0025488327, - -0.024003528, - 0.012777208, - -0.021906303, - 0.0068159797, - -0.044552803, - -0.02306947, - -0.030471439, - 0.011719784, - 0.0030114558, - 0.0040336326, - -0.02745778, - 0.0032780147, - 0.0036569252, - -0.014521958, - 0.013059188, - -0.009093847, - -0.021148482, - -0.011455428, - 0.014292849, - -0.01594948, - 0.012204437, - -0.016592747, - 0.0009665517, - 0.013825821, - -0.0037846973, - -0.017050965, - -0.027634017, - -0.021571452, - -0.030735794, - 0.0030533122, - -0.004586577, - 0.018857397, - 0.014292849, - -0.018399179, - 0.02312234, - -0.013297108, - 0.0023725955, - -0.005657219, - -0.0028814806, - 0.00055927824, - -0.03265678, - -0.010045529, - -0.01991482, - -0.0048465272, - 0.01561463, - 0.041345283, - 0.015033046, - -0.009913351, - 0.005379645, - -0.009102659, - 0.0076354835, - -0.017377002, - -0.0055602887, - -0.023316203, - -0.0024012339, - 0.03477163, - -0.01052137, - -0.0056175655, - -0.025783524, - 0.011728596, - 0.011772655, - 0.004806874, - -0.030559557, - 0.046068445, - -0.025272436, - -0.024567487, - 0.011164636, - -0.022805113, - 0.007106771, - -0.015808491, - -0.027070057, - 0.044165082, - -0.0021567047, - 0.020531652, - -0.020954622, - 0.0100984005, - -0.02217066, - 0.016575122, - -0.024937585, - -0.02306947, - 0.002590689, - 0.0101865195, - 0.00306653, - 0.013376415, - -0.6558849, - -0.012900574, - 0.005776179, - 0.004723161, - -0.025025705, - 0.0067410786, - 0.0062255845, - -0.014557205, - 0.08769571, - -0.00063941116, - 0.016249085, - -0.015403145, - 0.0019033634, - 0.012548099, - 0.0008789838, - 0.01028345, - 0.0063445447, - -0.021888679, - 0.0106183, - 0.0019110738, - -0.010442063, - -0.029132035, - 0.010221766, - 0.0046174186, - -0.0397239, - 0.031352624, - -0.003804524, - -0.016804231, - -0.031793218, - 0.0023043035, - -0.0025686594, - 0.01250404, - 0.015693936, - 0.0019242916, - -0.00087457785, - -0.02076076, - 0.0064194454, - 0.0075561767, - 0.01608166, - -0.013138494, - 0.00058819214, - 0.0039587314, - -0.08008225, - -0.012750773, - 0.0072169197, - -0.014451463, - -0.01613453, - -0.008203849, - -0.003518138, - -0.007102365, - -0.028656194, - 0.013913939, - 0.0053840512, - 0.016019976, - -0.0009951903, - 0.0075782062, - 0.0038243507, - -0.008851521, - -0.024937585, - 0.0040093996, - 0.0020762964, - -0.009226025, - 0.007203702, - 0.008049641, - -0.008560729, - -0.00046813046, - 0.030735794, - 0.00799677, - -0.019773832, - -0.019104129, - -0.023104716, - 0.011032458, - 0.014777502, - 0.018593041, - 0.012336615, - 0.023985904, - -0.004088707, - 0.005666031, - -0.015041858, - -0.008371274, - 0.049804676, - 0.017711854, - 0.013658395, - 0.024620358, - 0.0013460128, - 0.008274344, - 0.033678956, - -0.028074611, - 0.25068, - -0.0042208848, - -0.0031678665, - 0.19428405, - -0.019967692, - -0.024215013, - 0.029378766, - 0.009296521, - -0.03457777, - 0.006322515, - -0.018945515, - -0.0047540027, - 0.010221766, - 0.016680865, - 0.010371569, - 0.017341755, - 0.013103248, - -0.0067763263, - -0.0006900794, - 0.0051725665, - -0.016187401, - 0.0044147456, - 0.005599942, - -0.029836984, - -0.0037670734, - 0.009305332, - 0.028603323, - -0.018769277, - 0.004240711, - -0.022523133, - -0.0017216187, - -0.014698195, - 0.031264506, - -0.023562934, - 0.011288002, - -0.017147895, - -0.015676312, - -0.014354533, - -0.0062211785, - 0.008626819, - 0.0240564, - -0.0072345436, - 0.007124395, - -0.018469675, - -0.009331767, - 0.0035820242, - -0.025184318, - -0.018399179, - 0.0045293, - -0.0013482157, - 0.0048333094, - -0.011102953, - 0.04391835, - 0.029167281, - -0.018839773, - -6.853292E-05, - 0.01825819, - 0.015341462, - 0.047725074, - 0.006736673, - 0.008203849, - -0.017755913, - 0.031810842, - 0.024074022, - -0.0004516082, - -0.002531209, - 0.02084888, - 0.0014726834, - -0.004441181, - 0.0030158616, - -0.001528859, - 0.004657072, - 0.0025752683, - 0.014953739, - 0.018522546, - -0.0030929656, - -0.00015820056, - 0.0068952865, - -0.009367015, - 0.012689089, - 0.029466886, - -0.012178001, - 0.022082541, - -0.0032273466, - 0.0004934646, - -0.0013493173, - 0.009754738, - 0.011270379, - 0.024408873, - -0.026470851, - 0.009922163, - -0.028338967, - -0.003661331, - -0.033819947, - -0.011252755, - -0.03530034, - -0.006300485, - 0.033996187, - -0.01617859, - -0.029237777, - -0.011658101, - 0.022805113, - 0.0051373187, - 0.0074460283, - -0.0012226467, - -0.03704509, - 0.0043068, - 0.00943751, - 0.01627552, - 0.017086212, - 0.007401969, - 0.023862537, - -0.008454987, - 0.00026958808, - -0.014883244, - 0.008336027, - 0.009419886, - -0.0015145397, - 0.0031700693, - 0.0040358356, - -0.015878985, - 0.020249672, - 0.016566312, - -0.006538406, - -0.034383908, - 0.0028286094, - 0.06242327, - 0.011851962, - 0.0020443534, - 0.025043327, - -0.009508005, - -0.002654575, - -0.020443533, - 0.009825232, - -0.008860333, - 0.019121753, - 0.008913204, - -0.0004962183, - -0.024655607, - 0.016733736, - -0.011799091, - -0.019685712, - 0.003533559, - -0.0048861806, - 0.0068424153, - -0.0005262337, - -0.018152447, - -0.009278896, - 0.017703041, - 0.0020355415, - -0.0018086359, - -0.017606111, - -0.0053488035, - 0.022153035, - -0.012098694, - -0.0025928922, - 0.006062565, - 0.0043310327, - 0.013173742, - -0.004441181, - -0.024990456, - 0.013535028, - 0.011525922, - 0.003200911, - 0.017896904, - 0.0054986053, - 0.012909386, - -0.01642532, - -1.6849255E-05, - -0.017341755, - -0.0050315764, - 0.0014242181, - -0.03982964, - 0.028338967, - -0.005793803, - -0.005595536, - 0.0084858285, - -0.021976799, - -0.09418124, - 0.030541934, - -0.0061550895, - 0.004141578, - -0.03637539, - 0.0062388023, - 0.020108681, - 0.016909974, - 0.01868116, - 0.009367015, - 0.01991482, - 0.0042825677, - 0.026946692, - -0.007895433, - -0.007071524, - -0.03288589, - -0.0042913794, - 0.0006212367, - 0.0055074175, - 0.01028345, - 0.021430463, - -0.0012711119, - -0.017517993, - 0.012133942, - -0.0106359245, - 0.0025179912, - -0.006855633, - 0.0060185054, - 0.026999563, - 0.012089882, - -0.004912616, - 0.005511823, - -0.011904833, - -0.010089588, - 0.028250847, - -0.015834926, - 0.011825526, - -0.009032165, - 0.01845205, - 0.00183397, - 0.009701867, - 0.017896904, - -0.010371569, - 0.0046174186, - 0.006379792, - -0.0025598477, - -0.0010436556, - 0.0051681604, - 0.004806874, - 0.0036304896, - 0.012019387, - 0.034436777, - -0.007705978, - 0.0052386555, - -0.014627701, - -0.010732855, - 0.0051725665, - 0.024796596, - -0.006379792, - 0.03137025, - -0.006921722, - -0.015403145, - 0.0039499197, - 0.011067706, - 0.013570276, - -0.012142753, - 0.0070935534, - -0.013693643, - -0.02061977, - -0.013473346, - -0.027070057, - 0.002998238, - 0.0108121615, - -0.013834632, - 0.031652227, - 6.0512746E-05, - 0.0025400207, - 0.0029585846, - 0.0048377155, - -0.010926716, - 0.009032165, - -0.0075561767, - 0.014786314, - -0.009446322, - 0.020989869, - 0.0022271995, - -7.173411E-05, - 0.018645912, - -0.0128300795, - 0.01075929, - 0.0026413572, - -0.038631227, - 0.008631225, - -0.020884126, - 0.0011719784, - 0.017050965, - 0.0022976946, - -0.0020884126, - 0.0007539654, - 0.026294613, - -0.0015200472, - 0.04472904, - -0.005582318, - 0.008410928, - 0.019826703, - -0.0061903372, - 0.041063305, - 0.008569541, - 0.00071376126, - -0.019333238, - 0.04331914, - 0.019773832, - -0.004057865, - -0.017297696, - -0.0037736823, - 0.006551624, - -0.030259954, - -0.00025155128, - -0.021007493, - 0.028092233, - -0.0040182117, - -0.02430313, - 0.004201058, - -0.0077015725, - 0.017086212, - 0.004996329, - 0.011975328, - -0.002228301, - 0.004586577, - -0.008300779, - -0.010732855, - -0.008851521, - 0.017852845, - 0.01679542, - -0.0029079164, - -0.012733148, - 0.017535616, - 0.008697313, - 0.009657807, - 0.012777208, - 0.027581146, - 0.012944633, - 0.013825821, - 0.015984727, - -0.009226025, - 0.0087545905, - 0.059039515, - -0.0066089006, - -0.01222206, - 0.0051725665, - -0.00120282, - 0.017509181, - 0.020972244, - 0.0014010869, - 0.01609047, - -0.011922457, - 0.008199443, - 0.033520345, - 0.0026854167, - -0.02306947, - -0.022153035, - -0.031951834, - 0.028620945, - -0.014707007, - 0.02557204, - 0.0060052876, - -0.0027184612, - -0.0064282576, - 0.048852995, - -0.00056946697, - 0.0033815543, - -0.010724043, - 2.8483673E-05, - -0.016804231, - 0.0045645474, - 0.006983405, - -0.002061977, - 0.0021511973, - -0.01698047, - -0.00036018508, - -0.0060757827, - -0.0020245267, - 0.017403439, - 0.014134236, - 0.00022249966, - -0.0031546487, - 0.014803938, - 0.005392863, - -5.5143017E-05, - 0.03693935, - 0.012512852, - -0.042296965, - 0.0010733956, - -0.023034222, - -0.0031171981, - 0.0033154653, - 0.0025664566, - 0.030118963, - 0.023668677, - 0.030894408, - -0.011666913, - -0.0075826123, - 0.013438098, - -0.017183142, - 0.009701867, - -0.015332649, - 0.0028528422, - 0.010803349, - 0.010547806, - -0.017773537, - 0.0123806745, - -0.006053753, - -0.030841537, - 0.0014176092, - -0.010204143, - 0.033414602, - 0.006723455, - -0.017544428, - 0.02444412, - -0.0026171247, - 0.012671466, - 0.012847703, - -0.0067454847, - -0.009085036, - 0.026682336, - 0.02217066, - 0.026964314, - -0.0095168175, - -0.0096049355, - -0.009895727, - 0.013182554, - 0.0023659864, - -0.022487886, - -0.020796008, - 0.050227646, - -0.00021712993, - 0.052941702, - 0.0039785584, - 0.004661478, - 0.01991482, - -0.0226465, - 0.0036393013, - 0.03353797, - 0.011957704, - -0.010107212, - 0.0065119704, - 0.14275226, - -0.03544133, - 0.033714205, - -0.011525922, - 0.015649877, - -0.004798062, - -0.020672642, - -0.0040865038, - -0.015394333, - -0.010239391, - -0.00693494, - -0.003130416, - -0.0028308125, - -0.020179177, - 0.005542665, - -0.0052871206, - -0.0043442505, - 0.00088504195, - -0.0036415043, - -0.01052137, - 0.02585402, - -0.008313997, - 0.0011422384, - -0.0028462333, - 0.032568663, - 0.021307096, - 0.00272507, - -0.007388751, - 0.01703334, - 0.009834045, - -0.015746808, - 0.014336908, - -0.017253637, - -0.0020035985, - 0.0017381409, - 0.014054929, - 0.0096930545, - 0.0007181672, - 0.006855633, - -0.007322662, - 0.001113049, - 0.011120577, - 0.019157, - -0.00051742187, - -0.0039433106, - -0.010345133, - 0.0054941997, - -0.022012046, - 0.01637245, - 0.016037598, - 0.01170216, - 0.038948454, - -0.008525482, - 0.01424879, - -0.013658395, - 0.010054341, - -0.01646938, - -0.024990456, - 0.01467176, - 0.0030422972, - -0.030788666, - 0.0005449589, - -0.043988843, - -0.0018901456, - -0.0020487593, - -0.009939787, - -0.025536792, - -0.013394039, - 0.013270672, - 0.006080189, - -0.026876196, - -0.017368192, - 0.00023434061, - 0.035511825, - 0.025466297, - -0.001066236, - 0.02236452, - 0.012327803, - -0.010010282, - -0.014865621, - -0.011058894, - 0.011288002, - 0.03637539, - 0.0037075933, - 0.007935087, - -0.0012997505, - 0.0066838018, - -0.018328685, - 0.004727567, - 0.020831255, - -0.0076795425, - 0.013649583, - 0.024514616, - -0.014636512, - 0.019791454, - -0.010653548, - 0.020073434, - 0.018645912, - -0.002722867, - 0.015367897, - 0.0017744899, - -0.008331621, - 0.0017150098, - -0.010309885, - 0.0007952711, - 0.04123954, - 0.0013746513, - 0.022910856, - -0.027440157, - -0.0075782062, - -0.007957117, - -0.0088867685, - -0.016680865, - -0.017086212, - 0.0027647235, - 0.011525922, - 0.007873404, - -0.015385521, - 0.023316203, - -0.0009423191, - -0.009904539, - 0.007943898, - -0.012495228, - -0.00223491, - -0.009040976, - 0.014380968, - -0.018037893, - 0.005679249, - -0.016116906, - 0.009525629, - -0.019033635, - 0.01500661, - 0.0053003384, - 0.023386696, - 0.0019573362, - 0.022540757, - 0.016716113, - 0.017755913, - 0.014275226, - -0.016768984, - 0.012327803, - -0.009331767, - 0.019897196, - -0.008199443, - -0.019509476, - 0.0040997216, - -0.0016335, - 0.009067412, - 0.012697902, - 0.0020840068, - 0.06372742, - 0.018205319, - -0.022734618, - -0.0023241302, - 0.015429581, - 0.0067939498, - -0.010917904, - -0.027986491, - 0.0095168175, - -0.012803644, - -0.013376415, - 0.0022415188, - -0.009393451, - -0.014380968, - 0.0011196579, - -0.0058334563, - -0.006939346, - 0.024796596, - 0.0129622575, - -0.0012479807, - 0.0022547366, - 0.0029101192, - -0.0009836247, - -0.029801736, - 0.01613453, - 0.0014319285, - 0.005789397, - -0.020496404, - -0.0044301664, - 0.01623146, - -0.0031061834, - -0.010362756, - -0.004324424, - -0.033908065, - 0.020690266, - -0.0067631085, - -0.017940963, - 0.03128213, - -0.020302543, - 0.020672642, - -0.0012292556, - -0.029925102, - -0.010292262, - 0.018134823, - 0.018434428, - 0.002588486, - -0.036269646, - -0.0066133067, - 0.015367897, - -0.005247467, - -0.0076266713, - -0.029220153, - -0.02236452, - -0.009878104, - 0.027246295, - 0.020320166, - 0.020196801, - -0.035159353, - 0.0065560294, - -0.0101424595, - 0.0070318705, - 0.0013217801, - 0.0008420841, - -0.0032339555, - 0.015641065, - -0.011693348, - 0.002388016, - 0.018822148, - -0.017747102, - -0.008199443, - -0.02382729, - 0.028462332, - 0.015033046, - -0.015297403, - 0.022558382, - -0.019350862, - -0.009587312, - -0.012777208, - -0.02382729, - -0.016011164, - -0.010600677, - -0.009834045, - -0.0016753563, - -0.0122925555, - -0.0003221839, - -0.01222206, - 0.007895433, - 0.007705978, - 0.012750773, - 0.012548099, - 0.010045529, - 0.0023417538, - -0.0096049355, - -0.013490969, - 0.00995741, - 0.04127479, - 0.0034983114, - 0.014839185, - -0.015958292, - 0.012741961, - -0.00312601, - -0.02632986, - -0.038243506, - 0.017385814, - -0.02849758, - -0.008604789, - -0.007119989, - 0.012971069, - 0.014336908, - -0.009666619, - -0.014328097, - 0.0017921135, - 0.014072552, - -0.0035776182, - 0.004267147, - 0.010054341, - -0.012715525, - -0.009684242, - 0.023051845, - 0.02953738, - -0.008948452, - 0.014072552, - 0.009102659, - -0.005194596, - 0.028427085, - -0.027528275, - -0.0009704069, - 0.0068247914, - 0.014363344, - 0.012230872, - -0.006987811, - -0.0075693945, - -0.0043001915, - 0.010362756, - 0.0024364814, - 0.013411663, - 0.0064943465, - 0.008992511, - 0.0038067268, - 0.0021016304, - 0.025272436, - -0.012054635, - 0.013429286, - 0.014495523, - 0.014460275, - 0.00995741, - 0.00083106925, - -0.0072169197, - 0.020778384, - 0.020373039, - -0.022805113, - 0.0071640485, - 0.00067410787, - -0.015720371, - -0.004643854, - -0.0039477167, - 0.0108562205, - 0.0063621686, - -0.0055691004, - 0.006595683, - -0.0048993984, - 0.006789544, - -0.008882362, - 0.011666913, - 0.019262742, - 0.011499487, - -0.01052137, - 0.0038375685, - 0.0051196953, - -0.030207083, - 0.008891175, - 0.034225293, - -0.027475404, - 0.00024081182, - -0.00016618632, - -0.0074812756, - -0.011384933, - -0.018945515, - 0.0008966075, - -0.02104274, - -0.013173742, - -0.005723308, - -0.012918198, - -0.015843738, - 0.03891321, - -0.0128300795, - 0.021853432, - -0.018786902, - -0.0043662805, - -0.023686301, - -0.013429286, - -0.021871056, - 0.007772067, - 0.024197388, - -0.012865326, - 0.030929655, - -0.0024673229, - -0.0026369514, - -0.018857397, - -0.010803349, - -0.015138789, - -0.024391249, - 0.00533118, - 0.013623147, - 0.004223088, - 0.023421945, - 0.01727126, - -0.011825526, - 0.0063621686, - 0.0074328105, - 0.007274197, - -0.004185637, - 0.0113937445, - 0.008728155, - 0.011737408, - 0.0078117205, - -0.011649289, - 0.0070318705, - 0.0016423118, - -0.0152004715, - 0.010706419, - -0.030471439, - -0.02076076, - -0.023016598, - 0.0055558826, - -0.011737408, - 0.01845205, - 0.0040093996, - -0.001897856, - -0.01896314, - 0.030489063, - -0.002923337, - 0.01778235, - -0.038948454, - -0.0046262303, - 0.01028345, - 0.0019209872, - 0.0048465272, - -0.029308273, - 0.009005729, - -0.012010575, - 0.0031480398, - -0.004472023, - -0.0036481132, - -0.011094142, - 0.034031432, - 0.0065472177, - 0.0144426515, - -0.026964314, - 0.0044191517, - -0.028427085, - 0.0016533267, - -0.025307683, - 0.00058764144, - -0.023421945, - 0.003802321, - -0.0035313559, - 0.0011620651, - -0.012671466, - -0.015905421, - -0.00943751, - -0.0064855344, - -0.042860925, - 0.0015156412, - -0.002934352, - -0.017209578, - 0.020073434, - 0.019950068, - 0.012089882, - -0.025043327, - 0.015632253, - 0.021500956, - 0.015799679, - 0.0045160824, - -0.011834338, - 0.0003139228, - 0.0010816568, - -0.007525335, - 0.022135412, - 0.010865033, - -0.010926716, - 0.014900868, - -0.0052254377, - 0.012539288, - 0.009886916, - -0.017940963, - 0.02241739, - -0.0052034077, - -0.0017271261, - 0.015024235, - -0.022205906, - -0.0036833608, - 0.006185931, - 0.01679542, - 0.021923928, - -0.0013394039, - 0.040922314, - 0.0006217874, - 0.004020415, - 0.0044213547, - -0.014830373, - -0.007472464, - -0.030876784, - 0.018134823, - 0.0061594956, - 0.007644295, - 0.017958587, - 0.008225879, - -0.015843738, - -0.003134822, - 0.021888679, - 0.011120577, - 0.010027905, - 0.015632253, - -0.019456604, - -0.0021434869, - 0.0070539, - 0.017579677, - 0.018363932, - 0.002168821, - -0.009322956, - -0.018046705, - 0.008582759, - -0.008076076, - -0.009499193, - 0.00015957742, - 0.0089308275, - 0.024778971, - -0.0062211785, - 0.0034542521, - 0.013349979, - 0.024091646, - 0.014654136, - -0.010512558, - -0.012010575, - -0.017024528, - -0.01623146, - 0.009049788, - 0.015632253, - -0.0040798946, - 0.04712587, - -0.001428624, - 0.016381262, - -0.025378179, - -0.018645912, - 0.045363493, - -0.017500369, - 0.0025510357, - -0.0015608021, - 0.006992217, - 0.02146571, - 0.011402557, - 0.018363932, - -0.0002563703, - 0.0064106337, - 0.011067706, - 0.009657807, - -0.0418035, - -0.009393451, - -0.044940524, - 0.02675283, - -0.018205319, - 0.009287708, - -0.023228083, - -0.02571303, - 0.003394772, - -0.027951244, - 0.0021754298, - 0.029308273, - 0.0020399473, - -0.0067498907, - 0.024902338, - 0.00034173526, - -0.010865033, - -0.001194008, - -0.005762961, - 0.000106155465, - -0.012486417, - 0.020954622, - 0.012671466, - -0.00018656376, - 0.019386109, - 0.011243943, - 0.022258777, - 0.020214424, - 0.0076487013, - -0.018434428, - 0.0021699225, - -0.028585698 - ], - "HOTEL5_VECTORIZE_DESCRIPTION": [ - -0.01960212, - -0.02474159, - 0.0041769464, - -0.016662704, - -0.0036562372, - -0.015238078, - -0.0021617333, - 0.050745506, - 0.025102254, - 0.0066903275, - -0.016554505, - -0.011992097, - -0.012244562, - 0.005504643, - -0.003523242, - 0.023875995, - -0.029664662, - 0.0016455321, - 0.0033970093, - 0.021495609, - -0.022866134, - 0.0027207634, - 0.0008458711, - -0.009557611, - 0.017852897, - 0.010387139, - -0.02580555, - -0.010486322, - 0.0031896273, - -0.002671172, - 0.029700728, - -0.016662704, - 0.023984194, - 0.018826691, - -0.0065145036, - 0.014760197, - 0.004551136, - 0.01600449, - 0.0050853705, - 0.003466888, - 0.028943332, - 0.0037103368, - -0.017474199, - -0.0079661785, - 0.0053964434, - -0.017302882, - 0.005076354, - 0.014976596, - -0.003227948, - -0.0036968119, - -0.019529987, - -0.003949277, - 0.016590571, - 0.0033834844, - -0.013191307, - 0.013669187, - 0.017645514, - -0.012902775, - 0.008268235, - -0.015183979, - 0.012298662, - 0.01943982, - 0.016184822, - -0.011189618, - -0.028636767, - -0.011640449, - -0.011135519, - 0.0082456935, - -0.01893489, - 0.008394468, - 0.016284006, - -0.0019318096, - -0.019926718, - -0.007916587, - 0.0018033228, - 0.025733417, - -0.013515905, - -0.017131567, - -0.0063612214, - 0.026382614, - -0.022307103, - -0.0110363355, - 0.00013975753, - 0.024254693, - -0.009093256, - -0.01592334, - -0.021134945, - 0.025426852, - -0.0034759047, - 0.023190731, - 0.023533363, - 0.034010667, - 0.01712255, - -0.01326344, - 0.01206423, - -0.0074387067, - -0.0019115222, - -0.019061122, - 0.013110157, - 0.008804724, - 0.02239727, - 0.0033631972, - -0.020233283, - 0.018574225, - 0.015986457, - -0.013515905, - 0.034425434, - 0.006807544, - -0.002777117, - 0.009278096, - -0.022090705, - -0.012334729, - -0.008371926, - 0.020305416, - -0.016518436, - -0.0072042746, - -0.0059689987, - 0.007853471, - -0.027140008, - 0.024380924, - 0.02335303, - -0.01248801, - 0.016915169, - -0.015887273, - -0.014101985, - -0.002068186, - -0.021441508, - -0.008074378, - -0.009359245, - -0.039781302, - 0.007601006, - 0.007934621, - -0.02585965, - -0.009981392, - 0.019529987, - -0.0029890076, - -0.0116855325, - -0.011433067, - -0.005680467, - -0.015634809, - 0.00043927817, - -0.018808657, - 0.0016928694, - -0.007105092, - 0.034317233, - -0.011649465, - -0.0002936035, - 0.006717378, - -0.012352762, - 0.030512223, - -0.004963646, - 0.003243727, - 0.004519578, - -0.012551127, - 0.002657647, - -0.005531693, - -0.021351343, - -0.011487166, - 0.02162184, - 0.006266547, - -0.037509114, - -0.001041419, - -0.0045894566, - 0.018826691, - 0.022126772, - 0.016581554, - -0.0070059095, - 0.004855447, - -0.01547251, - -0.013362622, - 0.025625218, - 0.03507463, - -0.001109607, - 0.030494189, - 0.01848406, - 0.007871504, - 0.0058247326, - -0.013317539, - -0.019529987, - 0.0019216659, - -0.004183709, - -0.01320934, - 0.046489663, - 0.008232169, - 0.006739919, - 0.016662704, - 0.010269924, - 0.011712582, - 0.029736795, - 0.038735375, - 0.0076731388, - -0.0016511675, - -0.016464338, - 0.0011789224, - -0.002641868, - 0.006812052, - -0.014129034, - 0.002700476, - 0.027861338, - -0.0399977, - -0.002481823, - -0.032982774, - 0.006180889, - -1.438784E-05, - 0.0007652851, - -0.012253579, - -0.0020208487, - 0.008105936, - -0.010693705, - -0.0066632777, - -0.024471091, - -0.0040574763, - 0.014949546, - 0.012839659, - -0.019259488, - 0.005360377, - -0.013615088, - 0.009251046, - -0.017032385, - 0.006162856, - 0.0035390211, - 0.011108468, - 0.027608873, - -0.011721599, - -0.01153225, - 0.024903888, - -0.010964203, - -0.025282586, - -0.010964203, - 0.004932088, - -0.00270273, - -0.011983081, - -0.0014437854, - -0.030710587, - 0.022938266, - 0.01019779, - 0.007957162, - 0.007903063, - -0.011342901, - 0.015183979, - -0.006397288, - 0.00018737651, - -0.019133255, - -0.02463339, - 0.011090435, - -0.006433354, - 0.01877259, - 0.020738212, - 0.008083395, - -0.007857979, - -0.01320934, - 0.025120288, - 0.011378967, - -0.013497871, - 0.019115223, - 0.02239727, - -0.027446574, - 0.01083797, - -0.008205119, - 0.0020873463, - -0.034335267, - -0.016500404, - 0.0065550786, - 0.0014077189, - 0.014949546, - -0.014129034, - -0.019620152, - 0.016491387, - 0.0036765244, - -0.030656489, - -0.008791199, - -0.0030611404, - 0.013110157, - -0.01784388, - 0.024831755, - 0.017104518, - -0.021008711, - -0.0022440099, - -0.006162856, - -0.008241185, - 0.0049095466, - -0.04854545, - 0.0286007, - 0.0036224248, - 0.01616679, - 0.0048103635, - -0.014534783, - -0.02351533, - -0.018862758, - 0.012587193, - -0.021820206, - 0.0005928424, - -0.013804437, - -0.015761042, - -0.0048374133, - 0.017708631, - 0.020864446, - -0.00038546027, - 0.02580555, - -0.020449681, - 0.018970957, - 0.018276677, - 0.024525192, - 0.015905308, - -0.028005604, - 0.023136633, - 0.008556767, - -0.013362622, - 0.016554505, - 0.030422056, - 0.00027218903, - 0.002466044, - -0.0047427393, - -0.0039830892, - -0.0030340906, - -0.01773568, - -0.017564364, - 0.017239766, - -0.038843576, - -0.016013507, - 0.027681006, - 0.017970113, - 0.0082952855, - 0.007957162, - -0.0049095466, - -0.006455896, - 0.029610561, - 0.009584661, - -0.015292178, - -0.007857979, - 0.023226798, - 0.02793347, - 0.0056128423, - 0.026021948, - -0.023316965, - 0.01326344, - -0.011009286, - 0.01555366, - 0.006194414, - 0.011577332, - 0.014742164, - -0.010937153, - -0.005080862, - 0.00055762124, - 0.00854775, - -0.010964203, - -0.01589629, - -0.009737943, - -0.004621015, - 0.001322061, - -0.0006277818, - 0.0005815716, - -0.013984769, - 0.008160036, - 0.0053243106, - 0.00063341716, - -0.01888079, - 0.0068616434, - -0.02814987, - 0.004431666, - -0.030566322, - 0.0041792006, - 0.0091563715, - -0.013831486, - 0.0027207634, - 0.024651423, - -0.02362353, - 0.013019991, - -0.0045894566, - -0.007177225, - -0.026725244, - -0.02351533, - -0.02329893, - -0.0019735114, - 0.0052611944, - 0.020521814, - 0.023226798, - -0.0037982487, - 0.00092871126, - 0.0025742433, - 0.019385722, - 0.0046796226, - 0.00372837, - -0.03630089, - 0.006473929, - -0.011333884, - 0.0086559495, - -0.007623547, - 0.0019566054, - 0.001570018, - -0.012902775, - -0.0024773148, - -0.018628325, - 0.0039402605, - -0.0067263944, - 0.003358689, - 0.005004221, - -0.01600449, - 0.026508845, - 0.009016614, - 0.0058021913, - -0.017708631, - 0.007853471, - -0.012668343, - 0.0058878493, - -0.037076317, - -0.028005604, - -0.024110427, - 0.016464338, - 0.008173561, - 0.0017278087, - -0.020864446, - 0.0006520139, - 0.007921096, - -0.02005295, - 0.013371639, - -0.0062169554, - -0.015860224, - -0.010396156, - 0.0023803862, - 0.0004234991, - 0.010089591, - -0.010558455, - -0.0033248765, - 0.021820206, - -0.0025426853, - -0.016428271, - -0.030908953, - -0.025841616, - -0.017627481, - 0.0011620162, - -0.011847831, - 0.012469977, - 0.0086559495, - -0.01842996, - 0.008142003, - -0.008534226, - -0.010071558, - -0.0023285407, - -0.007014926, - -0.007794863, - -0.021044778, - -0.00684361, - 0.0027094926, - -0.002948433, - 0.013948702, - 0.027789205, - 0.027266242, - -0.00513947, - 0.005491118, - -0.014237233, - 0.009395312, - -0.010684688, - -0.0024299775, - -0.022667767, - 0.0051935697, - 0.034497567, - -0.01669877, - 0.005635384, - -0.019980818, - 0.012542111, - 0.007276408, - 0.009025631, - -0.035038564, - 0.04584047, - -0.027735105, - -0.0055181677, - 0.013993786, - -0.016752869, - 0.0047382307, - -0.0029732285, - -0.02178414, - 0.02497602, - -0.014083952, - 0.004170184, - -0.020070983, - 0.017825846, - -0.019980818, - 0.020467713, - -0.019259488, - -0.018457009, - 0.006063673, - 0.0011529996, - 0.010089591, - 0.008389959, - -0.6699705, - -0.012659326, - 0.0011146789, - 0.0072854245, - -0.038735375, - 0.009999425, - 0.009701877, - -0.019566054, - 0.09009401, - 0.00086390437, - 0.015220045, - -0.01776273, - -0.018628325, - 0.0016083386, - 0.0095756445, - 0.013308522, - 0.0010960822, - -0.018249627, - 0.01632909, - 0.0028154377, - -0.016428271, - -0.026112115, - 0.006225972, - -0.0018145936, - -0.030908953, - 0.042919084, - 0.0037937404, - -0.021243144, - -0.02636458, - -0.006207939, - -0.001092701, - 0.023262864, - 0.013110157, - -0.00977401, - 0.011180602, - -0.009287112, - 0.009205963, - -0.006225972, - 0.018682424, - 2.2488704E-05, - -0.0010453637, - 0.0069382847, - -0.05770633, - 0.0030566321, - 0.0076956805, - -0.020810345, - -0.013191307, - 0.005563251, - -0.005770633, - -0.004652573, - -0.03422707, - 0.00924203, - 0.007731747, - 0.009476461, - -0.008849807, - 0.0021313021, - 0.015463494, - -0.0110363355, - -0.024885856, - -0.005797683, - -0.001599322, - -0.005549726, - 0.0036291871, - 0.016554505, - -0.0051034037, - 0.0044992906, - 0.025931783, - -0.0021369376, - -0.019800484, - -0.025895717, - -0.024056327, - 0.017311899, - 0.009102272, - 0.015039712, - 0.02234317, - 0.023767795, - -0.000806987, - 0.0044136327, - -0.00796167, - -0.014101985, - 0.050024174, - 0.021892339, - 0.009602694, - 0.01893489, - -0.00460749, - -0.0015497305, - 0.024056327, - -0.026184248, - 0.23414344, - -0.0045894566, - -0.01091912, - 0.19663432, - -0.0151659455, - -0.020197216, - 0.017086484, - 0.0075243646, - -0.027572807, - 0.0046480647, - -0.0061403145, - -0.016491387, - 0.0065686037, - 0.021748073, - 0.0043099415, - 0.012172429, - 0.002040009, - -0.0046480647, - 0.007452232, - -0.0037306242, - -0.016365156, - 0.014958563, - -0.0029529412, - -0.05244063, - 0.0009991536, - 0.0059284237, - 0.02402026, - -0.010702721, - 0.00548661, - -0.018682424, - -0.0012251325, - -0.006942793, - 0.02977286, - -0.02072018, - 0.013597054, - -0.01366017, - -0.0097559765, - -0.0043324833, - -0.0120461965, - 0.009548594, - 0.017888963, - -0.009909259, - 0.0066181947, - -0.014291334, - -0.0068796766, - 0.0033789761, - -0.011117485, - -0.009602694, - 0.015517593, - 0.0074206735, - -0.0035570543, - -0.02026935, - 0.04284695, - 0.024813723, - -0.015048729, - 0.0038500943, - 0.02061198, - 0.01376837, - 0.043460082, - 0.012848675, - -0.0023668613, - -0.009882209, - 0.025823584, - 0.018916856, - 0.006244005, - -0.008020278, - 0.014624949, - 2.271764E-05, - -0.008660458, - -0.0058878493, - -0.0040484597, - 0.006866152, - -0.012776542, - 0.022721868, - 0.025661284, - -0.005008729, - -0.0042919083, - -0.0017751459, - -0.008480126, - 0.01270441, - 0.033469673, - -0.015833175, - 0.03155815, - -0.004109322, - 0.015355294, - 0.005355869, - 0.008876856, - -0.0037666906, - 0.021928405, - -0.027915437, - -0.004652573, - -0.028420368, - -0.0019509699, - -0.023930093, - -0.012028163, - -0.03568776, - -0.013155241, - 0.031323716, - -0.011135519, - -0.018438976, - -0.0006785002, - 0.030223692, - 0.009431379, - 0.008683, - 0.0007427436, - -0.045371603, - 0.0006367984, - 0.0072132912, - 0.012713426, - 0.004801347, - 0.00028853165, - 0.018114379, - -0.004859955, - 0.006825577, - -0.019295555, - 0.004479003, - 0.017970113, - 0.0023736237, - 0.0023307947, - 0.012614244, - -0.0077903545, - 0.007474773, - -0.008326843, - -0.013092124, - -0.031305686, - -0.0005601572, - 0.07054599, - 0.0040259184, - 0.008827265, - 0.011694549, - -0.0013412214, - -0.007001401, - -0.009819093, - 0.011081419, - -0.012235546, - 0.014579865, - 0.0044294116, - -0.0013457297, - -0.027067875, - 0.022433337, - -0.009341212, - -0.03166635, - -0.019295555, - -0.010531405, - 0.004905038, - -0.0047382307, - -0.024200592, - -0.009891226, - 0.02441699, - 0.004932088, - 0.0055407095, - -0.014507732, - 0.0064964704, - 0.030169591, - -0.010621572, - 0.0047878223, - 0.0024029277, - -0.0060546566, - 0.0065821283, - -0.010910103, - -0.026887543, - 0.020251315, - 0.010369106, - 0.0019103951, - 0.008836282, - -0.000108058484, - 0.009602694, - -0.0025021106, - -0.0024795688, - -0.026941644, - -0.0012285137, - 0.004064239, - -0.03898784, - 0.031522084, - -0.010324024, - -0.008304302, - 0.010910103, - -0.021820206, - -0.09629744, - 0.028402334, - -0.015995475, - -0.009093256, - -0.04825692, - 0.014787247, - 0.010242874, - 0.017465182, - 0.009611711, - 0.0063386797, - 0.018682424, - 0.0050267624, - 0.029790893, - 0.0027951505, - -0.003110732, - -0.031918813, - -0.020233283, - -0.0039289896, - 0.012803592, - -0.0019002515, - 0.022379236, - 0.0042085047, - -0.017338948, - -0.0022857117, - -0.015481527, - -0.0047337227, - -0.004796839, - 0.00545956, - 0.020864446, - 0.020070983, - -7.695821E-06, - 0.001350238, - -0.015066762, - 0.0028289626, - 0.017438132, - -0.0022180872, - 0.012343745, - 0.0010256398, - 0.02061198, - 0.0044587157, - 0.003099461, - 0.017393049, - -0.012839659, - -0.00080473284, - 0.009611711, - -0.0009174405, - -0.0046300315, - 0.0053198026, - 0.009945326, - 0.0039966144, - 0.00082727434, - 0.045335535, - -0.0023848945, - 0.017717646, - 0.0026058014, - -0.024957988, - -0.00016906152, - 0.019241454, - -0.008426026, - 0.012244562, - -0.0042039966, - -0.009102272, - 0.0033271306, - 0.013019991, - 0.0072448496, - -0.019638186, - -0.0009411091, - -0.01653647, - -0.014210184, - -0.013010974, - -0.022685802, - 0.005008729, - 0.016752869, - -0.019854585, - 0.026779344, - -0.007848963, - 0.021693975, - 0.0067579523, - -0.0032707767, - -0.01368722, - -0.0039988686, - -0.014111001, - 0.022018572, - -0.013894603, - 0.022613669, - 0.0015486035, - -0.0074612484, - 0.002026484, - -0.020738212, - 0.0021921643, - 0.0090662055, - -0.03184668, - -0.0067940187, - -0.024038294, - 0.0002121722, - 0.026328513, - 0.004431666, - 0.011090435, - 0.00742969, - 0.023731729, - -0.008903907, - 0.05027664, - -0.013921652, - 0.004972663, - 0.027897405, - -0.007736255, - 0.04944711, - 0.011730615, - -0.016779918, - -0.020233283, - 0.03161225, - 0.013029007, - -0.014255268, - -0.025336687, - -0.004007885, - -0.00094336324, - -0.02553505, - -0.005856291, - -0.022938266, - 0.024867821, - -0.011099452, - -0.019800484, - -0.005035779, - -0.0039718184, - 0.019475887, - 0.007307966, - 0.01837586, - 0.0059915404, - 0.0013254423, - -0.001701886, - -0.015463494, - -0.015932357, - 0.007533381, - 0.016788935, - 0.003520988, - -0.006636228, - 0.02095461, - 0.015364311, - 0.013344589, - 0.014020835, - 0.018952923, - 0.022938266, - 0.009521545, - 0.020702146, - -0.0070509925, - 0.010224841, - 0.06430649, - -0.00078444544, - -0.0062169554, - 0.008371926, - -0.011460117, - 0.014165101, - 0.028420368, - -0.00075852266, - 0.013497871, - -0.01248801, - 0.01206423, - 0.033361472, - 0.008006753, - -0.01757338, - -0.019475887, - -0.027194109, - 0.02329893, - -0.019475887, - 0.011983081, - 0.00024668893, - -0.004346008, - -0.023912061, - 0.044938806, - 0.004932088, - 0.0034961922, - -0.015643826, - -0.0047337227, - -0.020630013, - 0.002258662, - 0.0059509655, - -0.0052927528, - 0.011108468, - -0.01568891, - -0.008326843, - -0.009278096, - 0.0007511967, - 0.016067607, - 0.0029033497, - -0.0054550515, - -0.00884079, - 0.01834881, - -0.0027590839, - -0.00229022, - 0.036048423, - 0.012812609, - -0.032766376, - 0.0040416974, - -0.019421788, - -0.0012228783, - -0.0074071484, - 0.0038816524, - 0.03211718, - 0.019457854, - 0.021910373, - 0.0006339807, - -0.007384607, - 0.005328819, - -0.0034623798, - 0.012298662, - -0.016545488, - -0.0069067264, - 0.009945326, - 0.0006356713, - -0.0140659185, - 0.017293867, - -0.011829798, - -0.023713695, - -0.0071817334, - -0.006027607, - 0.036445156, - 0.003421805, - -0.023677628, - 0.016897134, - 0.00788503, - 0.008624392, - 0.014823314, - -0.011342901, - -0.009900242, - 0.024471091, - 0.031413883, - 0.02748264, - -0.0020602962, - -0.017988145, - -0.007253866, - 0.007664122, - -0.01485938, - -0.020810345, - -0.01318229, - 0.05211603, - 0.0030724113, - 0.04807659, - -0.004215267, - -0.0029101123, - 0.014787247, - -0.019620152, - 0.0054144766, - 0.01600449, - -0.0014460395, - -0.010080575, - 0.007060009, - 0.14469862, - -0.036066458, - 0.028726934, - -0.013416722, - 0.0057120253, - -0.011108468, - -0.016347121, - -0.00091067806, - -0.017302882, - -0.006915743, - -0.0015418411, - -0.002892079, - -0.0003722171, - -0.007934621, - 0.00660467, - 0.000704423, - 0.007578464, - -0.0015587471, - 0.005252178, - -0.007894046, - 0.015382344, - -0.005504643, - -0.0033744678, - 0.0013198069, - 0.02820397, - 0.007979703, - -0.0008368545, - -0.016969267, - 0.01597744, - -0.0046007275, - -0.019061122, - 0.024705524, - -0.022523502, - 0.000557903, - 0.0009360373, - 0.018646358, - 0.0009478716, - -0.0019870363, - -0.00079177145, - -0.007957162, - -0.00039813988, - 0.010648621, - 0.022812035, - 0.0071186167, - -0.0041318634, - -0.016843036, - 0.011243718, - -0.017970113, - 0.020738212, - 0.009025631, - 0.00974696, - 0.03345164, - -0.0047923303, - 0.01999885, - -0.009476461, - 0.012235546, - -0.012929825, - -0.017528297, - 0.01201013, - 0.0118658645, - -0.019511953, - 0.0030340906, - -0.034281168, - -0.0037328782, - -0.0084756175, - -0.008011262, - -0.02540882, - -0.011577332, - 0.012307678, - 0.0066407365, - -0.015202012, - -0.012848675, - 0.005784158, - 0.02998926, - 0.010648621, - -0.0065731118, - 0.023695663, - 0.0118658645, - -0.0030183117, - -0.016103674, - -0.0032256937, - 0.009629744, - 0.03341557, - 0.003759928, - -0.010729771, - 0.0087055415, - 0.0037982487, - -0.0050267624, - 0.007898554, - 0.01971032, - -0.010982236, - 0.013155241, - 0.019980818, - -0.0057030087, - 0.017023368, - -0.007619039, - 0.026743278, - 0.022307103, - -0.0035502918, - 0.016635653, - 0.00326176, - -0.008592834, - -0.0028965874, - -0.011000269, - -0.014733148, - 0.036787786, - -0.0010521262, - 0.009458428, - -0.023118598, - -0.003992106, - -0.0065821283, - -0.006153839, - -0.018466026, - -0.015373327, - 0.005959982, - 0.011947013, - 0.0066677863, - -0.011649465, - 0.013434756, - -0.010612555, - -0.012343745, - 0.0013682712, - -0.0143364165, - 0.00492758, - -0.01821356, - 0.014787247, - -0.012848675, - 0.0069473013, - -0.0136962375, - 0.01664467, - -0.018556193, - 0.0072178, - -0.0046165064, - 0.012551127, - -0.006884185, - 0.02764494, - 0.018132411, - 0.014480682, - 0.015986457, - -0.010612555, - 0.011387983, - -0.0042828918, - 0.032189313, - -0.0058923573, - -0.027212141, - 0.002993516, - -0.005152995, - 0.011550283, - 0.017077466, - -0.0015812888, - 0.06564095, - 0.017185668, - -0.03323524, - 0.0062485137, - -0.00014961945, - 0.004364041, - -0.0130560575, - -0.008268235, - 0.01153225, - -0.023677628, - -0.016671719, - -0.0061267894, - -0.010215824, - -0.012848675, - 0.00402141, - -0.0024141984, - -0.0018732016, - 0.02441699, - 0.01645532, - -0.013813453, - -0.0024885854, - 0.0015429681, - 0.0023894028, - -0.024164526, - 0.019638186, - -0.0075243646, - 0.013642137, - -0.020539848, - 0.004990696, - 0.01773568, - -0.00075345085, - -0.016293023, - -0.011568316, - -0.030259758, - 0.029141698, - -0.006415321, - -0.005256686, - 0.03530906, - -0.017483216, - 0.018438976, - -0.0011665245, - -0.032189313, - -0.011360934, - 0.011892914, - 0.023641562, - 0.0018562955, - -0.029195797, - -0.019223422, - 0.021243144, - -0.009548594, - -0.011640449, - -0.018249627, - -0.013083107, - -0.0027793713, - 0.018646358, - 0.025174387, - -0.001733444, - -0.043784678, - 0.0011327121, - 0.0042513334, - 0.00075514143, - 0.0006999147, - -0.0028785542, - 0.0044001075, - 0.020215249, - -0.003185119, - -0.007930112, - 0.015661858, - -0.012803592, - 0.0012431657, - -0.010098608, - 0.024254693, - 0.023821894, - -0.01949392, - 0.012524077, - -0.018952923, - -0.01888079, - 0.001966749, - -0.03283851, - 0.0013603817, - 0.0014449124, - -0.008525209, - 0.0020005612, - -0.007425182, - 0.0043527707, - -0.017402066, - 0.029358096, - 0.009314163, - 0.019457854, - 0.008403485, - 0.0004080018, - -0.013479838, - -0.016473355, - -0.015174962, - 0.024489123, - 0.03942064, - -0.007177225, - 0.022649735, - -0.022631701, - 0.015544643, - 0.0028131837, - -0.021712007, - -0.039817367, - 0.017032385, - -0.023912061, - -0.01960212, - -0.017825846, - 0.023875995, - 0.0020524068, - -0.0047652805, - -0.019475887, - 0.0015733992, - 0.021134945, - -0.026472779, - 0.00023879939, - 0.01019779, - -0.015914325, - -0.012217512, - 0.0056894836, - 0.031738482, - -0.0078038797, - 0.0020073238, - 0.005869816, - -0.012758509, - 0.031756517, - -0.020485748, - -0.010522389, - 0.004977171, - 0.007578464, - 0.011162569, - -0.0066903275, - 0.0024119443, - -0.0011259497, - 0.009620727, - -0.0027365424, - 0.01744715, - 0.008146511, - 0.021333309, - 0.007839946, - 0.01036009, - 0.024507158, - 0.0032888101, - 0.012866708, - 0.014408549, - 0.02764494, - 0.0008599596, - -0.0069833677, - -0.0007658487, - 0.022775967, - 0.007830929, - -0.029610561, - 0.011315851, - 0.0045285947, - -0.027103942, - 0.00516652, - -0.009629744, - 0.020539848, - 0.008078886, - 0.006108756, - -0.0052386527, - 0.007830929, - 0.009359245, - -0.012433911, - 0.012190462, - 0.017113535, - 0.016734837, - -0.011676515, - 0.00013250197, - -0.005666942, - -0.03134175, - 0.018177494, - 0.028961364, - -0.006352205, - 0.0049681542, - -0.0035164796, - -0.014850364, - -0.010098608, - 0.00085263356, - 0.005572268, - -0.020125084, - -0.011360934, - 0.0076370724, - -0.0011434194, - -0.011937997, - 0.023154665, - -0.006564095, - 0.014579865, - -0.019295555, - -0.013227373, - -0.020449681, - -0.009909259, - -0.010233857, - 0.010080575, - 0.02540882, - -0.013957718, - 0.029340062, - 0.0021053795, - 0.008930956, - -0.022379236, - -0.009837126, - -0.009210471, - -0.019313587, - 0.005297261, - 0.010549439, - -0.006329663, - 0.021080844, - 0.014092968, - -0.009201455, - 0.004404616, - -0.0027230175, - 0.013777386, - -0.0047607725, - 0.022162838, - 0.006356713, - -0.0069382847, - -0.0021628602, - -0.0141560845, - 0.0075243646, - -0.0018912349, - -0.008353893, - 0.017888963, - -0.026905578, - -0.023334997, - -0.01201013, - 0.00572555, - -0.012659326, - 0.007060009, - 0.005784158, - -0.011910947, - -0.017302882, - 0.030349923, - 0.0030498698, - 0.01648237, - -0.034299202, - 0.0026959677, - -0.0069698426, - -0.00631163, - -0.0015429681, - -0.03312704, - 0.007298949, - -0.016347121, - 0.0017244274, - -0.015211028, - 0.0019498428, - -0.0009788661, - 0.029502362, - 0.008696524, - 0.012731459, - -0.037220582, - 0.0069833677, - -0.0028740459, - 0.009278096, - -0.018520126, - 0.0034082802, - -0.017140584, - 0.002689205, - -0.002819946, - -0.0037554197, - -0.010937153, - -0.009151864, - -0.02005295, - -0.009332196, - -0.03307294, - 0.010702721, - -0.0012273866, - -0.015670875, - 0.030205658, - 0.025571117, - 0.011297817, - -0.025877682, - 0.010928136, - 0.02223497, - 0.03155815, - -0.013218356, - -0.010621572, - 0.0063386797, - 0.003214423, - 0.00025218344, - 0.020882478, - 0.006207939, - -0.008169052, - 0.004841922, - 0.002979991, - -0.002538177, - 0.0035728335, - -0.017050417, - 0.018276677, - 0.0038636192, - -0.0035277503, - 0.0071005835, - -0.030367957, - 0.008439551, - -0.0059825233, - 0.014949546, - 0.030133525, - 0.017591415, - 0.02708591, - -0.00607269, - 0.0068481187, - 0.01270441, - -0.0055452175, - -0.005739075, - -0.018123394, - 0.018682424, - 0.015183979, - 0.021874307, - 0.01259621, - 0.015283161, - -0.01366017, - -0.011469133, - 0.019566054, - 0.012190462, - 0.010865021, - 0.022974333, - -0.021405442, - 0.0056489087, - 0.003126511, - 0.028961364, - 0.015039712, - 0.0016342613, - -0.025156355, - -0.024561258, - 0.012019147, - -0.008353893, - -0.013344589, - -0.0034984464, - 0.007298949, - 0.008773166, - -0.0052611944, - 0.0050853705, - 0.012830642, - 0.0288712, - -0.0007793736, - -0.013948702, - 0.0010532533, - -0.011883898, - -0.02351533, - 0.0028447418, - 0.024092393, - -0.0010870656, - 0.0403223, - 0.001555366, - 0.019728351, - -0.019620152, - -0.011315851, - 0.037400916, - -0.015111846, - 0.007542398, - -0.005576776, - 0.008939973, - 0.01669877, - 0.005572268, - 0.011676515, - -0.004494782, - 0.018682424, - 0.00854775, - 0.011802748, - -0.03747305, - 0.0026396138, - -0.028402334, - 0.015111846, - -0.016022524, - 0.009629744, - -0.02250547, - -0.026184248, - -0.0048283967, - -0.033217207, - -0.0075378893, - 0.031467985, - 0.009792043, - 0.0054505435, - 0.026743278, - 0.0025314144, - -0.005035779, - -0.0021504625, - -0.015111846, - 0.0058878493, - -0.018610291, - 0.01664467, - 0.0170414, - -0.012469977, - 0.018123394, - 0.020972645, - 0.018790623, - 0.020341482, - 0.008020278, - -0.01701435, - 0.011947013, - -0.030259758 - ], - "HOTEL6_VECTORIZE_DESCRIPTION": [ - -0.014050829, - -0.005357445, - 0.027303934, - -0.0045075966, - -0.016969776, - 0.01419587, - 0.009436718, - 0.0033563352, - 0.0032974123, - -0.010977777, - -0.0077234237, - 0.015437782, - 0.032869875, - -0.019290429, - 0.0018911964, - 0.0066854754, - -0.01238286, - -0.034102723, - 0.0002660026, - 0.0137970075, - -0.013135259, - 0.0025291492, - -0.020704577, - -0.0035240387, - -0.00533025, - 0.011530745, - -0.013225909, - 0.0052033393, - -0.009060519, - 0.018474575, - 0.02289832, - -0.023732305, - 0.02135726, - 0.005003908, - -0.031365078, - 0.010035012, - 0.004659436, - 0.015202091, - -0.02297084, - 0.009536434, - 0.031074995, - 0.038870938, - -0.030748654, - -0.004673034, - 0.0071477927, - -0.00011402135, - 0.0065585645, - 0.0038095878, - -0.026596861, - 0.018891567, - 0.00017266089, - 0.005103624, - 0.0066310847, - -0.047718428, - -0.0034107254, - -0.00132803, - -0.00787753, - -0.019689292, - 0.0041676573, - -0.0015716533, - 0.0012532433, - 0.011394769, - -0.006037324, - -0.0066129547, - -0.0155012375, - 0.0062276903, - 0.0063410033, - 0.024493769, - -0.008439562, - -0.001371089, - 0.0011784567, - -0.011866152, - 0.010334158, - 0.020976529, - 0.010497329, - -0.0016860996, - -0.006096247, - -0.013588511, - -0.0005351213, - 0.014939204, - 0.00083965034, - -0.0024203686, - -0.0045665195, - 0.018619616, - 0.002517818, - 0.0029982657, - 0.00076373055, - 0.005112689, - -0.010116597, - 0.02837361, - 0.00083285157, - 0.00839877, - -0.014993595, - -0.016525589, - -0.009917166, - 0.011748306, - -0.0032475546, - 0.0021427514, - 0.004237911, - 0.009944361, - -0.004532526, - -0.0044282777, - -0.004704762, - 0.0068577114, - 0.013923919, - -0.0066265524, - 0.010832736, - -0.019435469, - -0.010479199, - 0.020450756, - 0.008231066, - 0.00075579865, - -0.039849967, - 0.022445066, - -0.02297084, - 0.004310432, - -0.029370766, - 0.0073789516, - 0.00091387046, - 0.0032090282, - 0.01842925, - -0.011177208, - 0.025980437, - 0.0053755753, - -0.023260921, - 0.0098718405, - -0.021574821, - 0.025019541, - 0.0019285897, - -0.018238883, - 0.018674005, - 0.016471198, - 0.00807696, - -0.0001644457, - -0.010850866, - 0.013579447, - -0.029606458, - 0.0021155563, - -0.0126094865, - 0.0006390861, - 0.025490925, - -0.005357445, - 0.029697107, - 0.0019127257, - 0.008466758, - 0.0077596838, - 0.017849086, - 0.025055801, - -0.024203686, - 0.0032316907, - 0.0013994173, - -0.043766066, - 0.012944893, - -0.0037937239, - 0.019090997, - -0.0319815, - -0.009989686, - -0.01959864, - 0.0049540503, - 0.009980622, - -0.010497329, - -0.025889786, - 0.008888283, - 0.020033764, - 0.01762246, - -0.0070662075, - -0.013289365, - 0.013026479, - -0.0013212312, - 0.002404505, - 0.009255418, - 0.020758968, - 0.028011007, - 0.01952612, - 0.0342115, - -0.013878593, - -0.013951113, - -0.037928175, - -0.014594733, - -0.002535948, - 0.019725552, - 0.0071795206, - 0.015120505, - 0.004727424, - 0.013062739, - 0.025563445, - -0.0020305715, - 0.002406771, - 0.021973684, - 0.020632057, - -0.0012645746, - -0.017205467, - -0.022154985, - -0.009164766, - 0.01595449, - -0.0036940083, - -0.025599705, - 0.015492172, - 0.0008379507, - -0.017957866, - 0.01663437, - -0.014114285, - 0.01954425, - -0.011793631, - 0.022735149, - 0.0065812273, - 0.0011535278, - 0.02840987, - -0.0015501238, - -0.0031795667, - -0.0067308005, - 0.01846551, - 0.004754619, - 0.023496613, - -0.014168675, - -0.023224661, - 0.0030911826, - -0.020160673, - -0.007691696, - 0.0051353513, - 0.0018674005, - 0.014884814, - 0.00985371, - -0.010841801, - -0.009563629, - 0.034519713, - 0.006458849, - 0.021538561, - -0.007863932, - 0.007927387, - -0.013479731, - -0.003931966, - 0.008045233, - -0.016416807, - 0.008253729, - 0.031328816, - -0.011866152, - 0.0026424625, - -0.004777282, - 0.013869529, - -0.0121109085, - -0.018102907, - -0.001638508, - -0.021411652, - 0.0022968573, - 0.0074197445, - 0.023496613, - 0.0342115, - 0.004663969, - -0.014794163, - -0.015664408, - 0.015428717, - 0.011122818, - -0.0095273685, - -0.0017461554, - 0.016770344, - -0.026107347, - 0.024094906, - -0.021611081, - -0.012491641, - -0.026995722, - -0.0160814, - -0.012990219, - 0.019689292, - -0.0012611753, - 0.0064180563, - 0.008122286, - 0.009681474, - -0.011403834, - -0.027068242, - 0.001035682, - -0.005561409, - 0.02463881, - 0.0031410402, - 0.017432094, - 0.0006923433, - 0.0033314063, - -0.022445066, - -0.0028509586, - -0.0159001, - 0.0031795667, - -0.039813705, - 0.005865088, - 0.0031274427, - 0.020813357, - 0.002148417, - 0.0031161113, - -0.02851865, - -0.0050582984, - 0.015455912, - -0.014649123, - 0.0066492152, - -0.016842864, - -0.003233957, - -0.020849617, - 0.010878061, - 0.018556159, - -0.03749305, - 0.024221817, - -0.005148949, - 0.0081857415, - -0.0045665195, - 0.018084778, - 0.00577897, - -0.012654811, - 0.0068713087, - 0.03189085, - 0.014640057, - -0.022753278, - 0.0033971278, - 0.005080961, - -0.00044362093, - 0.018964088, - -0.013561317, - 0.008842957, - -0.013488797, - -0.021538561, - 0.027503366, - -0.016162986, - -0.0017699512, - 0.023696044, - 0.019852461, - -0.010007816, - 0.005262262, - -0.015428717, - -0.015319937, - -0.00048044772, - 0.004294568, - 0.0012736397, - 0.009944361, - 0.023315312, - 0.0076599685, - -0.018873436, - -0.0037823927, - 0.0035353699, - -0.0045846496, - -0.0021506834, - 0.037638094, - -0.0029824018, - -0.015283676, - -0.0033812642, - -0.040248826, - 0.0015897834, - 0.018601485, - -0.0072837686, - -0.015628148, - -0.038870938, - -0.010198182, - 0.014821359, - 0.010941517, - 0.015745994, - 0.0070435447, - -0.0011761904, - 0.037529312, - 0.036876626, - 0.008743241, - 0.013497861, - -0.00039036377, - -0.027322065, - -0.019090997, - -0.0192723, - -0.004478135, - 0.018329533, - 0.006372731, - 0.038254514, - 0.013633837, - -0.022227505, - 0.014132415, - 0.014349976, - 0.019743681, - -0.0020226396, - -0.018945957, - -0.02324279, - -0.0044078813, - 0.014993595, - 0.0065676295, - -0.011431029, - 0.0063546007, - 0.008929076, - 9.355416E-05, - 0.018338598, - 0.013389081, - -0.0046073124, - -0.020559536, - 0.015437782, - -0.012854243, - -0.013044609, - -0.007945517, - -0.007827671, - -0.030313531, - 0.00572458, - -0.0027127166, - -0.025871657, - 0.014748838, - -0.018565224, - 0.00793192, - 0.04072021, - -0.011304119, - 0.030458571, - 0.0069574267, - 0.01064237, - -0.016271766, - 0.0036192217, - -0.00974493, - 0.019362949, - -0.027775317, - -0.010950582, - -0.03868964, - 0.004319497, - -0.019435469, - 0.010687695, - -0.028917514, - -0.006037324, - 0.0035263048, - -0.021411652, - 0.022046205, - -0.0062412876, - -0.004369355, - 0.006907569, - 0.017151076, - 0.010334158, - 0.008362509, - 0.0033563352, - 0.017323313, - 0.0053075873, - -0.0031954306, - 0.021556692, - -0.0109052565, - -0.009753995, - -0.01839299, - -0.012836113, - -0.0061506373, - 0.0080135055, - -0.0026923202, - -0.010814606, - 0.0248745, - -0.013679163, - -0.012074648, - -0.012265014, - 0.008888283, - 0.024475638, - -0.027285803, - -0.019362949, - -0.009409524, - -0.011911477, - 0.025400274, - 0.043149643, - -0.009169299, - 0.0012351132, - 0.002760308, - -0.0070934026, - -0.0067761256, - -0.041191593, - -0.009491108, - 0.016570913, - -0.0007144393, - 0.007768749, - 0.02632491, - -0.009463914, - -0.019036608, - 0.014694448, - 0.03357695, - 0.0044758692, - -0.022608237, - 0.009772125, - -0.012917698, - 0.00789566, - 0.012074648, - -0.038218256, - -0.0008339847, - -0.020940268, - -0.047718428, - 0.0338489, - -0.0064180563, - 0.02500141, - -0.034773536, - -0.0132984305, - -0.0061506373, - -0.0040090187, - -0.037964433, - -0.03533557, - 0.0168338, - 0.0013427607, - 0.009563629, - -0.016652498, - -0.6509432, - -0.03575256, - -0.016652498, - -0.015555628, - -0.004700229, - -0.008367042, - 0.012917698, - -0.020414496, - 0.09130319, - 0.019961243, - 0.014168675, - -0.022771409, - -0.002585806, - 0.011159078, - 0.0005473025, - 0.03934232, - -0.027666535, - -0.01688819, - -0.0042673727, - 0.0034084592, - 0.013035543, - -0.018229818, - 0.009645214, - -0.016262703, - 0.008784034, - 0.0035059087, - 0.025835397, - -0.009015193, - -0.018057581, - -0.0134706665, - 0.0004988611, - 0.022046205, - 0.0031750342, - 0.009554564, - -0.009391393, - 0.011276924, - 0.006554032, - 0.009998752, - -0.008820294, - 0.010742086, - -0.0034877784, - -0.0043806857, - -0.073245615, - -0.012301275, - 0.0007994242, - -0.010134727, - -0.03368573, - 0.0025676757, - -0.012092778, - -0.020051893, - -0.029298246, - 0.015582823, - -0.0038481143, - 0.009164766, - 0.0058922833, - 0.013833268, - 0.0007263372, - -0.0028962838, - -0.018220752, - -0.018093843, - -0.013543187, - 0.034610365, - 0.001164859, - 0.0020124414, - 0.011285989, - 0.0062050275, - 0.031346947, - 0.008267326, - -0.0045166616, - 0.0031523716, - 0.026252389, - 0.017522743, - 0.027303934, - 0.029116943, - 0.0001296019, - 0.03399394, - 0.0009467313, - -0.0041767224, - -0.014803229, - 0.0065087066, - 0.035281178, - -0.0038685105, - -0.029552067, - 0.023188401, - -0.0059194784, - -0.010288833, - 0.00021189557, - -0.019018477, - 0.2068282, - -0.0048634, - -0.0119386725, - 0.21291992, - -0.010334158, - -0.0029098815, - -0.0017110284, - 0.013905789, - -0.017042296, - 0.0062684827, - 0.0026197997, - -0.03720297, - 0.009962492, - 0.027140763, - 0.013706357, - 0.008308119, - 0.013271235, - -0.010651435, - 0.0033427377, - -0.007614643, - 0.014322781, - -0.014023635, - -0.009160235, - 0.001000555, - 0.0013665565, - 0.01773124, - 0.024258077, - -0.009364198, - -0.002542747, - -0.023551002, - 0.0079364525, - -0.012237819, - 0.002492889, - -0.018945957, - 0.015564693, - -0.017368639, - -0.0038662443, - -0.007827671, - 0.01146729, - 0.012917698, - -0.013552251, - -0.04489013, - 0.02657873, - -0.026016697, - -0.018945957, - 0.016507458, - -0.007836737, - -0.011748306, - -0.0075058625, - 0.025871657, - 0.017132947, - 0.020106284, - 0.002146151, - -0.0015410586, - -0.015283676, - 0.010035012, - 0.010288833, - 0.032471012, - 0.019290429, - 0.035643782, - 0.02679629, - -0.025237102, - 0.048552413, - -0.03383077, - 0.0027399117, - 0.0034855122, - 0.010506394, - -0.009042389, - -0.0074469396, - -0.005511551, - -0.008267326, - -0.023877345, - 0.0019274565, - 0.021030918, - 0.014739773, - -0.0066446825, - -0.0037846589, - 0.0024181025, - -0.0039954213, - 0.0129720885, - 0.011675786, - -0.008149481, - 0.0021280209, - 0.00054588605, - 0.012564161, - -0.011603265, - 0.012174363, - -0.012600421, - 0.04108281, - -0.035915732, - -0.00011118852, - -0.008253729, - 0.0031546378, - -0.04256948, - -0.025708485, - -0.018710265, - -0.015310871, - 0.030857434, - -0.005588604, - -0.018093843, - 0.0110774925, - 0.030748654, - 0.0023591795, - 0.02298897, - -0.010542654, - -0.046449322, - 0.010515459, - -0.0014164143, - 0.007356289, - -0.0059784013, - 0.020867748, - -0.0010929052, - 0.005008441, - -0.0013642902, - -0.035988253, - 0.015963554, - 0.017078556, - 0.0030594547, - 0.026379298, - -0.025599705, - -0.012899567, - 0.0148304235, - -0.013833268, - -0.013932983, - -0.014893879, - 0.0016793007, - 0.052541036, - -0.0036509493, - 0.027702797, - -0.014776033, - -0.0037551974, - -0.0045438567, - -0.020831488, - -0.007777814, - 0.018873436, - 0.0016260436, - -0.0007087737, - 0.0016135791, - 0.0002845576, - 0.026034826, - -0.024276206, - 0.0003617522, - -0.0022084732, - -0.014268391, - -0.0070344796, - 0.012237819, - 0.011757371, - -0.02121222, - 0.03413898, - 0.002474759, - 0.026197998, - -0.012446315, - -0.023587262, - 0.017740306, - 0.012156233, - -0.0056701894, - -0.0061868974, - -0.0033268738, - 0.0031750342, - -0.011857087, - 0.0014651389, - 0.033141825, - 0.005788035, - 0.0098718405, - -0.0036033578, - 0.026941333, - 0.016942581, - 0.0067443983, - 0.002327452, - 0.012074648, - -0.015927294, - 0.010107532, - -0.013207779, - 0.026415559, - -0.011095623, - 0.0073109637, - 0.030911824, - -0.018565224, - -0.098265156, - 0.028863123, - 0.0041721896, - -0.03187272, - -0.047210786, - 0.019018477, - -0.0031342413, - 0.010977777, - 0.00019631501, - 0.010859931, - -0.013352821, - -0.00042209146, - 0.013552251, - 0.0016747682, - 0.0160814, - -0.023551002, - 0.009953426, - 0.017821891, - 0.011775501, - -0.021665473, - 0.018084778, - 0.0057653724, - 0.010107532, - -0.014531277, - -0.018347664, - 0.022281896, - 0.014331846, - -0.0068305163, - 0.0124553805, - 0.005198807, - -0.012310339, - 0.011920542, - -0.018782785, - -0.0046775662, - 0.0008175543, - -0.019290429, - -0.00066174875, - -0.014513147, - 7.524701E-08, - 0.011331314, - -0.023387833, - 0.00893814, - -0.0146581875, - 0.0064180563, - 0.021973684, - 0.0026447286, - -0.023351572, - -0.005371043, - 0.011095623, - 0.034900445, - 0.012310339, - 0.017169207, - -0.029878408, - -0.030440442, - 0.0036078903, - -0.0061370395, - 0.019816201, - -0.0025472795, - -0.0040860716, - 0.028808733, - 2.1799501E-06, - -0.025345882, - -0.020487016, - 0.029461415, - 0.00069630926, - -0.015365262, - 0.0022673958, - -0.021883033, - -0.008861087, - 0.013506927, - 0.0029982657, - -0.018909696, - -0.0025495456, - -0.011032167, - 0.011258794, - -0.029552067, - -0.007442407, - 0.012754527, - -0.0011189673, - 0.0068259835, - 0.007854867, - -0.010062207, - 0.026234258, - -0.031002475, - -0.004027149, - -0.023297181, - -0.03723923, - 0.017151076, - 0.017667785, - 0.023569133, - -0.0018538029, - -0.022191245, - 0.01832047, - -0.016933516, - -0.038363297, - -0.016389612, - 0.007174988, - 0.0031070462, - 0.003950096, - -0.0151567655, - -0.01053359, - 0.0009580626, - 0.003009597, - -0.005407303, - -0.0052985223, - 0.003190898, - 0.022408806, - -0.01938108, - 0.0036849433, - 0.0056203315, - 0.007854867, - 0.00028498255, - 0.00042690727, - -0.026125478, - 0.0023909071, - -0.0143137155, - -0.0066582803, - 0.012156233, - -0.0070344796, - -0.0012011193, - -0.012817983, - -0.03158264, - -0.010578915, - 0.009463914, - 0.02483824, - 0.012509771, - 0.0032407558, - -0.021121569, - 0.030676134, - -0.0076554357, - 0.020178804, - 0.026016697, - -0.009187429, - 0.004061143, - -0.015845709, - -0.012174363, - 0.015963554, - -0.0018934626, - 0.0070526097, - -0.00405661, - 0.0008011239, - 0.03372199, - -0.01679754, - 0.03573443, - -0.004582383, - 0.024910761, - 0.020450756, - 0.012165299, - -0.032507274, - 0.0074967975, - -0.0040838057, - 0.007641838, - 0.010597045, - -0.0100440765, - 0.016308026, - -0.0175862, - -0.0057109823, - 0.032670446, - -0.011920542, - -0.010887126, - -0.00970867, - -0.008031636, - 0.025110193, - -0.0056883194, - 0.015401522, - 0.027322065, - -0.031618897, - -0.015764125, - 0.025182713, - -0.013026479, - -0.0006985755, - -0.0045121294, - -0.013815138, - -0.013017413, - 0.00047789817, - -0.017994126, - -0.0013404945, - 0.011186273, - -0.010578915, - 0.015138635, - 0.0014855353, - 0.024439378, - 0.029026294, - -0.005656592, - 0.005099091, - 0.009318872, - 0.0055568763, - -0.016144857, - 0.03540809, - 0.022390677, - 0.043766066, - -0.030585483, - -0.00021770287, - -0.034374673, - 0.0007303032, - -0.002690054, - 0.020142544, - 0.01663437, - -0.0012260482, - 0.03495484, - -0.036151424, - -0.012654811, - 0.00084078347, - -0.017921606, - 0.00405661, - -0.016217377, - -0.011340379, - 0.03519053, - 0.005457161, - 0.0034787133, - 0.016525589, - 0.007279236, - -0.0077823466, - -0.035988253, - -0.020595796, - 0.0107330205, - 0.0038798419, - -0.004045279, - -0.009101312, - -0.019743681, - 0.017160142, - 0.0045143953, - -0.012473511, - -0.021973684, - 0.02826483, - 0.006554032, - 0.0071976506, - -0.0007059409, - -0.01055172, - -0.010950582, - 0.023768565, - -0.010968712, - -0.030948084, - -0.009917166, - 0.009346068, - 0.007451472, - 0.033377517, - -0.015392457, - -0.019743681, - 0.0038571793, - 0.004115533, - 0.000100069665, - 0.020396365, - -0.018528964, - -0.0067172027, - 0.021883033, - 0.1460561, - -0.011222533, - 0.031183776, - -0.012672941, - -0.008226534, - -0.010379484, - -0.0073064314, - -0.007863932, - -0.022064334, - 0.0018028121, - -0.015854774, - 0.008212936, - -0.005121754, - -0.027267674, - -0.0041495273, - -0.0100440765, - 0.010687695, - -0.005788035, - -0.014912009, - 0.025255233, - -0.011376639, - -0.01853803, - -0.007184053, - 0.012845177, - 0.01842925, - 0.010578915, - 0.025019541, - -0.0112497285, - 0.0046163774, - 0.001129732, - 0.0048588673, - 0.0014164143, - -0.023496613, - -0.0027829707, - -0.017459288, - 0.0029416091, - -0.028844994, - 0.014676318, - 0.013434405, - -0.005905881, - 0.00020169739, - 0.0038526468, - -0.012654811, - -0.018411119, - -0.0016611706, - -0.0071795206, - -0.009518304, - 0.025635965, - 0.013688227, - -0.006200495, - 0.010778346, - 0.03187272, - -0.0248745, - 0.0153290015, - 0.013416275, - -0.011050297, - -0.0032634183, - -0.038363297, - 0.0006538168, - 0.009269015, - -0.04789973, - 0.018710265, - -0.009196495, - 0.0005662824, - 0.01511144, - 0.002232269, - -0.008507551, - -0.01419587, - 0.009482044, - 0.000183284, - 0.005443563, - -0.018674005, - -0.0034379207, - 0.027521495, - 0.025364013, - 0.045542818, - 0.014558472, - 0.014812293, - -0.012292209, - 0.0050311033, - 0.0066854754, - 0.046376802, - 0.044998914, - -0.03368573, - 0.020287585, - -0.01663437, - -0.00076769653, - 0.016752215, - 0.018927827, - 0.020704577, - 0.005597669, - 0.020740837, - 0.014893879, - -0.01744116, - 0.01593636, - -0.0012997017, - 0.015193026, - 0.026905071, - -0.001958051, - 0.023895474, - -0.026234258, - -0.0014152811, - -0.013715423, - 0.0126094865, - 0.009536434, - 0.02492889, - 0.029660847, - 0.022100594, - -0.011838957, - -0.009282612, - -0.0040090187, - -0.004750087, - 0.0060327915, - -0.025490925, - -0.007650903, - 0.016072337, - 0.009273548, - 0.024530029, - 0.024566289, - -0.01600888, - -0.002957473, - 0.0106605, - -0.018102907, - -0.034356546, - 0.0034424532, - 0.024022385, - 0.014295585, - 0.0070163496, - 0.021901164, - -0.023532873, - 0.0008028236, - -0.0054707583, - 0.02859117, - 0.016688759, - 0.012763592, - -0.01744116, - 0.0010668432, - 0.0075013298, - 0.007999907, - -0.011104688, - 0.0035738964, - -0.026161738, - 0.0064497837, - -0.022698889, - -0.021466041, - 0.002397706, - -0.014667253, - 0.020233193, - 0.025200842, - 0.019054737, - 0.06457943, - 0.016063271, - -0.026488079, - -0.014558472, - 0.011857087, - 0.0017699512, - 0.0036758783, - 0.023768565, - 0.025744746, - -0.016860995, - 0.020777097, - -0.004949518, - 0.026905071, - 0.004976713, - 0.01659811, - -0.0068259835, - 0.009454848, - -0.014277455, - -0.0028577573, - 0.005053766, - -0.018130103, - -0.02324279, - 0.012228754, - -0.016425872, - 0.022735149, - 0.01714201, - 0.006218625, - -0.021049049, - 0.00019858127, - -0.011068427, - -0.020668317, - 0.018175427, - 0.0012226488, - 0.011349444, - 0.034827925, - -0.0050311033, - -0.013932983, - -0.0042401776, - -0.030766783, - -0.017160142, - -0.013479731, - -0.0059693363, - -0.03201776, - 0.0009716602, - -0.00089913973, - -0.015909165, - -0.035353698, - 0.015691604, - 0.016144857, - -0.008987999, - -0.027376454, - -0.024294337, - -0.03223532, - -0.0008135883, - 0.017051362, - 0.0026447286, - -0.0087795025, - -0.025762875, - -0.0047727493, - 0.02686881, - 0.007823139, - -0.0059829336, - -0.000536821, - 0.026705641, - 0.024493769, - -0.0007359688, - -0.028137919, - 0.038254514, - -0.035933863, - 0.005008441, - 0.016770344, - 0.007605578, - 0.0175862, - -0.0014028166, - 0.014866684, - -0.027158894, - 0.02307962, - 0.012917698, - -0.009196495, - 0.0022877923, - 0.0010215179, - -0.022662628, - 0.025200842, - 0.00057591405, - 0.017903477, - -0.013425341, - 0.0004393717, - 0.02476572, - -0.0030027982, - -0.034827925, - 0.004645839, - -0.04043013, - -0.0036532157, - 0.002198275, - 0.018157298, - 0.026633121, - -0.0058968156, - 0.032325972, - -0.009645214, - -0.004292302, - -0.012500705, - -0.01153981, - -0.027594015, - 0.032761093, - 0.0038299842, - -0.0098718405, - 0.012700137, - 0.011004972, - -0.00979932, - 0.008661657, - -0.020487016, - -0.029969059, - 0.0073290938, - -0.012183429, - 0.024511898, - 0.012410055, - -0.0069302316, - 0.0020588997, - 0.029153205, - -0.0011931873, - -0.024076777, - -0.00047648174, - 0.0069800895, - -0.020885877, - -0.0032792822, - -0.0036169554, - -0.016725019, - 0.0063772635, - -0.023587262, - 0.010778346, - 0.012246884, - 0.008312652, - -0.0012033855, - 0.0077732815, - 0.011150013, - 0.030621743, - -0.010035012, - 0.004786347, - 0.007097935, - 0.00027039347, - 0.04101029, - -0.002646995, - 0.014884814, - 0.008475822, - 0.02126661, - 3.7464157E-05, - 0.010742086, - -0.027031982, - 0.0062911455, - -0.0030322596, - -0.021991814, - -0.008231066, - -0.012645747, - -0.008008973, - -0.0004577851, - -0.0018809981, - -0.0002478725, - -0.02315214, - -0.01754994, - -0.039849967, - 0.013760747, - 0.0072067156, - -0.0076690335, - -0.025599705, - 0.002889485, - 0.010542654, - 0.0037642624, - 0.018175427, - -0.031274427, - -0.01659811, - -0.015220221, - 0.032561664, - -0.0069574267, - 0.0036328193, - -0.0063455356, - -0.006277548, - -0.0030503897, - 0.0015353931, - -0.009953426, - -0.01773124, - -0.0036645469, - -0.0030662536, - -0.0013053673, - 0.024167426, - 0.019997504, - 0.0069030365, - 0.03876216, - -0.01919978, - -0.020487016, - -0.0057925675, - 0.0019251902, - -0.023369702, - 0.009024259, - -0.002062299, - -0.011431029, - -0.022191245, - -0.013225909, - -0.00086967833, - -0.039451104, - 0.005484356, - -0.023623524, - 0.006821451, - 0.018229818, - 0.012899567, - 0.00031812664, - 0.011784567, - 0.0013155655, - 0.014250261, - 0.015891034, - 0.021792384, - -0.000381582, - -0.020142544, - 0.0038662443, - -0.00014999828, - -0.0045755845, - 0.0037823927, - 0.02133913, - 0.010859931, - 0.0025200841, - 0.00018852473, - -0.011748306, - -0.027285803, - 0.0055750064, - 0.0036056242, - 0.008172143, - -0.012391925, - 0.008870153, - -0.015872905, - -0.004577851, - 0.008593668, - 0.0032362232, - 0.02819231, - 0.031419467, - -0.03383077, - 0.004419212, - -0.0059466735, - -0.00886562, - 0.008770437, - -0.021665473, - 0.0028645562, - 0.020922137, - 0.018964088, - -0.0017484217, - -0.019580511, - 0.009160235, - 0.008167611, - 0.02665125, - 0.0012441783, - -0.015292741, - 0.023623524, - -0.014204935, - 0.022354417, - -0.0045891823, - 0.00078016095, - 0.0018526699, - 0.014531277, - -0.03165516, - 0.043149643, - 0.011712046, - 0.00051075895, - 0.0030662536, - 0.00033285734, - 0.009409524, - 0.022626368, - 0.0009858243, - -0.0041631246, - -0.0029098815, - 0.018148232, - 0.020106284, - -0.03189085, - -0.010243508, - 0.0107330205, - 0.009019726, - 0.00018682504, - 0.0057835025, - -0.003802789, - -0.03209028, - -0.0035489674, - -0.0075874478, - 0.009590824, - -0.016036075, - -0.009309808, - -0.00877497, - -0.023260921, - 0.017740306, - -0.0043126983, - 0.023551002, - 0.009862776, - 0.039559882, - 0.01923604, - -0.018601485, - 0.0089336075, - -0.014431561, - -0.012582291, - 0.030331662, - 8.5976346E-05, - 0.021665473, - 0.0044758692, - 0.02133913, - 0.0067625283, - -0.00014319948, - -0.012591356, - -0.01600888, - 0.02115783, - 0.012591356, - 0.01846551, - 0.026741901, - 0.011884282, - -0.015773188, - -0.018302338, - 0.0044169463, - 0.012083713, - 0.0011353977, - 0.041191593, - -0.02298897, - -0.020142544, - -0.008693384, - 0.027430845, - -0.0011614597, - 0.012074648, - -0.008548344, - -0.0008039567, - 0.0063047432, - 0.0012464445, - -0.015655342, - 0.012246884, - 0.013787943, - 0.01241912, - 0.0045529217, - -0.02110344, - -0.011784567, - 0.00037874916, - 0.015464977, - -0.01941734, - -0.011122818, - -0.020722708, - 0.0031818328, - -0.002717249, - 0.010461069, - 0.008240132, - 0.025672225, - 0.0035670977, - 0.004818075, - 0.0048588673, - -0.022046205, - 0.0080135055, - -0.01832047, - 0.0052894573, - -0.0070662075, - -0.008743241, - -0.013071803, - 0.00095579633, - 0.0033721991, - 0.0021268877, - -0.018066647, - 0.01956238, - 0.00045041973, - -0.005008441, - 0.013443471, - -0.031147515, - -0.018229818, - 0.010497329, - -0.0012385126, - 0.00065325026, - -0.01056985, - 0.0026537937, - -0.015102375, - -0.02855491, - 0.0067625283, - 0.003941031, - -0.0020067757, - 0.029860279, - -0.0065494995, - 0.01056985, - 0.011721111, - -0.0062050275, - -0.007768749, - 0.017305182, - 0.0028577573, - 0.017114816, - 0.013534121, - 0.006010129, - 0.020922137, - 0.023424093, - 0.022154985, - 0.024113037, - -0.00791379, - -0.0011909211, - 8.556027E-06 - ], - "HOTEL7_VECTORIZE_DESCRIPTION": [ - -0.015571611, - -0.018019864, - 0.01613867, - -0.012754319, - 0.00879391, - 0.007317757, - 0.0046489807, - 0.049145084, - -0.009315964, - 0.004331698, - -0.008573387, - -0.003971661, - 0.028082905, - -0.0018508164, - 0.01913598, - 0.023240404, - -0.025814671, - -0.022430321, - -0.0023717454, - -0.008748905, - -0.016480705, - 0.019315999, - -0.032295343, - -0.02252033, - 0.0027047799, - 0.013933442, - -0.032817394, - -0.027704867, - 0.00038366468, - -0.013420388, - 0.012601304, - -0.016444702, - 0.012970341, - 0.0040076645, - -0.00880291, - -0.0014997801, - -0.016768735, - 0.020594131, - 0.027866883, - -0.0164267, - 0.022646343, - 0.02387047, - -0.009306963, - -0.018883953, - 0.0018181881, - -0.014806531, - 0.0018181881, - 0.03510363, - -0.011971238, - 0.019460013, - -0.0034293549, - -0.008937924, - 0.01468952, - -0.028946994, - -0.014869538, - 0.008046833, - 0.0020927165, - -0.036867812, - 0.028784977, - 0.0048785047, - 0.03180929, - 0.009964031, - 0.012367279, - -0.00041488666, - -0.010621099, - -0.01440149, - -0.004106675, - 0.0127633205, - 0.0052430425, - -0.0063096527, - 0.044392593, - -0.011062144, - -0.02648074, - 0.0035936218, - -0.0012488792, - -0.013771425, - -0.013843432, - -0.020432113, - 0.008973928, - 0.0396401, - -0.009694003, - -0.03227734, - -0.010270063, - -0.005558075, - -0.01179122, - -0.0033798497, - -0.000961412, - -8.5790125E-05, - 0.009171949, - 0.030531159, - 0.0054095597, - 0.023762459, - 0.006755199, - 0.007335759, - 0.017668828, - -0.008042332, - -0.010684106, - -0.01622868, - 0.009144946, - 0.011377177, - 0.042700417, - -0.028928993, - 0.016804738, - 0.0032313343, - 0.012106252, - -0.021692244, - 0.031755283, - -0.015994655, - -0.01102614, - 0.013411388, - 0.015265579, - -0.021692244, - -0.023942476, - 0.031215228, - -0.017749837, - 0.0075292788, - -0.023330413, - 0.02378046, - -0.019586027, - -0.010036038, - 0.013267373, - -0.027794875, - 0.02988309, - 0.008451874, - -0.016588716, - -0.0062106424, - -0.026318723, - 0.010783115, - -0.0164267, - -0.03267338, - 0.04601276, - -0.007898317, - -0.025166603, - 0.015688622, - 0.015427596, - 0.00357787, - -0.015985653, - 0.0063591576, - -0.020612132, - -0.008073836, - 0.0328534, - -0.007695796, - 0.0055895783, - 0.0029973101, - 0.026714763, - -0.0076192883, - -0.005549074, - 0.018721936, - -0.04147629, - 0.019063972, - -0.001778809, - -0.0024437527, - 0.0077363, - -0.014221471, - -0.00860489, - -0.006408663, - 0.019334, - -0.0076777944, - 0.01508556, - 0.022790357, - 0.003856899, - -0.001256755, - -0.006899214, - 0.016039658, - 0.008910921, - 0.017056765, - -0.015706625, - -0.01372642, - -0.014959548, - 0.006417664, - 0.005441063, - 0.023168396, - 0.019928062, - 0.028784977, - 0.05072925, - 0.0145275025, - 0.0017495559, - -0.03546367, - 0.0063816602, - 0.00889742, - 0.007160241, - 0.00030265632, - 0.041152257, - 0.0037938925, - 0.0154636, - -0.0072457497, - -0.017902851, - 0.011062144, - -0.0016955504, - 0.025364624, - -0.0040099146, - -0.012286271, - -0.037659895, - -0.039316066, - 0.0141404625, - -0.017677829, - -0.011827224, - -0.016669724, - 0.0099730315, - -0.024086492, - 0.0049550124, - -0.030369142, - -0.005211539, - -0.0056975894, - 0.017425803, - -0.024284512, - -0.01575163, - 0.011359175, - -0.008078336, - -0.022484327, - -0.01440149, - 0.022916371, - 0.0028195416, - 0.022016278, - -0.012844329, - -0.00059912447, - -0.025202608, - -0.0029253026, - -0.0117732175, - 0.004534219, - 0.0038433976, - -0.020036073, - 0.018298892, - -0.020720143, - -0.024896575, - 0.0145275025, - -0.0046489807, - 0.0021793505, - 0.0044554607, - -0.0019869555, - -0.018001862, - -0.0043159463, - -0.0071107354, - -0.003886152, - 0.024698555, - 0.023078388, - 0.0027812878, - 0.0033573473, - -0.005684088, - 0.011080146, - -0.0061341347, - -0.016408697, - -0.019874057, - -0.037875917, - 0.020936165, - 0.004525218, - 0.022664344, - 0.023312412, - 0.00957699, - -0.03139525, - -0.007902818, - -0.00029365538, - 0.009703004, - -0.015967652, - -0.010180053, - 0.026426734, - -0.0376959, - 0.004675984, - -0.008541884, - 0.024734559, - -0.032511365, - -0.020666137, - 0.051845364, - 0.01478853, - 0.006989223, - 0.01285333, - -0.013015347, - 0.022016278, - -0.01044108, - -0.023762459, - 0.013888436, - -0.0053285514, - 0.019550022, - -0.021314206, - 0.022682346, - 0.0021332207, - 0.0031773287, - -0.015832638, - -0.018865952, - 0.007412267, - -0.044428594, - -0.049613133, - 0.0560938, - 0.0044127065, - 0.011170155, - -0.0046444805, - -0.0044599613, - -0.01034207, - -0.0063816602, - 0.0063546575, - -0.019676035, - 0.00811434, - -0.030513156, - 0.0033685984, - -0.005733593, - -0.0058911094, - 0.044212572, - -0.025148602, - 0.039316066, - -0.0063591576, - 0.021422217, - 0.006777701, - 0.015715625, - -0.006368159, - -0.023906473, - 0.011962238, - 0.0051350314, - 0.0141404625, - 0.0023537434, - 0.0046062265, - -0.018919958, - 0.010585095, - 0.0012049996, - -0.020630134, - -0.006408663, - 0.020594131, - -0.021494223, - 0.016084664, - -0.0541496, - -0.039496087, - 0.024248509, - 0.005724592, - 0.012673311, - -0.01527458, - -0.01179122, - -0.014779529, - 0.027128806, - 0.004464462, - -0.0028285426, - -0.024914578, - 0.03711984, - 0.012412284, - 0.0066291858, - 0.029793082, - -0.004437459, - 0.015364589, - 0.009468979, - 0.034545574, - 0.0017371797, - -0.010738111, - 0.017380798, - -0.03557168, - -0.021980274, - 0.0025675157, - -0.005945115, - -0.016192675, - -0.005733593, - -0.018118875, - 0.033411454, - 0.034473564, - 0.034779597, - -0.009694003, - -0.017029762, - 0.01962203, - 0.008424872, - 0.007844311, - 0.009378971, - -0.013024347, - -0.035535675, - -0.003994163, - 0.0019183235, - -0.005189037, - 0.00927996, - -0.0051800357, - 0.0010671729, - 0.041296273, - 0.005724592, - 0.026282718, - -0.00047901832, - 0.00071332377, - -0.033321448, - -0.019676035, - -0.0017675578, - -0.030387143, - 0.010351071, - 0.0077363, - -0.002736283, - 0.0033033418, - 0.011395179, - -0.030117115, - 0.018919958, - 0.02010808, - -0.013762424, - -0.020018071, - 0.02282636, - -0.0084563745, - -0.0027272822, - 0.002950055, - -0.00918995, - -0.009730007, - 0.0083168605, - 0.005657085, - -0.014239473, - 0.019586027, - -0.0022581087, - 0.006255647, - 0.022862365, - 0.003933407, - 0.02822692, - -0.005549074, - 0.0074887746, - -0.010954133, - -0.0035126135, - -0.021854261, - 0.008946925, - -0.020612132, - -0.030027106, - -0.013384384, - 0.005441063, - -0.024104493, - 0.029217022, - -0.023942476, - 0.0023514933, - 0.014950546, - -0.024824567, - -0.0016899249, - -0.00011462123, - -0.020324102, - -0.013465393, - -0.02495058, - -0.012124254, - 0.012781322, - 0.008708401, - -0.016408697, - 0.0036768804, - 0.022934372, - -0.0002414781, - -0.0043069455, - -0.05519371, - -0.037551884, - -0.0029208022, - -0.015913647, - -0.008969428, - -0.03468959, - -0.0123762805, - 0.014671518, - -0.023672448, - -0.015697625, - 0.016003655, - 0.0017439304, - -0.0034293549, - -0.031827293, - 0.0011194908, - 0.0025585147, - 0.013987447, - 0.010324068, - 0.023150396, - 0.03440156, - -0.001180247, - -0.0077678035, - 0.008460876, - 0.015931647, - -0.013168362, - 0.00908644, - -0.014446494, - -0.010135048, - 0.034581576, - 0.0038321465, - 0.011467186, - -0.006179139, - 0.025256613, - 0.01944201, - 0.010396075, - -0.0150945615, - 0.041440286, - -0.018145878, - -0.003150326, - 0.018685933, - -0.010288064, - -0.004698486, - -0.022592338, - 0.0061611375, - 0.016111666, - 0.0016944252, - 0.016255682, - -0.008919923, - -0.00060531264, - -0.0068407077, - 0.0222323, - -0.025760666, - -0.0025270113, - 0.0082088495, - 0.03249336, - 0.0032898404, - -0.010153051, - -0.64057827, - -0.019297997, - -0.007025227, - 0.006786702, - 0.0024415026, - 0.0007515777, - 0.008235852, - -0.018451909, - 0.088569164, - -0.00046326668, - -0.006021623, - -0.040612202, - -0.0145635065, - 0.008420371, - 0.0023739955, - 0.0045387195, - 0.0030918198, - -0.0022007276, - 0.026570749, - -0.006552678, - 0.019928062, - -0.026264718, - -0.010909129, - 0.009793013, - -0.018055867, - 0.022412319, - -0.009874022, - -0.0056795874, - -0.017038763, - 0.015589613, - 0.0014491499, - 0.0109631345, - 0.0039851624, - -0.018451909, - -0.009315964, - -0.003528365, - 0.012331275, - -0.0004888631, - 0.022898369, - -0.0054635652, - -0.004099924, - -0.020666137, - -0.050333206, - -0.009441976, - 0.015922647, - -0.004630979, - -0.014068455, - 0.0069982237, - 0.007839811, - -0.00986502, - -0.019514019, - 0.01671473, - 0.004464462, - 0.025382625, - -0.0039874124, - -0.0036228749, - -0.002659775, - 0.0057110908, - -0.030855192, - -0.008289858, - 0.006206142, - -0.01072911, - -0.0028645464, - 0.0020240843, - 0.0055715763, - 0.0031278236, - 0.029451046, - 0.0024099993, - -0.017812843, - 0.012970341, - -0.004531969, - 0.020360107, - 0.025202608, - 0.03209732, - 0.032745387, - 0.003152576, - -0.001488529, - 0.017650826, - 0.00021180316, - -0.002466255, - 0.014977549, - 0.012106252, - -0.0027722868, - 0.014554505, - -0.0025495137, - 0.013087354, - 0.02010808, - -0.0309272, - 0.23128793, - -0.0076597924, - -0.014716523, - 0.18952361, - -0.006044125, - -0.020756148, - 0.0047794944, - 0.00763729, - -0.018937958, - -0.000753828, - -0.00037775782, - 0.0027092802, - 0.025292616, - 0.021242198, - 0.0029658068, - 0.018334897, - 0.0025495137, - 0.002058963, - 0.02145822, - 0.019370005, - 0.008645394, - 0.002812791, - -0.005936114, - -0.027110804, - 0.02079215, - 0.001526783, - 0.020666137, - -0.02145822, - -0.0013715168, - -0.020450115, - 0.009667, - 0.0022671095, - 0.006930717, - -0.034563575, - 0.0027092802, - 0.0013591406, - 0.0010418578, - -0.010756113, - -0.0037623893, - -0.00028563893, - 0.017092768, - -0.009288961, - 0.0033595976, - -0.0072277477, - -0.007947822, - 0.016417699, - -0.00898743, - -0.021368211, - 0.003355097, - 0.0055535743, - 0.01730879, - 0.021800255, - 0.023996482, - 0.00045707854, - -0.005819102, - 0.007452771, - 0.010126048, - 0.0075967857, - 0.02822692, - 0.030261131, - 0.0059676175, - -0.004419457, - 0.023924476, - 0.02329441, - 0.013789427, - -0.015229575, - -0.0047299895, - -0.004675984, - -0.009946029, - -0.013357381, - -0.0057200915, - -0.023528434, - 0.009333965, - -0.00069757213, - 0.002211979, - -0.0027835378, - -0.012133255, - 0.00041038622, - -0.024680553, - -0.004572473, - 0.021710245, - -0.008919923, - 0.021836258, - -0.00377139, - 0.028478947, - -0.004534219, - 0.007326758, - -0.009018933, - 0.01788485, - -0.016129669, - 0.043852538, - -0.03373549, - -0.0037173845, - -0.046444803, - 0.0044712126, - -0.02957706, - -0.005918112, - 0.018163878, - 0.010945132, - -0.0070432285, - 0.002531512, - 0.0055040694, - -0.0037758907, - 0.014716523, - 0.0062916507, - -0.030891195, - -0.018145878, - 0.0046084765, - 0.018685933, - 0.0068047037, - -0.0049730144, - 0.011125151, - -0.016696727, - 0.0012927587, - -0.01141318, - 0.0062466464, - 0.017713832, - 0.016003655, - -0.0034068525, - 0.015121564, - -0.008199848, - 0.006971221, - 0.0064041624, - 0.0019565774, - -0.020162085, - 0.009005432, - 0.054293618, - -0.002774537, - -0.0016100416, - 0.026642757, - -0.013888436, - 0.012907336, - 0.025184605, - 0.0109631345, - -0.0106301, - 0.013375384, - -0.0055715763, - 0.0012004991, - -0.023618443, - 0.020612132, - -0.024014484, - -0.01411346, - -0.008928924, - -0.016669724, - -0.0069352174, - -0.011044143, - -0.009252957, - -0.041908335, - 0.017992862, - 0.007286254, - 0.0024932579, - -0.016993757, - -0.006003621, - 0.020774148, - 0.0023064886, - -0.013987447, - -0.021764252, - -0.005985619, - 0.022898369, - -0.028640963, - -0.010675104, - 0.013978446, - -0.001720303, - 0.0036408766, - -0.006557178, - -0.0027092802, - 0.0042596906, - 0.011368176, - 0.00590011, - -0.009901024, - -0.005855106, - -0.0011926234, - -0.016120669, - 0.022448322, - -0.011395179, - -0.027668862, - 0.048389006, - -0.016759735, - -0.0956979, - 0.01440149, - 0.009378971, - -0.022142291, - -0.047488913, - 0.009910025, - 0.013420388, - 0.0031975808, - 0.022142291, - 0.0071017346, - -0.0028735471, - -0.020630134, - 0.0025000086, - 0.021854261, - 0.012313274, - -0.0145275025, - -0.015427596, - 0.008289858, - 0.021152189, - 0.0060666273, - 0.02360044, - -0.010144049, - 0.016597716, - -0.00348111, - -0.0023627444, - 0.021296203, - -0.027398834, - -0.024032487, - 0.025040591, - 0.0065976824, - 0.0072322483, - 0.016678724, - -0.023438424, - -0.0021320956, - 0.025652654, - 0.0063636582, - 0.0038546487, - -0.009113443, - -0.017920854, - -0.0091269445, - 0.0045162174, - 0.017803842, - -0.013447391, - -0.009207953, - 0.00821785, - 0.008811912, - -0.026228713, - -0.003827646, - -0.002677777, - 0.015220574, - -0.010297066, - 0.022142291, - -0.008789409, - 0.0069262167, - 0.009919026, - -0.0016674225, - 0.0136094075, - 0.0044914647, - -0.007848812, - 0.017371798, - -0.0007341384, - -0.024446528, - -0.009405973, - -0.0011155528, - 0.019388005, - 0.0057290928, - -0.0032628374, - -0.027956892, - -0.015553609, - -0.004207935, - 0.0155176055, - 0.005346553, - 0.0045454702, - -0.0056075803, - 0.045076665, - -0.0022896118, - -0.0025157603, - 0.017560817, - 0.005684088, - -0.025886677, - -0.004581474, - 0.0006930717, - 0.03661579, - -0.015796633, - 0.006255647, - -0.013033348, - -0.028352933, - 0.036867812, - -0.007974825, - -0.0016089164, - 0.0071962443, - -0.02117019, - 0.027650861, - -0.022880366, - -0.027038798, - 0.003751138, - -0.0109271305, - -0.0038659, - 0.0030963202, - 0.0019678285, - 0.004079672, - 0.012502293, - -0.002929803, - -0.010558092, - -0.0024865072, - 0.004108925, - 0.019225989, - 0.0013636411, - -0.0034766097, - -0.021404214, - 0.012313274, - 0.010900128, - 0.01141318, - -0.004493715, - -0.004106675, - 0.0105760945, - -0.01150319, - 0.018316895, - -0.018811947, - 0.020162085, - 0.00079770753, - -0.020072076, - -0.023690451, - -0.005724592, - 0.02280836, - 0.0008421496, - 0.0034676087, - 0.004081922, - 0.016030658, - 0.01411346, - 0.0029748078, - 0.0006030624, - -0.0006497547, - 0.01102614, - -0.010621099, - 0.0023222403, - 0.009504983, - 0.003971661, - 0.0052025383, - 0.017461807, - 6.6627986E-06, - 0.045400698, - 0.02543663, - 0.01855992, - -0.019063972, - 0.015886644, - 0.051485326, - -0.012286271, - -0.0027002792, - 0.018055867, - 0.018865952, - 0.005963117, - 0.0014030201, - -0.0068317065, - 0.012439286, - -0.022358313, - 0.0059586163, - 0.017236782, - 0.013375384, - 0.023186399, - -0.032511365, - -0.031773288, - 0.013807428, - -0.03211532, - 0.001768683, - 0.019243991, - -0.010324068, - -0.008339362, - 0.020252096, - -0.018811947, - 0.0010328569, - -0.025922682, - 0.0076777944, - 0.018541917, - 0.004169681, - -0.01653471, - 0.015328586, - 0.0045004655, - -0.0018091871, - 0.015931647, - 0.00947798, - -0.013420388, - 0.015571611, - 0.011449184, - -0.020414112, - 0.016705727, - 0.028982999, - -0.0270748, - 0.023168396, - 0.014860537, - 0.0055940785, - -0.025688658, - 0.02309639, - -0.0008669022, - -0.016174674, - -0.0034743594, - 0.009612994, - 0.03510363, - 0.027776873, - 0.037479877, - -0.014977549, - -0.015148567, - -0.0022704848, - -0.0010739235, - -0.021008173, - 0.013429389, - -0.009243956, - 0.0021996025, - 0.009072939, - -0.004475713, - 0.005751595, - -0.0018643178, - -0.006755199, - 0.0012511294, - 0.012673311, - -0.000715574, - 0.032529365, - 0.0077272994, - 0.02280836, - 0.0048785047, - 0.0040166653, - 0.016912749, - -0.0060081217, - -0.015850639, - 0.022844363, - 0.0036386263, - 0.010072042, - 0.006651688, - -0.01333938, - -0.010522088, - 0.029703073, - -0.0004559534, - -0.0299731, - -0.04194434, - 0.019496016, - 0.0010463583, - 0.029271027, - -0.013843432, - -0.0037781408, - 0.03701183, - -0.012187261, - -0.0014468997, - 0.0034653584, - -0.0015909146, - 7.53828E-05, - 0.009162948, - 0.12586902, - -0.012232265, - 0.019297997, - -0.0029455547, - 0.029055005, - -0.0042214366, - -0.00405942, - 0.0020083326, - -0.023906473, - 0.001135805, - -0.011764217, - 0.009603993, - -0.0053510536, - -0.024248509, - 0.010603097, - 0.0054590646, - 0.0040954235, - 0.0013433889, - -0.0023424923, - 0.023996482, - 0.0075517814, - -0.0036611287, - -0.022790357, - 0.009158447, - 0.020918164, - 0.0056885886, - -0.010432079, - 0.009153947, - 0.000104706145, - 0.022322308, - -0.021782253, - 0.030675173, - 0.0014997801, - 0.014761527, - -0.0058011003, - 0.010756113, - -0.026354726, - -0.0073897643, - 0.014059454, - -0.008181847, - -0.024824567, - -0.014365486, - 0.012106252, - -0.019676035, - 0.0020420863, - -0.019388005, - -0.00045539087, - 0.005018019, - 0.018280892, - -0.014833534, - 0.0114221815, - 0.035139635, - -0.02774087, - 0.013384384, - 0.006255647, - 0.009757009, - -0.009784012, - -0.01855992, - 0.01701176, - -0.002821792, - -0.021224195, - -0.017677829, - -0.011935235, - 0.006197141, - 0.00405717, - 0.014257475, - -0.026804773, - -0.0057560955, - -0.0053690556, - 0.008240352, - -0.01044108, - -0.02021609, - 0.004995517, - 0.01817288, - 0.020324102, - 0.04100824, - 0.0030828188, - 0.01537359, - -0.010747111, - -0.0073402594, - -0.0061701383, - 0.004417207, - 0.038920026, - -0.0014547755, - 0.014419491, - -0.0047029867, - -0.0114221815, - -0.016732732, - -0.002522511, - 0.040936235, - -0.020648137, - 0.004716488, - 0.010270063, - -0.014464497, - 0.008438373, - 0.009405973, - 0.01034207, - 0.017101768, - -0.011323172, - 0.026444735, - 0.0118452255, - -0.014707522, - 0.022448322, - -0.021818258, - 0.013528399, - 0.025508638, - 0.0062691486, - 0.018469911, - -0.015490603, - 0.0011059894, - -0.017803842, - 0.0021422217, - -0.01729979, - -0.0033888505, - 0.027992895, - -0.0079973275, - -0.0041899337, - -0.0030873194, - 0.028154913, - -0.00947798, - 0.0040864227, - 0.006872211, - -0.008978428, - -0.0017338044, - -0.023438424, - 0.036561783, - -0.030765183, - 0.0041606803, - 0.007695796, - -0.012457289, - -0.011035142, - 0.012061248, - 0.0010885501, - 0.027308825, - 0.0022052282, - 0.0042011845, - 0.007412267, - 0.031017208, - -0.002290737, - -0.00947798, - -0.003064817, - -0.008271855, - 0.00091078173, - -0.0060171224, - -0.012700314, - -0.024140498, - -0.009270959, - -0.013492396, - -0.004743491, - 0.022610338, - 0.065490775, - 0.0032605873, - 0.00068969635, - -0.0029545557, - -0.017623823, - 0.0106301, - -0.0088794185, - -0.018541917, - 0.038523987, - -0.017029762, - -0.0056480845, - 0.005067524, - -0.025220608, - -0.012394282, - 0.0007459522, - -0.0014480248, - -0.0059496155, - 0.00030012478, - 0.000449484, - -0.0018001862, - -0.003267338, - 0.0063771596, - 0.009113443, - -0.021026175, - 0.011278166, - -0.009883022, - -0.00376914, - -0.0046444805, - 0.006899214, - 0.00947798, - -0.015985653, - 0.011035142, - -0.0029658068, - -0.039172053, - 0.035607684, - 0.0013816429, - 0.0032020812, - -0.009603993, - -0.037515882, - -0.0013546401, - -0.009468979, - -0.017542815, - -0.021782253, - 0.003721885, - 0.018163878, - 0.0052925474, - -0.058362037, - -0.0058911094, - 0.031179225, - 0.00089390494, - -0.00879841, - -0.0024302513, - -0.02203428, - -0.01749781, - 0.014779529, - 0.041404285, - 0.020576129, - -0.036453772, - 0.02205228, - 0.008708401, - 0.018505914, - 0.022142291, - 0.0056075803, - 0.0006795703, - 0.022196297, - 0.003663379, - -0.0136454115, - 0.039532088, - -0.0008235852, - -0.008618391, - 0.015103563, - 0.015625617, - 0.02271835, - 0.0023177397, - 0.025814671, - -0.026318723, - 0.008933424, - 0.010558092, - 0.014446494, - -0.02203428, - -0.020342104, - 0.003557618, - 0.016264683, - -0.0042214366, - -0.008046833, - -0.00473899, - 0.00091584475, - -0.008622892, - 0.012538297, - 0.0069757216, - -0.00608913, - 0.013366383, - -0.032817394, - 0.0047029867, - 0.023906473, - 0.015571611, - 0.006300652, - 0.025670655, - 0.0017799342, - 0.006431165, - -0.004273192, - -0.011566197, - -0.024806567, - 0.025184605, - -0.009775011, - -0.008442873, - -0.008946925, - 0.002137721, - 0.007115236, - 0.015346588, - -0.022430321, - -0.010702107, - 0.01392444, - -0.007025227, - 0.004698486, - -0.002211979, - -0.020414112, - -0.023366418, - 0.02262834, - -0.015742628, - -0.009522985, - -0.008744405, - -0.011917233, - -0.00251351, - 0.040360175, - -0.00802883, - -0.002137721, - 0.027146809, - -0.014518502, - 0.020414112, - 0.004311446, - -0.0105760945, - -0.030261131, - 0.02639073, - 0.0118452255, - -0.006710194, - 0.007911818, - 0.0089154225, - -0.0011290543, - 0.005724592, - 0.02039611, - -0.0031368246, - 0.00074370194, - 0.0018901955, - 0.0026237713, - -0.007394265, - 0.008546384, - -0.019766044, - 0.00956799, - 0.0061656376, - -0.029361038, - 0.0017529313, - -0.008780409, - 0.00028999874, - -0.009414974, - -0.0060756286, - 0.023186399, - -0.011377177, - -0.008838914, - 0.010027037, - -0.036003724, - 0.021242198, - 0.016786737, - -0.005171035, - 0.009117943, - -0.0039379075, - -0.00040054144, - 0.020288099, - -0.008231351, - -0.010171052, - 0.006539176, - 0.026876781, - -0.0057740975, - 0.038595993, - -0.0035508673, - -0.010018037, - -0.0011768717, - -0.007376263, - -0.00889742, - -0.01817288, - -0.03308742, - 0.0154455975, - 0.00043992052, - -0.0058236024, - 0.03306942, - 0.002252483, - 0.010306066, - -0.01944201, - -0.019496016, - -0.0024685054, - -0.05519371, - -0.018451909, - 0.016957754, - 0.020378107, - -0.014671518, - 0.018865952, - -0.011575198, - -0.007371763, - -0.007223247, - -0.0074707726, - -0.025670655, - -0.0136814155, - 0.01730879, - -0.0014097708, - -0.013366383, - 0.022898369, - 0.0046039764, - -0.0033100925, - 0.009378971, - 0.012925337, - 0.0076012863, - -0.010585095, - 0.0047704936, - -0.006971221, - -0.0026057696, - -0.016318688, - -0.016561713, - -0.0031390747, - 0.00037522631, - -0.010675104, - 0.0105760945, - -0.018523917, - -0.019694038, - -0.020702142, - -0.00074201426, - -0.03161127, - 0.013852433, - 0.013141359, - -0.023762459, - -0.012250267, - 0.004030167, - 0.008357365, - 0.014482498, - -0.032331344, - 0.0077948063, - 0.010225058, - 0.007920819, - -0.022970377, - -0.05299748, - -0.0077227987, - -0.0212782, - -0.0003676318, - -0.011755216, - -0.0062466464, - -0.014905542, - 0.029037004, - 0.04205235, - -0.014680519, - -0.03888402, - 0.038127944, - 0.010162051, - 0.0026642757, - -0.007605787, - 0.0015717876, - -0.014077457, - 0.017938856, - -0.014725523, - 0.008775908, - 0.0018879453, - -0.0062691486, - 0.0060756286, - -0.023636445, - -0.014293479, - 0.024050487, - -0.035139635, - 0.0071017346, - 0.031863295, - -0.0011644955, - 0.011935235, - -0.028406939, - -0.02435652, - 0.016471704, - 0.027992895, - -0.0034428563, - -0.027668862, - -0.01246629, - -0.006836207, - -0.00077858055, - 0.013519399, - 0.014050454, - 0.021512225, - 0.03006311, - -0.010027037, - -0.015535607, - -0.0040279166, - 0.015724627, - 0.026354726, - 0.021044176, - 0.01111615, - -0.007259251, - -0.022304308, - 0.0013996448, - 0.001126804, - 0.027776873, - 0.020126082, - -0.0087399045, - 0.01498655, - -0.0026417733, - 0.00085058797, - -0.011854227, - 0.009297961, - -0.0067236954, - -0.015787633, - 0.01777684, - 0.015535607, - -0.0010851747, - 0.009050436, - -0.0027205315, - -0.012061248, - 0.026894782, - 0.01247529, - -0.0109271305, - -0.0106391, - 0.03684981, - -0.021998275, - -0.02010808, - -0.004302445, - 0.022286305, - 0.009892023, - -0.0015875392, - -0.014041453, - -0.020900162, - 0.008784909, - 0.006948719, - -0.004106675, - -0.010981136, - 0.01363641, - 0.035913713, - -0.012385281, - -0.008555385, - 0.0036903818, - 0.014941545, - 0.010477084, - -0.009964031, - -0.00017214281, - -0.02937904, - -0.020864159, - 0.006467169, - 0.018154878, - 0.0072727525, - 0.03308742, - -0.029271027, - -0.0052520433, - -0.025004586, - -0.00014964047, - 0.03877601, - -0.0004899882, - 0.020324102, - 0.014581508, - 0.0108551225, - 0.0020702141, - 0.01720978, - 0.006071128, - 0.008393369, - -0.015148567, - 0.0013985196, - 0.03132324, - -0.02784888, - 0.010234059, - -0.029037004, - -0.016210677, - -0.00705673, - -0.018253889, - -0.0034856105, - -0.047704935, - 0.009270959, - -0.009531986, - 0.030099114, - 0.0076417904, - 0.015616615, - -0.0028240422, - 0.0132943755, - -0.0106391, - -0.026552746, - 0.0024910078, - -0.013330379, - 0.0109271305, - 0.0044149566, - 0.033195432, - 0.0019880806, - 0.0007645166, - -0.0041899337, - 0.00019745792, - 0.014320482, - 0.021350209, - 0.052241404, - -0.024824567, - 0.02010808, - 0.0041921837 - ], - "HOTEL8_VECTORIZE_DESCRIPTION": [ - -0.011193806, - -0.024631938, - 0.033998754, - 0.003649348, - -0.011583318, - 0.0077670366, - 0.028508501, - 0.005698918, - 0.009046858, - -0.001775985, - -0.017082844, - 0.0063851997, - 0.008944844, - 0.011731703, - 0.013966754, - 0.020773925, - 0.026950458, - -0.013382488, - -0.005963229, - 0.00041646385, - -0.019382814, - -0.01020148, - -0.022239229, - -0.005587629, - 0.0020692777, - -0.001292574, - 0.0064037475, - -0.0024738591, - -0.0022072294, - 0.009032947, - 0.011397836, - -0.022647288, - 0.026394013, - -0.0066680587, - -0.032551996, - 0.0040365406, - 0.018427584, - -0.0084208585, - 0.00441214, - 0.0011905591, - 0.012983703, - 0.012093391, - -0.042401064, - -0.0077994955, - -0.017518725, - -0.012918784, - 0.011731703, - 0.01436554, - -0.0035357405, - 0.0066355993, - -0.009867614, - -0.010720829, - 0.011240177, - -0.007187407, - 0.0025086368, - -0.00882428, - -0.002146948, - -0.038468856, - 0.01591431, - -0.02292551, - 0.026282724, - 0.012575643, - 0.0036215256, - -0.021311821, - 0.005573718, - -0.011824444, - 0.0320141, - 0.012807495, - 0.00053644716, - -0.0032969331, - 0.020069094, - 0.008624888, - -0.012918784, - 0.008991214, - -0.0064686663, - 0.029398812, - 0.0032575182, - -0.005796296, - -0.0010983981, - 0.021682784, - 0.0053975107, - 0.0035774738, - 0.006626325, - -0.007442444, - -0.023240827, - -0.009311169, - -0.041955907, - 0.002916696, - 0.0067237034, - 0.02882382, - 0.016146163, - 0.01846468, - 0.017611464, - 0.02442791, - -0.00730797, - -0.00718277, - -0.014133688, - -0.015812295, - 0.028360117, - -0.02470613, - -0.009338992, - 0.003960029, - -0.017898962, - -0.014532473, - 0.021181984, - -0.024873065, - 0.033757627, - -0.015450606, - -0.022072295, - 0.011778073, - 0.029473005, - -0.0081704585, - 0.0049709035, - 0.019364266, - -0.0029329257, - -0.001449074, - -0.007117851, - 0.00054514164, - 0.0012311332, - 0.0076464736, - 0.003985533, - -0.017481629, - -0.006018874, - -0.0041292813, - 0.009747051, - 0.006579955, - 0.017472355, - -0.019902162, - -0.015552621, - -0.011101066, - 0.004442281, - 0.015997777, - -0.0069184587, - 0.0030210293, - 0.007785585, - 0.00031995552, - -0.009543021, - -0.0016333961, - -0.0062553626, - -0.014560295, - 0.028081894, - -0.0026454295, - 0.008940207, - 0.008397673, - -0.013855466, - 8.600254E-05, - 0.0054485183, - 0.03731887, - -0.003860333, - 0.04021238, - -0.0057591996, - 0.011982103, - 0.01971668, - -0.02363034, - -0.02841576, - -0.018446133, - 0.008267837, - 0.01982797, - -0.0134288585, - 0.033386663, - -0.026171435, - -0.0027938145, - -0.017583642, - 0.011267999, - 0.031698782, - -0.0062275403, - 0.027710931, - -0.031847168, - -0.011332918, - 0.01816791, - 0.0037073109, - 0.016109066, - 0.015997777, - 0.034017302, - 0.018844917, - 0.01361434, - -0.0063712886, - -0.04125108, - -0.027636738, - -0.012584917, - 0.0046602217, - -0.0046138517, - 0.033646338, - 0.026950458, - 0.01156477, - -0.0016310776, - 0.004423733, - 0.02181262, - -0.00031763702, - 0.008940207, - -0.017611464, - -0.0018223554, - -0.031364918, - 0.011462755, - -0.0031485478, - -0.02622708, - -0.018093716, - 0.01165751, - -0.018000977, - -0.023556147, - -0.0072708735, - -0.0112123545, - 0.021256177, - 0.011054696, - -0.009923259, - -0.0011638962, - 0.0012311332, - 0.012306696, - 0.02190536, - 0.005689644, - -0.02470613, - -0.00034516942, - 0.0062460885, - 0.033497952, - -0.004495607, - 0.007368251, - -0.026486754, - 0.032069746, - -0.021571495, - 0.0010642, - 0.013317569, - 0.02151585, - 0.01725905, - -0.0067376145, - -0.020087643, - 0.05122998, - 0.0028216369, - 0.00373977, - 0.0037838218, - 0.01941991, - -0.00793397, - -0.014690132, - -0.013308295, - 0.010526073, - 0.031068146, - 0.010331318, - 0.026338369, - 0.014625214, - -0.020477153, - 0.021348916, - -0.009645036, - -0.02301825, - -0.010247851, - -0.022072295, - 0.0052073924, - 0.014894161, - 0.025077095, - 0.018882014, - -0.0049662665, - -0.020532798, - -0.008049896, - 2.4942186E-05, - 0.020365866, - 0.008462592, - -0.014551021, - 0.031309273, - -0.0420301, - 0.0064176586, - -0.021478754, - 0.006028148, - -0.024465006, - -0.027247228, - 0.0128538655, - -0.009213792, - 0.0018664072, - -0.016860265, - 0.04536877, - 0.0027845404, - -0.016544947, - -0.0031369552, - -0.004312444, - -0.009765599, - 0.026245628, - -0.021441657, - 0.008675896, - 0.014894161, - 0.004984814, - -0.009329718, - 0.0012241777, - 0.0040365406, - 0.005963229, - -0.015932858, - -0.012204681, - 0.014940532, - -0.001234611, - 0.005949318, - -0.000497612, - -0.0009760962, - -0.0030558072, - 0.02902785, - -0.018353391, - 0.014653035, - -0.024372265, - 0.010238577, - -0.010247851, - -0.0122788735, - 0.05174933, - -0.030196384, - 0.021441657, - -0.020588443, - 0.02531822, - 0.021107791, - 0.010767199, - 0.017314695, - -0.008495051, - 0.018724354, - 0.038580146, - 0.0078087696, - -0.013771999, - -0.024409361, - -0.0016206444, - -0.0009471147, - -0.018269924, - -0.0136792585, - 0.008550696, - 0.006204355, - -0.010869214, - -0.012724029, - -0.03249635, - 0.0015290629, - 0.023259375, - 0.0049801776, - 0.016322369, - -0.013948207, - -0.00051065366, - -0.0060095997, - 0.018900562, - 0.026672235, - -0.0041316, - 0.0015174702, - 0.011982103, - 0.008179733, - 0.0035496515, - 0.03472213, - 0.011082518, - -0.008875288, - 0.013707081, - 0.016544947, - -0.008629525, - 0.004066681, - -0.005828755, - -0.02392711, - 0.0051378366, - 0.0041571036, - 0.0123623395, - 0.010934132, - -0.033906013, - -0.036966458, - -0.00048514997, - 0.016480029, - -0.0055134366, - -0.022795672, - -0.0025828294, - 0.014180059, - 0.008137999, - 0.01265911, - -0.019382814, - 0.007312607, - -0.004212748, - 0.0033177997, - -0.00935754, - -0.029268976, - -0.0032551996, - 0.0016380332, - 0.014782873, - 0.020532798, - -0.015450606, - 0.012343791, - -0.001538337, - 0.025151286, - -0.01664696, - -0.008490414, - -0.0015951407, - 0.012788947, - 0.0016855628, - 0.041065596, - -0.02312954, - 0.009042221, - 0.008337392, - -0.00055354624, - 0.00018330786, - 0.0015452924, - -0.00081843697, - -0.0051239254, - 0.007076118, - 0.008893836, - -0.0006862814, - 0.025967406, - -0.023463406, - -0.016953006, - -0.013994576, - -0.02522548, - -0.0068813623, - 0.0007210592, - -0.019679584, - -0.006686607, - 0.019252976, - -0.00042052128, - 0.026783524, - 0.0033085258, - 0.00040689996, - -0.0012496813, - -0.0041640587, - 0.039952707, - 0.00918597, - -0.009162785, - 0.006093066, - -0.014653035, - 0.0021399923, - -0.006023511, - 0.02021748, - -0.007590829, - 0.015394961, - 0.024075495, - -0.0021075332, - -0.00076511106, - -0.0050079995, - -0.016860265, - -0.012992977, - 0.023778724, - 0.022165036, - 0.01416151, - -0.0009807333, - 0.011963555, - 0.03641001, - 0.0032551996, - -0.013141362, - -0.01411514, - -0.0034592294, - -0.02040296, - -0.010999051, - -0.018399762, - -0.0014328443, - 0.002397348, - -0.008374488, - -0.006746888, - -0.017045747, - -0.002777585, - 0.004683407, - 0.005541259, - 0.00047326754, - -0.026097242, - -0.016433658, - 0.030752826, - 0.0018211962, - -0.0004425472, - 0.040360767, - -0.006329555, - 0.007971066, - 0.020885212, - 0.0018513369, - 0.007711392, - -0.025392413, - 0.0048596147, - 0.019178784, - -0.021200532, - 0.034685034, - 0.004567481, - -0.014949806, - -0.022183584, - 0.033572145, - 0.020198932, - 0.020124739, - 0.007368251, - 0.03134637, - -0.018724354, - -0.0110454215, - -0.0051517477, - -0.008054533, - -0.0070390217, - -0.0073867994, - -0.017583642, - 0.007961792, - 0.0020518887, - -0.005787022, - -0.026598042, - -0.009366814, - -0.009334355, - -0.019438459, - -0.02832302, - -0.017092118, - -0.00039096017, - 0.028638339, - -0.016285272, - -0.00011643309, - -0.656456, - -0.015654637, - 0.02401985, - -0.012390162, - 0.0066124145, - -0.03362779, - 0.013002251, - -0.012232503, - 0.09318589, - -0.0065289475, - 0.005193481, - -0.027302872, - 0.002647748, - 0.030437509, - -0.01181517, - 0.004124644, - 0.01630382, - -0.0048642517, - 0.021998102, - -0.0058658514, - 0.01607197, - -0.009645036, - 0.029194783, - 0.0031925999, - -0.01992071, - 0.037374515, - 0.0019092999, - -0.016897362, - -0.012714755, - -0.0031485478, - -0.018047348, - 0.023982754, - 0.018334843, - -0.012798221, - 0.006937007, - -0.016582044, - -0.00024156063, - 0.0009737777, - 0.04032367, - -0.007484177, - -0.029806871, - 0.004924533, - -0.058389567, - 0.015775198, - -0.013067169, - 0.010303495, - 0.0053789625, - 0.02032877, - -0.007609377, - -0.00045964625, - -0.032088295, - 0.005582992, - 0.009352903, - 0.0046996367, - 0.006589229, - -0.020996502, - 0.0016762888, - -0.0039113406, - -0.015422784, - -0.020161835, - 0.01090631, - 0.00039124998, - -0.024446458, - 0.020365866, - 0.022276323, - 0.0009384203, - 0.026004503, - 0.009371451, - -0.0041176886, - -0.012955881, - 0.005049733, - 0.007215229, - -0.014152236, - 0.037801124, - 0.015932858, - 0.012093391, - -0.0051146513, - 0.019290073, - -0.018928384, - -0.0024228517, - 0.028953657, - 0.0007112055, - 0.016507851, - 0.041770425, - -0.01932717, - 0.025058547, - 0.0018629294, - -0.017138487, - 0.19067495, - -0.01971668, - 0.0023046073, - 0.19631359, - -0.022053747, - -0.02561499, - 0.017129213, - 0.020773925, - -0.012826043, - 0.0629895, - -0.017704206, - -0.0067561623, - -0.00697874, - 0.02643111, - -0.0089958515, - -0.02171988, - -0.016776798, - -0.018334843, - -0.0019834924, - -0.0024877703, - -0.0022002738, - 0.0047807847, - -0.000560212, - -0.02952865, - -0.021571495, - -0.016016325, - 0.00572674, - -0.03431407, - -0.0056108143, - -0.031958457, - 0.018000977, - 0.025281124, - 0.006343466, - -0.017138487, - -0.003779185, - 0.0051471107, - 0.025299672, - 0.002555007, - 3.7204973E-05, - 0.0077994955, - 0.0042243404, - -0.005596903, - 0.011676058, - -0.014523199, - -0.017203405, - 0.0027033924, - 0.0008717629, - -0.008587792, - -0.0020495702, - 0.00016867221, - -0.005787022, - 0.016841717, - 0.008921659, - -0.00092566846, - -0.0152373025, - 0.019160235, - 0.024335168, - 0.011676058, - 0.026004503, - 0.016285272, - 0.018205006, - -0.009445644, - 0.03262619, - -0.00668197, - 0.004402866, - -0.01511674, - 0.0062739104, - 0.004727459, - 0.0020947813, - 0.004481696, - 0.013586517, - 0.0110454215, - -0.0077809477, - -0.0049987254, - 0.03149475, - -0.007201318, - -0.009297258, - -0.01215831, - -0.006742251, - -0.011082518, - 0.022758575, - -0.023444857, - -0.010581718, - 0.012371614, - 0.02392711, - 0.004386637, - 0.029806871, - 0.0012311332, - 0.01491271, - -0.014810695, - 0.024149686, - -0.010331318, - -0.00832348, - -0.013985302, - -0.007094666, - 0.0026291998, - 0.0028425036, - 0.041176885, - -0.0031299999, - -0.015126013, - -0.0046509476, - 0.022294872, - 0.009459555, - 0.013447407, - -0.008161184, - -0.023259375, - -0.011397836, - 0.026486754, - 0.024112592, - 0.0014015443, - -0.033182636, - -0.0018513369, - 0.01156477, - 0.0136792585, - -0.020087643, - 0.010999051, - 0.026690783, - -0.0055180737, - 0.025948858, - -0.009849066, - 0.0056479108, - 0.012047022, - 0.01020148, - -0.005578355, - -0.025763376, - 0.0067144292, - 0.051786426, - -0.0048827995, - -0.01145348, - 0.017221954, - -0.00029503147, - 0.0045999405, - 0.012260325, - -0.0009361018, - 0.01664696, - -0.0017864184, - -0.00048775828, - -0.006334192, - -0.008889199, - 0.0060466956, - -0.015023999, - 8.701689E-05, - -0.031012502, - -0.011638962, - -0.0071549476, - 0.019086042, - 0.01366071, - -0.003157822, - 0.025002902, - -0.013215555, - -0.027785124, - -0.010182933, - 0.008017437, - 0.0063527403, - -0.002133037, - 0.012000651, - -0.008406947, - 0.02010619, - -0.0003335768, - -0.02401985, - -0.009287984, - -0.007595466, - 0.0044306885, - -0.0032018737, - 0.036076147, - 0.014467554, - -0.005156385, - 0.015005451, - 0.011972829, - -0.019290073, - 0.010433332, - -0.015654637, - -0.01846468, - 0.022832768, - 0.013048621, - -0.027581094, - 0.002146948, - -0.00080104807, - -0.10038257, - 0.007822681, - -0.021386012, - -0.012770399, - -0.032644738, - 0.0061394367, - 0.01085994, - -0.018779999, - 0.002580511, - 0.0053835995, - -0.011880088, - -0.0009697203, - -0.0029421998, - 0.02133037, - 0.014421184, - -0.013605066, - -0.019698132, - -0.0043054884, - 0.022758575, - 0.0073775253, - -0.008267837, - -0.005578355, - 0.008161184, - 0.014504651, - 0.014346992, - 0.0092416145, - 0.004182607, - -0.0100623695, - 0.02112634, - -0.026523849, - 0.018446133, - 0.007859777, - -0.01386474, - 0.0041710143, - 0.012390162, - -0.0020368183, - 0.031772975, - -0.010303495, - 0.004298533, - -0.01671188, - -0.019123139, - 0.018353391, - -0.041473657, - 0.018344117, - 0.007460992, - 0.012269599, - -0.031476203, - -0.008634162, - -0.008940207, - 0.026004503, - -0.015265125, - 0.017824769, - 0.015719553, - -0.00960794, - -0.010025273, - 0.020792473, - -0.0049709035, - 0.002294174, - 0.016340917, - 0.005295496, - 0.01145348, - -0.0037559997, - 0.013901836, - 0.013057895, - 0.042289775, - -0.012557095, - 0.0071595847, - -0.011583318, - -0.005527348, - -0.0134288585, - 0.019364266, - 0.0034870517, - -7.491712E-05, - -0.03633582, - 0.020755377, - -0.022424709, - 0.02531822, - 0.039804325, - 0.03331247, - -0.026876265, - -0.0093204435, - -0.04893001, - 0.009102503, - -0.01541351, - -0.019345718, - 0.0011140481, - -0.006709792, - 0.01470868, - -0.031568944, - -0.022090843, - 0.028081894, - -0.023240827, - 0.0053650513, - -0.020273125, - -0.018010251, - 0.0071642217, - -0.00910714, - -0.012353065, - 0.00910714, - -0.016396562, - -0.007340429, - 0.00923234, - -0.016860265, - 0.007553733, - -0.007294059, - 0.0009523314, - 0.023574695, - -0.002782222, - 0.00535114, - -0.011833718, - 0.021998102, - -0.0026964368, - 0.0033433035, - -0.009700681, - -0.006705155, - 0.00066077773, - 0.00078018144, - 0.002464585, - -0.017268324, - -0.0047807847, - -0.005411422, - -0.0035125553, - -0.0018895925, - -0.011694606, - 0.0066355993, - -0.0076603848, - 0.005698918, - -0.0024158962, - 0.029454457, - -0.014272799, - 0.0019985628, - -0.0062924586, - 0.01366071, - -0.0022512814, - 0.0030650813, - -0.028063346, - 0.0005700657, - 0.003658622, - 0.024056947, - 0.020755377, - 0.00047529626, - 0.03260764, - 0.026894813, - 0.010386962, - 0.007303333, - 0.009468829, - 0.042178486, - -0.012371614, - -0.060689535, - 0.011778073, - -0.017407436, - -0.008179733, - 0.02251745, - 0.0032134664, - -0.0057499255, - -0.038876917, - 0.016776798, - 0.0041292813, - 0.0022327332, - 0.00039907498, - -0.015561895, - -0.008457955, - 0.016266724, - -0.02251745, - -0.032218132, - -0.007099303, - -0.012733303, - -0.0085831545, - 0.029973805, - -0.014634488, - 0.005902948, - -0.0014189333, - -0.0036076144, - -0.018650161, - 0.0086619845, - -0.012306696, - 0.010331318, - -0.0029143775, - -0.009645036, - -0.01520948, - 0.008838192, - 0.003157822, - 0.0052769477, - -0.0044793775, - -0.027933508, - 0.015450606, - 0.004669496, - -0.020885212, - 0.018798547, - 0.008476503, - -0.019957805, - -0.011694606, - 0.005967866, - 0.0006735296, - -0.022851316, - -0.014189332, - 0.011880088, - 0.0063620145, - 0.023500502, - 0.0074980883, - -0.044775225, - 0.0014154555, - 0.005040459, - -0.007539822, - -0.006074518, - -0.012260325, - -0.014949806, - 0.019086042, - -0.009635762, - -0.019197332, - -0.0058843996, - -0.009951081, - -0.0062460885, - -0.0029306072, - -0.0019382813, - 0.029473005, - -0.007052933, - -0.009496651, - 0.021868264, - 0.0108877625, - 0.019178784, - 0.013132088, - -0.023110991, - -0.011397836, - 0.02290696, - 0.010322044, - 0.004943081, - 0.000101362726, - -0.015524799, - -0.007113214, - 0.01611834, - 0.009000489, - 0.022146488, - -0.023055347, - 0.00392757, - 0.0065382216, - 0.022498902, - -0.012436532, - -0.003229696, - 0.024594843, - -0.025911761, - -0.013669984, - 0.015014725, - 0.010693006, - 0.0009053814, - 0.0044144588, - 0.1691591, - -0.0051239254, - 0.04941226, - -0.029584294, - -0.0016844036, - 0.0024854518, - 0.014838518, - 0.0048688883, - -0.0092416145, - 0.009904711, - -0.0085043255, - 0.014801421, - -0.023593243, - -0.024390813, - 0.027877865, - 0.02982542, - -0.02363034, - -0.009923259, - 0.01095268, - 0.016554222, - 0.02351905, - 0.0057545626, - 0.0007993092, - 0.0072662365, - 0.033906013, - 0.0047622365, - -0.017546548, - -0.047557447, - 0.001355174, - 0.0017377295, - -0.018956207, - 0.025244027, - -0.02661659, - -0.013020799, - -0.0124458065, - -0.0024390812, - -0.020940857, - 0.0010450721, - 0.0015893443, - 0.005652548, - 0.012844591, - -0.03214394, - -0.009543021, - 0.008212192, - -0.0052444884, - 0.0061208885, - -0.0025202294, - -0.030047998, - 0.02413114, - 0.0053882366, - 0.009260163, - -0.0080128, - -0.005666459, - 0.02852705, - -0.0017191813, - 0.013456681, - -0.02040296, - -0.028712532, - 0.01325265, - 0.018436858, - -0.0019127777, - -0.01466231, - -0.03603905, - 0.02722868, - -0.0074053477, - -0.007906147, - -0.03720758, - 0.0060559697, - 0.004312444, - -0.008063807, - 0.022573095, - 0.004794696, - 0.013039347, - 0.021831168, - 0.005912222, - 0.012557095, - -0.0026732516, - -0.0061394367, - -0.017611464, - -0.014124414, - -0.0017562776, - 0.020069094, - 0.013512325, - -0.015728828, - -0.019976353, - 0.018733628, - -0.027785124, - 0.009037584, - 0.020755377, - 0.023333568, - -0.009635762, - 0.027859317, - -0.0047715106, - 0.018863466, - 0.022647288, - -0.0063666515, - 0.012380888, - 0.026041597, - -0.0006828036, - -0.0040852292, - -0.01757437, - -0.0003622685, - -0.0028193183, - 0.005833392, - -0.010869214, - 0.016637689, - -0.022072295, - 0.023667436, - -0.02212794, - -0.017249776, - -0.024854517, - 0.018891288, - -0.016665509, - -0.0028100442, - 0.017008651, - -0.0050265477, - 0.012983703, - 0.0008740814, - 0.0016588998, - 0.004106096, - 0.019401362, - -0.016062696, - -0.018362666, - 0.0011302776, - -0.007117851, - 0.02511419, - -0.02151585, - -0.010795021, - 0.013002251, - -0.05063644, - -0.034963258, - 0.0033850367, - -0.00411537, - 0.0042475257, - -0.007822681, - -0.0062599997, - 0.021701332, - 0.030344767, - -0.023185184, - 0.016906636, - 0.00428694, - 0.011305096, - -0.01416151, - 0.0031415923, - -0.011091792, - -0.012890962, - 0.014745777, - 0.018186457, - 0.01020148, - 0.005828755, - 0.06669913, - 0.012056296, - -0.01780622, - 0.0010329, - -0.0126034655, - -0.01691591, - 0.008555333, - -0.01156477, - 0.0006532425, - -0.0061579845, - 0.0100623695, - 0.01115671, - -0.0025735553, - -0.02222068, - 0.0055180737, - 0.0061811698, - -0.0072755106, - 0.029843967, - -0.0014363221, - 0.013669984, - -0.002791496, - 0.0106373625, - -0.0009129166, - -0.053158987, - 0.026987553, - 0.00081322034, - 0.0066541475, - -0.01020148, - 0.021534398, - 0.008587792, - -0.0020611628, - 0.018075168, - 0.024260975, - -0.016739702, - 0.0077531254, - 0.011351466, - 0.009552295, - -0.0018814777, - -0.03271893, - -0.010526073, - 0.011805896, - -0.022999702, - -0.015728828, - -0.0041849255, - 0.015330044, - 0.028842367, - -0.013512325, - 0.0022559185, - -0.005847303, - 0.015172384, - 0.021311821, - -0.007312607, - -0.031383466, - -0.0048920736, - 0.008495051, - 0.0016183258, - 0.02222068, - -0.042512354, - -0.0005564444, - 0.027043197, - 0.0010039185, - 0.002026385, - -0.008722266, - -0.0084162215, - 0.048670337, - -0.010414785, - -0.01095268, - 0.035371315, - -0.0066541475, - -0.00915351, - 0.011509125, - 0.013299021, - 0.0134288585, - 0.000823074, - 0.026913362, - -0.028582694, - 0.0057499255, - -0.014504651, - 0.010832118, - -0.023537599, - 0.0068396293, - -0.00028938008, - 0.020421509, - -0.01611834, - -0.007720666, - -0.015654637, - -0.0076511106, - -0.012686932, - 0.00568037, - -0.0023996665, - 0.005170296, - 0.013308295, - -0.019252976, - 0.0048503405, - 0.013382488, - 0.0016473073, - 0.01921588, - 0.008471866, - -0.028378664, - -0.02672788, - 0.01796388, - -0.027377065, - -0.032997154, - 0.015608265, - -0.041696236, - 0.006185807, - 0.009635762, - -0.013521599, - -0.011397836, - -0.023871465, - 0.001046811, - -0.023333568, - 0.027803672, - -0.016507851, - 0.024650486, - -0.028193183, - 4.50662E-05, - 0.009274073, - 0.01111034, - 0.0148292435, - -0.01311354, - 0.00084394065, - -0.0062970957, - 0.033089895, - 0.020569894, - -0.025132738, - 0.0022617145, - 0.0029723404, - -0.0023011295, - 0.019679584, - 0.0018443813, - 0.014875614, - 0.005912222, - 0.016183257, - -0.0066077774, - 0.009570844, - 0.0028285924, - 0.014189332, - 0.016340917, - -0.010442606, - 0.033479404, - 0.008712992, - 0.020273125, - 0.02452065, - 0.006148711, - 0.00050688605, - 0.012019199, - -0.024835968, - 0.0021852036, - -0.004664859, - -0.0030024813, - 0.030381864, - -0.021961005, - 0.011546222, - -0.018622339, - -0.013475229, - 0.018177183, - -0.007609377, - -0.013697807, - -0.0019023443, - 0.0021550627, - 0.012139762, - 0.013512325, - 0.0016925184, - 0.0049013477, - 0.02782222, - 0.008866014, - -0.018242102, - -0.006074518, - -0.014504651, - 0.011258725, - 0.026338369, - -0.020569894, - 0.008879925, - 0.0057499255, - 0.014078043, - -0.019141687, - -0.0055227107, - -0.01810299, - -0.005972503, - -0.009102503, - 0.014467554, - 0.0004726879, - 0.015626814, - 0.027692383, - 0.02982542, - 0.014152236, - -0.023723079, - -0.0014687814, - -0.0007396074, - -0.04444136, - -0.0060374215, - 0.01566391, - 0.02032877, - -0.01156477, - -0.00038893145, - -0.00014497984, - 0.013280473, - -0.015098192, - -0.019623939, - 0.008559969, - 0.006315644, - -0.004437644, - 0.00823074, - -0.0006799055, - 0.0153207695, - -0.02222068, - -0.0070158364, - 0.0051517477, - -0.017221954, - -0.0024669035, - -0.005814844, - 0.020031998, - 0.0070390217, - -0.018399762, - 0.003470822, - -0.023778724, - -0.023055347, - -0.002040296, - -0.002888874, - 0.013104266, - -0.009876888, - -0.023389213, - -0.003716585, - -0.0042799846, - -0.00024329952, - -0.007460992, - -0.0064964886, - 0.0029978442, - -0.032681834, - 0.025244027, - -0.008388399, - 0.010581718, - -0.015135287, - 0.0012519999, - 0.041955907, - -0.0076325624, - -0.03132782, - -0.047965508, - 0.0054485183, - 0.020848118, - -0.012872414, - -0.025485154, - -0.016535673, - 0.016693331, - 0.010080918, - 0.0059771403, - -0.007873688, - -0.021033598, - -0.0065289475, - -0.012241777, - 0.010943406, - -0.0045558885, - -0.008624888, - -0.024149686, - 0.008815006, - -0.023259375, - 0.012788947, - -0.0015244258, - -0.0060003255, - -0.010433332, - -0.006946281, - -0.01070228, - 0.012297422, - -0.0033224367, - 0.005425333, - 0.03754145, - -0.0068535404, - 0.012037748, - 0.0026036962, - -0.007168859, - 0.022424709, - 0.030641539, - 0.01982797, - -0.028805273, - -0.016990103, - -0.012102665, - -0.0015951407, - 0.022684384, - 0.01675825, - 0.01866871, - 0.019271525, - -0.007869051, - 0.014931258, - 0.01031277, - -0.011722429, - 0.0002134486, - -0.0051239254, - 0.02902785, - 0.020384414, - -0.024335168, - 0.0043796813, - -0.013104266, - -0.008063807, - 0.020458605, - -0.012640562, - 0.014551021, - 0.0052398513, - 0.018288473, - 0.01941991, - 0.010665185, - 0.007864414, - -0.03481487, - 0.023500502, - 0.028285924, - 0.008852103, - 0.007614014, - 0.008949481, - 0.0005265935, - -0.003538059, - -0.00042283977, - 0.010164385, - 0.022888413, - 0.023723079, - -0.029250428, - -0.016507851, - -0.04125108, - 0.01265911, - 0.004451555, - -0.013725628, - 0.004386637, - -0.012788947, - -0.0038394663, - 0.02101505, - 0.01941991, - -0.034184236, - -0.011601866, - -0.0004564583, - 0.015858665, - -0.0062229033, - 0.013938933, - 0.004813244, - 0.022443257, - 0.010006725, - -0.01611834, - 0.0035797923, - -0.02381582, - 0.0066402364, - -0.011305096, - -0.0020855071, - -0.0014571887, - -0.008508963, - -0.021293273, - -0.023055347, - 0.014059495, - 0.016378013, - -0.02772948, - -0.0034267702, - 0.041955907, - -0.0030558072, - -0.015617539, - -0.012751851, - 0.00436577, - 0.02231342, - 0.0010044981, - 0.015200206, - 0.005550533, - -0.005657185, - -0.00865271, - -0.029547198, - -0.012992977, - -0.0053279554, - -0.0074934512, - -0.0052676736, - -0.027302872, - 0.021831168, - 0.019438459, - -0.0033038887, - 0.01111034, - 0.025652086, - -0.0099789025, - 0.012306696, - 0.002120285, - -0.017323969, - 0.020310221, - -0.015098192, - 0.015172384, - -0.024576295, - 0.0042637554, - -0.011945006, - -0.0011621573, - 0.0069694663, - -0.002075074, - 0.010424059, - 0.008805732, - 0.023741627, - -0.037986603, - -0.012547821, - 0.00047500644 - ], - "HOTEL9_VECTORIZE_DESCRIPTION": [ - -0.02881642, - -0.030480592, - 0.033476096, - 0.021984564, - -0.005583729, - -0.028028129, - -0.013856406, - 0.019304374, - 0.032057174, - -0.006647922, - -0.009301836, - 0.016028587, - -0.0077077355, - 0.0014747613, - -0.0016422732, - 0.0109484885, - -0.031881995, - 0.019654727, - 0.025838431, - -0.0063107084, - -0.020320393, - 0.015818376, - -0.01961969, - -0.013155703, - 0.01253383, - 0.02144152, - -0.020951027, - -0.00046120505, - 0.021774353, - 0.01057186, - 0.004004957, - -0.021021098, - 0.046141308, - 0.027379978, - -0.001053792, - 0.025663257, - -0.004497639, - -0.0029714196, - -0.0059647365, - 0.0056756963, - 0.011675468, - -0.00238896, - -0.0011353582, - -0.0019356927, - -0.018743811, - -0.0009508762, - -0.026101196, - 0.040886033, - -0.0055574523, - 0.021756835, - -0.032197315, - -0.007843497, - 0.008771929, - -0.045300465, - -0.02613623, - 0.0011495913, - 0.024804894, - -0.009406941, - 0.03445708, - 0.0030436798, - 0.0048567494, - 0.011789332, - 0.019164234, - -0.002925436, - -0.026101196, - 0.02671431, - 0.006503402, - 0.0037181065, - -0.03584097, - -0.007497525, - 0.037487622, - 0.00629757, - 0.010755795, - -0.001346664, - 0.0048742667, - 0.013269568, - -0.008369024, - 0.005264033, - 0.010028815, - -0.010440478, - 0.010274061, - -0.022002082, - -0.017009571, - 0.008434715, - -0.014075376, - -0.018603671, - -0.0065340577, - -0.01614245, - 0.017175987, - 0.02990251, - 0.016159968, - 0.0034487736, - 0.028080681, - -0.0022422504, - -0.017955521, - 0.008189469, - 0.009582117, - -0.031111224, - 0.006017289, - 0.008390921, - 0.019321892, - 0.015800858, - -0.0065340577, - 0.013514814, - 0.00027973388, - -0.014530833, - 0.043828987, - -0.029447053, - 0.013155703, - 0.009258041, - -0.020407982, - -0.006836236, - -0.006004151, - 0.0013236722, - -0.015949758, - 0.007620148, - 2.5780268E-05, - 0.00038292338, - 0.007830359, - 0.041306455, - -0.015730787, - -0.014933738, - 0.014548351, - 0.009590875, - -0.03055066, - 0.002577274, - -0.0077077355, - -0.0014430108, - -0.016904466, - -0.012910457, - 0.0067311306, - -2.376164E-05, - -0.043618776, - 0.007357384, - 0.010817106, - 0.002577274, - -0.005785181, - 0.007869774, - -0.009722257, - 0.012332377, - -0.00050116703, - -0.018883953, - -0.0020736437, - 0.0058683897, - 0.008504786, - 0.014942496, - -0.015870929, - 0.039134275, - -0.02070578, - 0.032022137, - 0.020670746, - 0.020250324, - 0.022720302, - -0.015765823, - 0.0016904465, - -0.01216596, - -0.002592602, - 0.0072084847, - 0.008009914, - 0.028728833, - -0.017368682, - 0.008815723, - -0.014460763, - 0.012227272, - 0.005018787, - 0.01716723, - -0.043268424, - -0.029096702, - -0.004909302, - -0.011859402, - -0.008583615, - -0.0141104115, - -0.006240638, - 0.032530148, - 0.016475284, - 0.02671431, - -0.027852954, - -0.021424001, - -0.0029670403, - 0.013725025, - 0.024734825, - -0.013383431, - 0.058543757, - -0.025733326, - 0.026416512, - 0.018989058, - -0.0085792355, - 0.024734825, - 0.021704283, - 0.008246401, - -0.014670974, - 0.006971997, - -0.053393587, - -0.012139684, - -0.01253383, - 0.006639163, - -0.013716266, - -0.011789332, - 0.021406483, - -0.019899972, - 0.01072076, - 0.006118015, - 0.0115791205, - -0.0005586466, - -0.018130695, - -0.0038845236, - -0.00891207, - 0.0070157913, - 0.011447739, - 0.016781842, - -0.04547564, - -0.0071865874, - 0.02447206, - 0.034159284, - -0.005312206, - 0.0039217486, - -0.05192211, - 0.008933966, - -0.03454467, - 0.01687819, - 0.011885678, - 0.008517924, - 0.030445555, - -0.0007061775, - -0.029201807, - 0.030673284, - 0.00659099, - -0.0138739245, - 0.0076595624, - 0.018656224, - -0.0029144876, - 0.010966006, - -0.0008638357, - -0.01811318, - 0.012262306, - 0.01672929, - 0.013129427, - 0.013838889, - -0.03216228, - 0.008277057, - -0.02114372, - -0.015100155, - -0.0057370076, - -0.014828633, - 0.011535327, - 0.003446584, - 0.008237642, - 0.008058087, - -0.00042890702, - 0.015809616, - 0.011403945, - 0.014951255, - 0.020040112, - -0.0020791178, - 0.0032144762, - 0.032600217, - -0.011929473, - 0.010703241, - 0.015187742, - 0.019024093, - -0.023210794, - -0.011132423, - 0.051011197, - -0.009871157, - -0.0004261699, - -0.010046333, - -0.028588692, - 0.0017440942, - -0.008517924, - -0.048768945, - 0.00076091994, - -0.014872426, - 0.01650156, - -0.04141156, - 0.01499505, - 0.0022838546, - -3.5890513E-05, - -0.021196272, - -0.0065953694, - 0.0027699675, - -0.0085004065, - -0.040675823, - 0.038853996, - 0.0027852952, - 0.008929587, - -0.0108609, - -0.021126203, - -0.006481505, - -0.026836934, - 0.024437025, - -0.023421006, - 0.01354109, - -0.016562873, - 0.010563102, - 0.015967274, - 0.013795095, - 0.027887989, - -0.052307498, - 0.0008370119, - -0.014565868, - -0.0065515754, - 0.034877505, - 0.026889486, - -0.011255045, - -0.019672243, - 0.0092668, - -0.008850758, - 0.008719376, - 0.014469522, - 0.0036239496, - -0.004541433, - -0.014863667, - 0.011071111, - -0.035911042, - -0.022264846, - -0.025698291, - -0.02519028, - 0.0057107313, - -0.034281906, - 0.003556069, - -0.0030174034, - 0.0006558144, - 0.013742542, - 0.0006032617, - 0.021126203, - -0.03514027, - 0.015187742, - 0.020898474, - -0.023368454, - 0.0025947916, - 0.03990505, - -0.0011747727, - 0.012945492, - 0.014548351, - -0.006161809, - -0.004598365, - -0.0015546853, - 0.008539821, - 0.010589378, - 0.014548351, - 0.014276829, - -0.043828987, - -0.0050363047, - -0.0049355784, - 0.011999543, - -0.0065690926, - -0.017850416, - -0.0069238236, - -0.008404059, - -0.012910457, - -0.015257813, - -0.023088172, - -0.011824367, - 0.023421006, - 0.0065340577, - -0.0031903894, - -0.016063621, - 0.024104191, - -0.009293077, - 0.00016573274, - -0.033703826, - -0.045300465, - 0.0018809503, - 0.004694712, - 0.02345604, - 0.0007286219, - -0.04050065, - 0.00593846, - -0.003851678, - 0.01623004, - -0.02657417, - -0.023368454, - -0.0060567036, - 0.007002653, - -0.012402447, - 0.021476554, - -0.011666709, - 0.0050582015, - -0.013716266, - -0.019514585, - -0.002577274, - -0.012901698, - -0.0019783918, - -0.051361546, - -0.0064420905, - 0.0023626836, - 0.022317398, - -0.0075851125, - -0.019812385, - 0.0017999314, - 0.009152936, - -0.0061048768, - -0.009599634, - 0.005728249, - -0.013558608, - -0.01274404, - 0.009836121, - 0.0023626836, - 0.025347939, - -0.021283861, - 0.028711315, - -0.03626139, - 0.006424573, - -0.00905659, - 0.022317398, - -0.018848917, - -0.040185332, - -0.037207343, - 0.0091179, - -0.0046158824, - 0.016492803, - -0.008697479, - 0.00434436, - 0.00985364, - 0.011780573, - 0.032179795, - -0.0054698647, - -0.02498007, - 0.011438981, - -0.0049574752, - 0.0031028015, - 0.02294803, - -0.0025816534, - 0.014311864, - 0.0060742213, - 0.014942496, - 0.012603899, - -0.004909302, - -0.042532686, - -0.0055136587, - 0.011605397, - 0.0055486937, - 0.027204802, - 0.028133234, - -0.03410673, - 0.026766863, - 0.00088025845, - -0.009625911, - -0.0038538678, - -0.028045647, - -0.03622636, - -0.018918987, - -0.0010817106, - -0.010519307, - 0.03944959, - 0.031338952, - 0.02506766, - 0.038889028, - 0.015354159, - 0.011018558, - 0.012218513, - 0.0019718227, - -0.010090127, - -0.00014616232, - -0.006280053, - 0.027555155, - 0.031216329, - -0.018551119, - 0.018288355, - -0.02766026, - 0.0011572551, - 0.0053778975, - -0.008478509, - -0.0039261277, - 0.029149255, - -0.020250324, - 0.012341136, - -6.78122E-05, - -0.007068344, - 0.013514814, - -0.017859174, - -0.0111849755, - 0.02795806, - 0.0073398664, - 0.0170884, - -0.041902054, - -0.028255858, - 0.03195207, - 0.016816877, - -0.035227854, - 0.012989286, - 0.0039983876, - -0.01773655, - -0.0018743812, - -0.0133221205, - -0.63287514, - -0.020968545, - 0.024349438, - 0.01940948, - -0.005995392, - -0.0040947343, - 0.012113407, - 0.00536038, - 0.0842946, - 0.010957247, - 0.006350123, - -0.023911498, - -0.025295386, - -0.014311864, - -0.003904231, - 0.022282362, - 0.0054873824, - 0.024962552, - -0.01644025, - 0.009441976, - -0.0067530274, - -0.017281093, - -0.0006623835, - -0.0015415471, - -0.010449237, - 0.0063413642, - 0.016046105, - -0.012192236, - -0.016282592, - -0.023018101, - -0.0014298726, - 0.02317576, - 0.018551119, - 0.0060917386, - -0.02049557, - -0.0047385055, - 0.026101196, - -0.009985021, - 0.037697833, - 0.0011298839, - 0.026661757, - -0.0029779887, - -0.08128157, - 0.008885792, - 0.00825078, - -0.017938003, - -0.018183248, - 0.0069676177, - 0.025260352, - 0.0015700132, - -0.012104648, - -0.005758905, - -0.010729519, - 0.013199497, - 0.01623004, - 0.0061661885, - -0.012174719, - 0.006096118, - -0.0138739245, - -0.024577167, - -0.000261532, - -0.012078372, - -0.003939266, - 0.025137728, - -0.004668435, - -0.001897373, - 0.0156432, - 0.009065348, - 0.009512046, - -0.0013784147, - 0.0025816534, - 0.0064858845, - -0.017009571, - 0.01057186, - 0.012472518, - -0.023999086, - 0.0103178555, - -0.0014462953, - -0.0034597223, - 0.0068887887, - 0.008014293, - 0.01172802, - 0.023788875, - 0.01231486, - -0.025260352, - 0.0061968444, - -0.014381934, - 0.0012722143, - 0.20488563, - -0.0059034247, - 0.0064420905, - 0.17699763, - 0.0016904465, - -0.019584656, - 0.021739317, - 0.0185336, - 0.0023167, - 0.007839117, - -0.006236259, - -0.028413516, - -0.007742771, - 0.027327426, - 0.016203763, - 0.00011885953, - 0.0141892405, - -0.0010483178, - -0.005544314, - 0.029131737, - 0.010422961, - -0.008123778, - -0.0064201932, - -0.055285484, - -0.008404059, - -0.020530606, - 0.017079642, - -0.014101652, - 0.0015732978, - -0.009249283, - -0.0126827285, - 0.012253548, - -0.0055355555, - -0.013865165, - 0.019094164, - 0.004585227, - -0.014303105, - -0.0015919101, - 0.0051238923, - 0.022072151, - 0.018410977, - -0.0072610374, - 0.032565184, - -0.01615121, - -0.015108913, - 0.012875422, - -0.008942725, - -0.015651958, - 0.028396, - 0.0119732665, - 0.007777806, - 0.01361116, - 0.026013607, - 0.0050231665, - -0.0141892405, - 0.0032057173, - -0.01440821, - 0.012060855, - 0.023701288, - 0.027765365, - 0.0056756963, - -0.006989515, - 0.023228312, - 0.011386428, - -0.0043991026, - -0.025312904, - 0.0050450633, - -0.029972581, - 0.0017386199, - -0.006792442, - 0.012472518, - 0.0058333543, - 0.011631674, - 0.005973495, - 0.021476554, - 0.0059997714, - 0.0029801785, - 0.0004710587, - 0.012271065, - 0.016755566, - 0.017850416, - -0.0035144647, - 0.00905659, - 0.031041153, - 0.01614245, - -0.0023364073, - 0.002230207, - 0.0059647365, - 0.010142679, - -0.047472645, - 0.0036699332, - -0.020583158, - 0.0039874394, - 0.0024984449, - -0.00028685038, - 0.004576468, - 0.0080230525, - -0.009766052, - 0.011360151, - -0.014171723, - 0.024945036, - 0.019462032, - 3.8217066E-05, - -0.0104755135, - -0.0052465154, - -0.029096702, - -0.0033655653, - 0.016974537, - 0.014381934, - -0.0070289294, - 0.011911955, - 0.032039657, - -0.004026854, - 0.0023517353, - 0.008198228, - 0.026942039, - 0.011745538, - 0.00035172017, - 0.025890984, - 0.009976262, - -0.005772043, - 0.009380665, - -0.032179795, - -0.00039606154, - -0.028133234, - -0.027572673, - 0.02317576, - 0.00029040864, - 0.0006788063, - 0.01440821, - -0.018305872, - -0.0054611056, - 0.00209992, - 0.022667749, - -0.00022471772, - 0.017412476, - 0.0044888803, - -0.001089922, - -0.022369951, - 0.013654955, - -0.043758918, - -0.012008302, - -0.014145447, - -0.015187742, - -0.018253319, - -0.018428495, - -0.016449008, - -0.028886491, - 0.021126203, - -0.010274061, - -0.0024984449, - -0.029639747, - 0.0028290893, - 0.02035543, - -0.016247556, - 0.0156081645, - 0.004655297, - 0.018551119, - 0.0076070097, - -0.0051939627, - -0.008780687, - 0.00600853, - -0.009643428, - -0.018848917, - 0.011036076, - -0.023736322, - 0.009660946, - -0.004607124, - -0.018586153, - -0.040010154, - 0.0046903323, - 0.0073092105, - -0.010081368, - 0.017035848, - -0.034824952, - -0.019689761, - 0.038924064, - -0.012463759, - -0.09039072, - 0.02114372, - 0.010869659, - 0.0063676406, - -0.016597908, - 0.006402676, - 0.008329609, - 0.0065778517, - 0.02599609, - 0.017771585, - -0.0046596765, - 0.0011868161, - 0.028273376, - 0.022194775, - 0.0040531303, - 0.008780687, - 0.024997588, - -0.012034578, - 0.0052771713, - 0.0011988594, - 0.02368377, - 0.012253548, - -0.018603671, - -0.0011933852, - -0.017973037, - -0.017114677, - -0.013313361, - -0.0062756734, - 0.004300566, - 0.004742885, - -0.012586382, - 0.0172373, - -0.013295844, - 0.026311407, - 0.018183248, - -0.015538095, - -0.0050231665, - -0.0018776658, - 0.011333874, - 0.0026407754, - 0.014933738, - -0.008583615, - -0.009731016, - 0.012113407, - 0.0016159968, - 0.0085442, - -0.017894208, - -0.023193277, - -0.0034947575, - 0.015625682, - 0.00011167458, - 0.0057808016, - -0.02476986, - 0.0090478305, - 0.018866435, - -0.01644025, - -0.006748648, - 0.014075376, - -0.012148443, - 0.02752012, - 0.009976262, - -0.0067223716, - 0.011675468, - 0.010493031, - 0.0019433566, - -0.026644241, - 0.013190739, - -0.0032298039, - -0.006205603, - 0.0035385513, - 0.022054635, - -0.0009826268, - 0.01028282, - -0.0031816305, - 0.023578664, - -0.018918987, - 0.0029429535, - 0.016449008, - 0.0049706134, - -0.016256316, - 0.017797861, - -0.01767524, - 0.02881642, - 0.0021185325, - -0.0026144988, - -0.0172373, - -0.00070946204, - 0.017114677, - -0.013094392, - -0.009608394, - 0.023508593, - -0.05034553, - -0.012971769, - -0.020337911, - -0.007068344, - 0.025365457, - 0.006945721, - 0.02121379, - 0.008750032, - 0.004020285, - 0.010685724, - 0.047262434, - -0.0065515754, - -0.025015105, - 0.015100155, - -0.008706238, - 0.013365914, - -0.0067311306, - -0.02100358, - -0.036681816, - 0.011360151, - 0.0119732665, - -0.03505268, - -0.013225773, - 0.029149255, - -0.0031465956, - -0.029026631, - 0.0031663028, - 0.017062124, - -0.01926934, - 0.012446241, - 0.010966006, - -0.0068756505, - 0.000641034, - 0.0026539136, - -0.0114214625, - -0.007103379, - -0.012998045, - -0.0047910586, - 0.009450735, - -0.008592374, - 0.015170225, - 0.016282592, - -0.006021668, - -0.0035757762, - -0.030936047, - 0.012113407, - 0.0059691155, - 0.009748533, - 0.020250324, - -0.005110754, - 0.026539136, - 0.0031181294, - 0.01455711, - 0.005465485, - -0.009512046, - 0.055215415, - -0.024507096, - 0.0121309245, - 0.012560106, - -0.028974079, - -0.0005715111, - 0.015397954, - 0.0069982735, - 0.034807432, - -0.007957361, - 0.00600853, - 0.019584656, - 0.0073398664, - -0.015091396, - 0.0043706363, - -0.017631445, - 0.017508822, - 0.0046421587, - -0.002040798, - 0.021459037, - -0.010817106, - -0.026118712, - -0.002702087, - -0.0028685038, - 0.00651654, - -0.020232806, - 0.0113426335, - 0.0044932594, - 0.016773084, - -0.021283861, - 0.0026123093, - 0.0033305301, - -0.024945036, - -0.015459266, - -0.006713613, - 0.023911498, - 0.0012656453, - 0.008150054, - -0.013549848, - -0.014241793, - 0.018726295, - -0.005837734, - 0.011911955, - 0.01238493, - 0.019864937, - -0.033283405, - 0.015599405, - -0.011220011, - -0.0066566807, - -0.01788545, - 0.012271065, - 0.003280167, - 0.031549163, - 0.0028071923, - -0.019864937, - -0.009012795, - -0.0038713855, - 0.0045195357, - 0.018778848, - 0.003148785, - -0.00738804, - 0.0085442, - -0.0055224174, - -0.020600675, - 0.0070552058, - 0.007147173, - 0.0031071808, - 0.004412241, - -0.008570476, - -0.007992396, - 0.028255858, - -0.0071865874, - -0.009844881, - 0.017140953, - 0.021231309, - 0.012078372, - 0.00933687, - 0.0027042765, - 0.0091179, - 0.03454467, - 0.0016740238, - -0.009783569, - 0.020443017, - -0.006774924, - 0.0017364302, - -0.012901698, - -0.010466754, - -0.004974993, - 0.0072435196, - -0.0059078042, - 0.024734825, - -0.007992396, - 0.02158166, - 0.037627764, - -0.013917718, - 0.013059356, - -9.278844E-05, - -0.00048775514, - 0.006792442, - 0.010020056, - 0.14392444, - -0.021494072, - 0.023876462, - -0.01694826, - 0.035157785, - -0.02548808, - 0.013383431, - 0.01897154, - 0.0044078613, - -0.023193277, - 0.0064333314, - 0.014294346, - -0.016361421, - 0.011412704, - -0.00419984, - 0.020618193, - 0.014811114, - -0.028325928, - 0.018866435, - 0.026959557, - -0.0026035504, - 0.0006295381, - -0.014732285, - 0.0023626836, - -0.003823212, - 0.015573129, - 0.0046728146, - -0.016352661, - -0.006424573, - 0.0070727235, - -0.006849374, - -0.002780916, - 0.013409709, - -0.0037334345, - 0.0022389658, - 0.0060435655, - 0.017517582, - 0.012043336, - 0.0013740353, - 0.004655297, - -0.007808462, - -0.006945721, - 0.020898474, - -0.016895706, - -0.0071865874, - -0.026609205, - -0.018340908, - -0.019759832, - 0.037487622, - 0.009573358, - 0.017368682, - 0.017613927, - -0.013287085, - -0.008303333, - 0.005307827, - 0.000114959126, - -0.009660946, - -0.04582599, - 0.010703241, - 0.011509051, - -0.01520526, - 0.0019094163, - -0.013260809, - 0.0128403865, - 0.004545812, - -0.014154205, - -0.03990505, - -0.0143468985, - -0.004528295, - -0.023228312, - 0.010300337, - -0.014136688, - 0.035280406, - 0.01811318, - 0.0016477475, - -0.017149711, - -0.0037903665, - 0.017710274, - -0.008933966, - -0.027064662, - -0.0049224403, - 0.006915065, - 0.029429536, - -0.00068701763, - 0.003556069, - -0.0070333085, - -0.007129655, - -0.02678438, - -0.00412758, - 0.030568179, - -0.01499505, - 0.0172373, - -0.009433217, - -0.016449008, - 0.016816877, - -0.03605118, - 0.015222778, - 0.031601716, - 0.0021951718, - 0.015888445, - -0.0033064433, - -0.0331783, - 0.0012043337, - -0.007734012, - -0.019356927, - 0.01867374, - 9.114616E-05, - -0.0059647365, - 0.0038319707, - -0.011920714, - -0.02317576, - -0.0062143616, - -0.009450735, - -0.01940948, - 0.03279291, - 0.016886948, - 0.037207343, - -0.005010028, - 0.04323339, - 0.020653227, - 0.0005471507, - 0.009223007, - -0.0020703592, - -0.0038867132, - -0.009004037, - 0.022054635, - 0.01744751, - -0.0053910357, - 0.0025115833, - -0.013856406, - -0.024051638, - -0.005561832, - 0.008732514, - 0.032425042, - 0.012910457, - -0.008771929, - 0.012139684, - 0.0067661656, - 0.017403716, - -0.0017495684, - 0.008723755, - 0.011438981, - 0.0268019, - -0.011246287, - 0.0016247557, - -0.006472746, - -0.011544086, - 0.018288355, - -0.0065778517, - 0.034071695, - 0.06474498, - 0.016895706, - -0.03692706, - 0.013514814, - -0.0015984792, - 0.014303105, - -0.014294346, - -0.004664056, - 0.010580619, - -0.019339409, - 0.006139912, - -0.0059691155, - -0.021599177, - -0.0056888345, - -0.011964507, - -0.0068625123, - 0.009170454, - 0.00861865, - 0.0019094163, - -0.013943994, - 0.016475284, - -0.0071822084, - -0.0045677093, - -0.0002007679, - 0.031338952, - 0.0038910927, - 0.01440821, - 0.02527787, - -0.0034071694, - -0.0022334915, - -0.0021842234, - 0.0022641474, - 0.025295386, - -0.033213332, - 0.007830359, - 0.020075148, - -0.043618776, - 0.00600853, - -0.033949073, - 0.01954962, - 0.0014233035, - -0.029079184, - -0.012437482, - -0.010712001, - 0.05034553, - 0.015143949, - -0.032827947, - 0.0050231665, - 0.029429536, - -0.012910457, - -0.021686764, - -0.009494529, - -0.027257355, - -0.0020824024, - 0.03267029, - 0.00094102253, - -0.0018579584, - -0.013926477, - 0.016641703, - 0.0007039878, - 0.019672243, - 0.00405751, - -0.0071427934, - 0.0148987025, - 0.029849958, - -0.025505599, - -0.02433192, - 0.031601716, - -0.0006585516, - -0.002853176, - -0.012630176, - -0.0020386085, - -0.01802559, - -0.02179187, - 0.022527609, - 0.009503287, - -0.0037181065, - 0.015485542, - -0.011631674, - -0.016676737, - 0.0030524384, - 0.005561832, - 0.013024322, - -0.008828861, - -0.013383431, - -0.026942039, - -0.0018951832, - 0.01593224, - 0.041376527, - 0.017806621, - 0.0376628, - 0.007760288, - 0.0053647594, - -0.011684227, - 0.045300465, - 0.018183248, - 0.025908502, - 0.004423189, - -0.005307827, - -0.0182358, - 0.007501904, - 0.006481505, - -0.025505599, - 0.025645738, - -0.015835892, - -0.0328805, - -0.01752634, - 0.0005003459, - 0.0029495226, - -0.0019466411, - -0.01491622, - -0.019321892, - 0.005561832, - -0.022667749, - -0.007734012, - -0.0078216, - -0.020968545, - -0.015739547, - -0.026171265, - -0.016711771, - 0.004865508, - -0.023666251, - 0.014381934, - -0.009949986, - 0.036681816, - -0.009039071, - 0.005636282, - 0.0033589962, - 0.016028587, - -0.0013006803, - 0.038503643, - 0.009380665, - 0.0037640901, - 0.04270786, - -0.0022926135, - -0.007515042, - 0.00043410755, - 0.019146716, - 0.026994592, - 0.010563102, - 0.03923938, - -0.019356927, - 0.001093754, - -0.002526911, - 0.022440022, - -0.009074107, - -0.010090127, - -0.037767906, - 0.0149775315, - -0.0156432, - -0.0029714196, - 0.016913224, - 0.009170454, - -0.031093705, - -0.0042502033, - -0.017789103, - -0.0032057173, - -0.004677194, - -0.0074493513, - 0.005172066, - -0.001687162, - 0.008233263, - -0.02273782, - -0.020092666, - 0.035157785, - -0.0029144876, - 0.00017763922, - -0.008719376, - 0.027572673, - -0.0111061465, - 0.01961969, - -0.0012481277, - 0.00025291007, - -0.0080230525, - 0.009608394, - 0.019602172, - -0.012910457, - -0.0002964303, - -0.007501904, - -0.0344746, - -0.0059997714, - 0.008552959, - 0.0015481162, - -0.004510777, - 0.048488665, - 0.010107644, - -0.0128403865, - -0.019356927, - -0.019094164, - -0.0066304044, - -0.015967274, - -0.021879459, - 0.014924979, - 0.024086673, - -0.0415517, - 0.025347939, - -0.004804197, - -0.010300337, - -0.016195003, - -0.015468024, - -0.016133692, - -0.0067179925, - 0.005097616, - -0.0028838317, - -0.025523115, - 0.013628677, - 0.011614156, - -0.0039020411, - 0.014635939, - -0.0024283747, - -0.022755338, - -0.01629135, - 0.013287085, - 0.0018634327, - 0.003801315, - 0.010904694, - -0.020250324, - 0.00629757, - 0.01340095, - -0.024279367, - -0.017561374, - -0.0048698876, - -0.0112638045, - -0.008623029, - 0.0066128867, - -0.022965549, - -0.013856406, - 0.009477011, - -0.03041052, - -0.030322932, - -0.008881413, - -0.008027432, - 0.019497067, - -0.02498007, - 0.020863438, - 0.021686764, - -0.026749346, - 0.008785067, - -0.026223818, - 0.0025685153, - 6.0319326E-05, - 0.010405443, - 0.020845922, - 0.0046334, - 0.025032623, - 0.03445708, - -0.017359924, - -0.0141104115, - 0.0053822766, - 0.0026035504, - -0.019286856, - 0.015143949, - -0.020145219, - -0.004510777, - 0.017648963, - 0.03533296, - 0.013943994, - 0.03251263, - -0.008158813, - -0.025961054, - -0.020092666, - -0.0012130925, - -0.039589733, - 0.028781386, - -0.018989058, - 0.017535098, - 0.02541801, - 0.013260809, - -0.00022718112, - 0.00021664321, - 0.000988101, - 0.024016604, - 0.007357384, - -0.004353119, - 0.010335373, - -0.027432531, - -0.032144763, - 0.01469725, - 0.011754297, - 0.019321892, - -0.0035889144, - 0.0078216, - 0.0021042994, - 0.00038702905, - 0.014487039, - -0.036997132, - 0.019216787, - 0.022002082, - 0.0016838774, - 0.012244789, - -0.022422504, - 0.01767524, - -0.00804057, - 0.006472746, - -0.003858247, - -0.013068115, - 0.029674781, - 0.004337791, - 0.010335373, - 0.01615121, - 0.010712001, - -0.02114372, - -0.018551119, - 0.014198, - 0.02107365, - 0.013681231, - -0.004939958, - 2.4890704E-05, - -0.013795095, - -0.0029144876, - 0.0011813418, - 0.009074107, - 0.02005763, - 0.02730991, - -0.014250552, - -0.04628145, - 0.0033787035, - -0.00058848126, - 0.026398994, - 0.019164234, - -0.011745538, - -0.013146944, - -0.014294346, - -0.01223603, - 0.011360151, - 0.0032714081, - 0.010457995, - 0.0053516207, - -0.009529564, - -0.015844652, - 0.020600675, - 0.020443017, - -0.009739775, - -0.00543045, - 0.0070727235, - -0.0059778746, - -0.014714768, - -0.00076091994, - -0.010922211, - -0.0054479674, - 0.024156744, - -0.0074186954, - -0.020162735, - 0.012376171, - -0.020022595, - 0.008846378, - -0.019829901, - 0.006280053, - -0.011193735, - 0.011763056, - -0.02412171, - 0.014022823, - 0.030690802, - -0.016676737, - -0.0063413642, - -0.0038560575, - 0.006113636, - -0.02643403, - 0.014600904, - -0.039064206, - 0.016676737, - 0.015564371, - 0.013138185, - -0.0067355097, - -0.025172764, - 0.00253348, - -0.02541801, - 0.019059127, - 0.017132195, - 0.011176216, - 0.003867006, - 0.015616924, - 0.026521618, - -0.0185336, - 0.03375638, - -0.017219782, - 0.022212293, - -0.0042874278, - 0.007436213, - -0.012367412, - -0.013681231, - -0.0017254817, - 0.01050179, - -0.002476548, - 0.015581888, - 0.023806393, - -0.030971084, - -0.009941227, - -0.010895935 - ], - "HOTEL10_VECTORIZE_DESCRIPTION": [ - -0.028266374, - -0.010204822, - 0.049104568, - 0.012579697, - -0.023820179, - -0.020213226, - 0.007865659, - 0.017909775, - 0.0038390844, - 0.012713619, - -0.0011740456, - 0.0146688735, - 0.009137914, - 0.008490626, - -0.016311644, - 0.027319996, - -0.024480859, - 0.02508797, - -0.007874587, - 0.020177513, - 0.0048747445, - 0.011651174, - -0.032819707, - -0.0076692407, - 0.012195789, - 0.021820284, - -0.025284387, - -0.018909723, - -0.008111182, - 0.014588521, - -0.0041426397, - -0.026159342, - 0.008222783, - -0.033373248, - -0.00911113, - 0.023427343, - -0.010169109, - 0.014365318, - 0.026766453, - -0.020481069, - 0.014552808, - 0.0029127935, - -0.022177408, - -0.01821333, - -0.00019418624, - 0.0045198523, - -0.0044752117, - 0.014017122, - -0.012588626, - 0.00724962, - -0.0020188673, - -0.0069103516, - 0.0140974745, - -0.056711312, - -0.007740665, - 0.03512316, - 0.0036761465, - -0.0125707695, - 0.010320887, - 0.0030355551, - 0.020088231, - 0.025998637, - 0.02457014, - 0.008504018, - -0.01849903, - -0.006642509, - 0.002493173, - 0.013151096, - -0.02983772, - -0.010240534, - 0.013820703, - -0.010186966, - -0.011097632, - 0.0010244999, - 0.012347567, - 0.010436952, - 0.009633423, - -0.027819969, - -0.013142168, - 0.01887401, - -0.0040890714, - -0.01228507, - -0.008392417, - 0.020802481, - -0.0066291164, - -0.017436584, - -0.018186547, - -0.006472875, - 0.033533957, - 0.039926477, - 0.024016598, - 0.005182764, - -0.0025512055, - -0.00363597, - 0.010767292, - 0.002081364, - 0.002167297, - -0.019231133, - 0.005312221, - 0.027891394, - 0.022195265, - -0.024016598, - 0.01976682, - 0.020695344, - 0.007356757, - -0.02678431, - 0.020409644, - 0.00081915344, - 0.0015311696, - 0.020873904, - -0.034069642, - -0.004481908, - -0.016311644, - 0.00087160605, - -0.010892286, - -0.029641302, - -0.043604854, - -0.0066246525, - -0.02621291, - 0.018391892, - 0.010276247, - -0.0046426137, - 0.01835618, - -0.0071915872, - -0.03896224, - -9.918564E-05, - -0.022945225, - 0.0072987243, - 0.006057718, - -0.018516885, - -0.0074906787, - 0.030301983, - -0.003718555, - -0.0017699965, - 0.0027520878, - 0.013633213, - -0.008240639, - -0.009258443, - -0.014847435, - 0.0069505284, - 0.025248675, - -0.0006439394, - 0.005655953, - -0.00094749493, - 0.0054193586, - -0.027212858, - 0.012079723, - 0.00031694767, - -0.0146688735, - 0.053247206, - 0.0010663503, - -0.0013425635, - 0.013838559, - -0.016293788, - -0.010588731, - 0.005437215, - -0.030337695, - 0.023355918, - -0.010160182, - 0.022695238, - -0.009758417, - -0.011463684, - -0.002357019, - 0.031266216, - -0.0022855944, - -0.01332073, - 0.011526181, - -0.023855891, - -0.015124206, - -0.007454966, - 0.026105773, - 0.014034978, - 0.0078299465, - 0.060782526, - 0.03242687, - 0.006651437, - -0.00027300464, - -0.009463789, - -0.01999895, - 0.00088611426, - 0.0011494933, - -0.015945593, - 0.05106875, - -0.008512946, - 0.006392522, - 0.009463789, - 0.008477234, - 0.012436847, - 0.0058211233, - 0.021766715, - -0.0034194635, - -0.008227247, - -0.02739142, - -0.015329553, - 0.029855577, - 0.009936979, - -0.03449819, - -0.012561841, - 0.008437057, - 0.010124469, - -0.0182669, - -0.010990495, - 0.009660208, - 0.007115698, - 0.0039551496, - -0.030659106, - 0.008575443, - 0.01242792, - -0.013070743, - -0.002513261, - -0.01355286, - 0.034373198, - 0.01939184, - 0.024302296, - 0.00094861095, - -0.029016335, - -0.016240219, - 0.01266005, - 0.009383436, - 0.016972324, - 0.0030556433, - 0.010936926, - -0.0019251222, - 0.00223649, - -0.02151673, - 0.0073076524, - -0.0040488946, - -0.004399323, - 0.013445723, - 0.020034663, - 0.0015356337, - -0.0146688735, - -0.007606744, - -0.017240167, - 0.034087498, - 0.01788299, - -0.0034373198, - 0.008160287, - -0.005022058, - 0.0074906787, - -0.017427657, - -0.01962397, - -0.03199832, - 0.00090397045, - 0.0034083033, - 0.005026522, - 0.014633161, - 0.015990233, - 0.008004044, - -0.0039395257, - -0.0033458066, - 0.016570559, - -0.007843339, - -0.008209391, - 0.04217636, - 0.008602227, - -0.022230977, - -0.0022309097, - 0.004245313, - 0.019802533, - -0.024427291, - 0.008767397, - 0.025337957, - 0.0040913033, - 0.0046158293, - 0.025962925, - 0.0026962871, - 0.014159972, - -0.006062182, - -0.026320048, - -0.0059461165, - 0.0043770024, - 0.018659735, - -0.048568882, - 0.04471194, - -0.004151568, - -0.015311697, - -0.0228738, - 0.0034373198, - 0.016150938, - -0.024105879, - -0.02951631, - 0.037069485, - -0.012954677, - 0.021338167, - -0.0080442205, - -0.00863794, - 0.0039618458, - -0.005539888, - 0.02569508, - -0.024195159, - 0.02146316, - -0.01896329, - -0.02715929, - 0.0061648553, - 0.02649861, - 0.00011501908, - -0.009713776, - 0.016365213, - -0.012767187, - 0.016222363, - -0.0057496983, - 0.005727378, - 0.020195369, - 0.0031784046, - 0.018284755, - 0.010624442, - 0.008294208, - 0.0034060713, - -0.011856521, - -0.008905783, - -0.021106036, - 0.020498924, - 0.004077911, - -0.019588258, - 0.01068694, - -0.026802165, - 0.033926792, - -0.026748598, - 0.0013124312, - -0.003734179, - 0.011677959, - 0.021481017, - 0.0018871778, - 0.005276509, - -0.023605905, - 0.012901109, - 0.0075487113, - -0.011722599, - -0.010561946, - 0.025141539, - 0.021213174, - -0.002415052, - 0.0077674496, - -0.017088389, - 0.013892128, - 0.0061871754, - 0.007365685, - -0.013526076, - 0.0012945749, - -0.0026895911, - -0.017008036, - -0.016945539, - -0.016267003, - -0.0016226828, - -0.0010440301, - -0.0397122, - 0.01120477, - -0.00487028, - 0.008812037, - 0.01858831, - -0.012106508, - -0.0029194898, - 0.018713305, - 0.032444727, - 0.018007984, - -0.006495195, - -0.0029663623, - 0.000520341, - -0.018195475, - -0.0049684895, - 0.0021873852, - 0.007718345, - -0.014865291, - 0.012249357, - 0.031551916, - -0.019820388, - -0.010722652, - 0.020838192, - 0.025284387, - 0.015302769, - -0.0051782997, - -0.0036315059, - 0.011883305, - 0.0025579014, - 0.015561684, - 0.010776221, - 0.020552494, - 0.01844546, - -0.0071380185, - 0.01585631, - 0.0073880055, - -0.016972324, - -0.032605432, - 0.027034296, - 0.0037029309, - -0.016365213, - -0.0054997117, - -0.02701644, - -0.0100709, - 0.0017409801, - -0.009142377, - -0.020195369, - 0.0012800668, - 0.00072596635, - -0.017499082, - 0.014249252, - 0.004830104, - 0.022838088, - -0.025159394, - 0.01176724, - -0.0062496723, - -0.0049059927, - -0.013722494, - 0.0011416812, - -0.014445671, - -0.012740403, - -0.022909513, - 0.006999633, - -0.008173678, - 0.02457014, - 0.0058434433, - 0.008405809, - -0.021855997, - -0.014106403, - 0.012445776, - -0.014052834, - -0.029052047, - -0.0072272993, - 0.009999475, - -0.010151253, - 0.0069907047, - 0.007968332, - -0.0041984404, - 0.0036225778, - 0.002428444, - -0.0027230715, - 0.0030556433, - -0.057782684, - -0.02664146, - -0.027927106, - -0.023195213, - 0.010151253, - 0.012785044, - -0.01087443, - 0.005713986, - -0.017249094, - -0.0066469726, - 0.0013559556, - -0.014249252, - -0.0011539573, - 6.075295E-05, - 0.0054729274, - -0.008704901, - 0.0022967546, - 0.009258443, - 0.028141381, - 0.04456909, - -0.004249777, - 0.02028465, - -0.01713303, - -0.0027208393, - -0.001994315, - -0.0017041516, - -0.016508063, - -0.027123578, - 0.020677486, - -0.019123998, - 0.011606534, - 0.0013302873, - 0.020873904, - 0.025195107, - 0.016079513, - -0.010267318, - 0.033141118, - -0.004986346, - 0.010695867, - 0.0061648553, - -0.0050666984, - 0.0014887612, - -0.008954887, - -0.015704533, - -0.0044372673, - 0.00783441, - -0.00070587813, - -0.021445304, - 0.029677015, - 0.025480807, - 0.0012253822, - -0.026141485, - -0.03821228, - 0.0052318685, - -0.0069192797, - -0.018695448, - -0.01539205, - -0.6519658, - -0.019606115, - -0.008508482, - -0.024409434, - -0.0005013688, - -0.017079461, - 0.010320887, - 0.0074058617, - 0.08799539, - -0.017052677, - 0.0017543723, - -0.02946274, - 0.0055800644, - 0.024338009, - 0.0007348945, - 0.027873538, - -0.0013470276, - -0.008338848, - -0.0010763945, - 0.0062184236, - -0.006995169, - 0.0065442994, - -0.006254136, - -0.015802743, - -0.010606587, - 0.02612363, - -0.007709417, - -0.0025221892, - -0.012838612, - -0.008593299, - -0.0030913558, - 0.01355286, - 0.0009396828, - 0.002598078, - -0.035051733, - -0.017141959, - 0.036605224, - -0.0034551758, - 0.025070114, - -0.010454808, - -0.011044064, - 0.0027878003, - -0.12127935, - 0.0038413163, - 0.016927684, - -0.020909617, - 0.0068880315, - 0.011115489, - 0.010820861, - -0.01129405, - -0.012561841, - 0.028409224, - 0.014445671, - 0.028159237, - -0.010606587, - 0.019981096, - -0.007629064, - 0.008289744, - -0.013106455, - -0.0036181137, - -0.020963186, - -0.011606534, - 0.0106422985, - 0.010892286, - 0.01849903, - 0.010240534, - 0.012776116, - 0.001468673, - -0.016659841, - -0.011695815, - -0.020891761, - 0.009615567, - -0.0125707695, - 0.021570297, - 0.0036739144, - -7.972517E-05, - 0.0034708001, - 0.018534742, - 0.012579697, - 0.021820284, - 0.0036471302, - 0.028319944, - 0.020356076, - -0.0055889925, - -0.01228507, - -0.014615305, - 0.01924899, - -0.018061552, - 0.21384592, - -0.013142168, - 0.00155907, - 0.17913346, - -0.0026739668, - -0.027694976, - -0.004062287, - 0.014427815, - -0.011044064, - 0.018034767, - 0.007901371, - 0.014570665, - -0.022391682, - 0.028337799, - -0.001557954, - 0.016704481, - 0.015150991, - -0.0117136715, - 0.011008351, - -0.016775906, - -0.0065353713, - 0.0025579014, - -0.0078076264, - -0.031051943, - 0.010079828, - -0.025123682, - 0.0031047477, - -0.015883096, - -0.031212648, - -0.019873958, - 0.0147402985, - -0.0071067703, - 0.0054818555, - -0.037855156, - -0.0028145844, - -0.023034506, - -0.016731266, - 0.00588362, - -0.0032542937, - 0.014276037, - 0.030176988, - -0.014508167, - 0.005218476, - -0.011695815, - 0.015008141, - 0.013026102, - -0.0368195, - 0.0017376321, - -0.0079236915, - 0.003566777, - 0.025641512, - 0.018624023, - 0.021641722, - 0.0018905258, - -0.025641512, - 0.0035645452, - -0.0059014764, - 0.012543985, - 0.06913923, - 0.025337957, - 0.0035288327, - 0.0048167114, - 0.036962345, - 0.00969592, - -0.017481226, - 0.0057452344, - 0.004995274, - -0.021820284, - -0.020481069, - -0.020409644, - -0.0031404602, - 0.0019262383, - 0.011535109, - 0.011508325, - -0.009419149, - 0.0015155455, - 0.008334384, - 0.002252114, - -0.025962925, - 0.037533745, - 0.03656951, - -0.012356495, - 0.009829842, - 0.0022777824, - 0.0054193586, - 0.0009357768, - 0.0005814427, - 0.01068694, - 0.007633528, - -0.027730688, - 0.0025355814, - -0.008325456, - 0.008218319, - -0.0009954835, - 0.0019262383, - -0.01812405, - 0.0022242137, - 0.01896329, - 0.016017018, - -0.004412715, - -0.0113565475, - -0.011919018, - -0.003028859, - 0.018624023, - -0.0009608871, - -0.02598078, - 0.019802533, - 0.009785201, - 0.02362376, - -0.0068746395, - 0.003720787, - 0.026712885, - 0.0038725648, - 0.0020244473, - 0.009633423, - 0.008731685, - -0.009910194, - 0.003278846, - -0.002084712, - 0.0007655848, - 0.008579907, - -0.009722704, - -0.017231239, - 0.0044886037, - -0.022623813, - -0.002159485, - 0.038426556, - -0.003216349, - 0.020731056, - 0.010267318, - -0.026909303, - 0.0023637153, - -0.028694924, - 0.026712885, - -0.015240272, - -0.010463737, - -0.012517201, - 0.0039127413, - -0.027123578, - -0.00021873853, - -0.026427185, - -0.016891971, - -0.019606115, - -0.023427343, - -0.00503545, - -0.0071603386, - -0.028319944, - -0.0038413163, - 0.025820075, - 0.011472613, - -0.0046426137, - -0.018007984, - 0.015981305, - 0.005477391, - -0.0009960415, - -0.0029194898, - -0.010561946, - 0.022945225, - 0.014927789, - -0.0042475453, - -0.004508692, - -0.010901214, - 0.004084607, - -0.013945697, - 0.020016808, - -0.017159814, - 0.01350822, - 0.011606534, - 0.012892181, - 0.009535214, - 0.0007382425, - -0.00085430784, - -0.038569406, - 0.04456909, - -0.02240954, - -0.038605116, - 0.016909827, - -0.014865291, - -0.09435219, - 0.012454703, - 0.0112851225, - -0.014704586, - -0.03214117, - 0.0045577968, - 0.009454861, - 0.002079132, - 0.016508063, - 0.016347356, - 0.0071380185, - 0.010329816, - 0.01713303, - 0.034962453, - 0.014713514, - -0.0070442734, - 0.0023101466, - 0.011026207, - 0.0143831745, - 0.021731002, - 0.003535529, - 0.015981305, - -0.012972534, - -0.024909407, - -0.012883252, - -0.0051425872, - -0.011079776, - -0.0018291451, - 0.0041984404, - -0.018606167, - 0.011731528, - 0.020356076, - -0.0072317636, - -0.0004051127, - 0.005687202, - 0.015508115, - 0.005897012, - 0.017918702, - -0.0056916657, - -0.0011729295, - 0.0008225015, - 0.0013314034, - -0.030159133, - 0.009945907, - 0.014776011, - -0.004597973, - -0.01275826, - 0.0075487113, - -0.005164908, - 0.0046336856, - -0.0007694909, - 0.028355656, - -0.010106613, - 0.023302348, - -0.0019452105, - -0.020088231, - -0.008012973, - 0.0002504054, - -0.009160234, - 0.015918808, - 0.0150974225, - 0.0027855681, - 0.018713305, - -0.0027342315, - 0.021159604, - -0.023998741, - 0.024284441, - -0.038890816, - -0.0059327246, - 0.00922273, - 0.022016702, - -0.0031359962, - 0.0048970645, - 0.0073031886, - 0.017686572, - -0.020248938, - 0.01162439, - 0.020123944, - -0.00020130082, - -0.023820179, - -0.009722704, - -0.0034328557, - 0.020159656, - 0.00045393824, - -0.005298829, - -0.008919175, - -0.000955865, - 0.029944858, - -0.009312011, - 0.0029016335, - -0.00096869917, - -0.017909775, - 0.011561894, - -0.021534584, - -0.0041158553, - 0.017445514, - -0.010124469, - 0.013838559, - -0.009981619, - -6.221772E-05, - 0.01073158, - 0.017579434, - -0.003196261, - -0.013463579, - -0.0027386956, - 0.012329711, - 0.03214117, - -0.013374299, - -0.021481017, - -0.010838717, - 0.017874062, - 0.024927264, - -0.008231711, - -0.010892286, - 0.013454651, - -0.012999319, - 0.0010780684, - -0.007008561, - 0.004575653, - -0.0075710313, - 0.013186809, - -0.024730846, - -0.012936821, - -0.0022130536, - -0.021713147, - 0.010392312, - 0.0052631167, - -0.0082584955, - -0.007637992, - -0.00057056156, - -0.0010334279, - 0.0066871494, - -0.00016391439, - 0.018007984, - -0.01247256, - 0.00901292, - 0.024230871, - 0.01774907, - -0.002582454, - -0.0055979206, - 0.02310593, - 0.0228738, - 0.028980622, - 0.013570717, - -0.004691718, - -0.0074772863, - 0.034819603, - 0.008262959, - 0.011544038, - 0.01087443, - 0.0014586288, - -0.025248675, - 0.033694662, - -0.019677538, - 0.013276089, - -0.01962397, - 0.008437057, - -0.014463527, - 0.012169004, - 0.008079933, - -0.022052415, - -0.01976682, - 0.00884775, - -0.03185547, - 0.0068791034, - 0.0003638202, - -0.021641722, - 0.00277664, - 0.005990757, - -0.020088231, - 0.02249882, - -0.015543828, - 0.018007984, - -0.016240219, - 0.001033986, - -0.00863794, - 0.0074326457, - 0.01896329, - -0.004439499, - 0.018186547, - 0.026320048, - -0.0042787935, - -0.014106403, - 0.016856259, - 0.011927946, - 0.021391734, - 0.00020688088, - -0.0318019, - -0.01091907, - 0.008919175, - 0.02310593, - -0.010061972, - 0.0020356076, - -0.01609737, - -0.0015780422, - -0.016508063, - -0.005548816, - 0.009633423, - 0.0051381234, - 0.015383122, - -0.007164803, - -0.0010284059, - -0.004785463, - -0.0009452629, - 0.008249567, - 0.005615777, - -0.004265401, - 0.03194475, - 0.0020969883, - -0.0057764826, - 0.018159762, - 0.005562208, - 0.011044064, - 0.009990548, - 0.009990548, - -0.003368127, - 0.024534427, - 0.009686992, - 0.001738748, - 0.014829579, - 0.027873538, - 0.001909498, - -0.01313324, - -0.04467623, - 0.0027520878, - 0.025248675, - 0.0066469726, - -1.7960832E-05, - 0.0035243686, - -0.002245418, - 0.009678064, - 0.002250998, - -0.02207027, - -0.011401188, - 0.012276142, - -0.016749121, - 0.048961718, - 0.019141853, - 0.0043836986, - 0.023963029, - -0.019284703, - -0.0025065648, - -0.013070743, - -0.001299039, - -0.011338691, - -0.0017197758, - 0.18613309, - -0.011704743, - 0.024962977, - -0.016829474, - 0.01129405, - -0.004597973, - -0.0034596398, - 0.026855733, - -0.01073158, - 0.020552494, - 0.010704796, - -0.007633528, - -0.00041097176, - -0.004334594, - 0.022016702, - 0.021945277, - -0.0030601074, - 0.0025422773, - -0.0011065268, - 0.016641984, - 0.0016204508, - 0.0030578752, - -0.014820651, - 0.010660155, - 0.019052573, - -0.01962397, - 0.025212964, - -0.020481069, - 0.012374351, - 0.021284597, - -0.036926635, - 0.036176674, - -0.018204402, - 0.01807941, - -0.019927526, - 0.013633213, - -0.008691508, - 0.0107851485, - -0.03012342, - 0.005910404, - -0.021409592, - 0.014999214, - 0.018677592, - -0.014186756, - -0.019498978, - 0.00880311, - 0.008030829, - -0.008620083, - 0.030944806, - 0.008526338, - 0.009633423, - 0.027944963, - -0.017231239, - 0.020195369, - -0.030891236, - 0.007428182, - -0.015445618, - -0.011311906, - 0.027819969, - -0.0054238224, - -0.015552755, - -0.0022309097, - -0.019981096, - 0.010615515, - -0.009963763, - -0.0008492858, - -0.031194793, - -0.0039618458, - -0.0050443783, - -4.9418446E-05, - -0.00037609634, - -0.023570193, - 0.0061871754, - 0.03892653, - 0.00044640515, - 0.0012030619, - -0.0054729274, - 0.00094972696, - -0.0018737856, - 0.013615358, - 0.019231133, - 0.021820284, - 0.040640727, - 0.008606692, - 0.005133659, - -0.0179812, - -0.013651069, - -0.009419149, - 0.01087443, - 0.0160438, - -0.027230715, - 0.029177042, - -0.008343312, - -0.022570245, - 0.0034886564, - -0.010240534, - 0.011383331, - 0.012722547, - -0.004002022, - 0.026623603, - -0.0013146632, - -0.015454547, - 0.022980938, - 0.01162439, - -0.010838717, - 0.008231711, - -0.009615567, - 0.010204822, - -0.005700594, - -0.04453338, - -0.01369571, - 0.007454966, - -0.0009625611, - -0.02537367, - -0.009294155, - -0.006584476, - 0.026570035, - -0.008240639, - 0.027319996, - 0.024266584, - 0.0030400192, - 0.008718292, - 0.0042073685, - 0.012713619, - -0.019177565, - -0.0012767187, - 0.004493068, - -0.001122709, - 0.02244525, - -0.0076246, - -0.029623447, - -0.0031672446, - 0.016436638, - 0.0077272733, - 0.0015780422, - -0.009526286, - 0.0026784309, - 0.011311906, - -0.0070487373, - -0.013802848, - 0.014052834, - 0.017999057, - 0.0088075735, - 0.0018425373, - -0.00988341, - -0.0076424563, - -0.016338428, - 0.035319574, - -0.013659998, - 0.020123944, - 0.06542514, - 0.01261541, - 0.0059237964, - -0.010195894, - 0.004508692, - 0.009276299, - -0.0012443544, - -0.015400978, - 0.024534427, - -0.00380114, - 0.0032520615, - -0.010811933, - 0.008919175, - 0.00033173483, - -0.001817985, - -0.007968332, - -0.020409644, - 0.018284755, - -0.0047006463, - 0.005713986, - -0.011901162, - 0.017356232, - 0.008432593, - -0.018034767, - 0.009124521, - -0.012722547, - -0.0075040706, - -0.0026360224, - 0.010303031, - 0.0231595, - -0.0068701752, - -0.0005708406, - 0.012177933, - -0.042247783, - 0.024373721, - 0.00082752353, - -0.0049506333, - 0.001898338, - -0.011419044, - -0.003917205, - -0.0051604435, - -0.027516413, - -0.029427027, - -0.015543828, - 0.023052363, - 0.029855577, - -0.019731108, - -0.00089615834, - 0.0014262645, - -0.03853369, - 0.009588783, - -0.015606324, - 0.0049818815, - -0.018016912, - 0.0111422725, - 0.014901004, - -0.009419149, - -0.032391157, - -0.0014619769, - -0.009678064, - 0.023552336, - -0.022320257, - 0.003908277, - 0.01858831, - 0.014347462, - -0.017222311, - -0.04317631, - 0.021213174, - -0.009829842, - -0.0028346728, - 0.0040377346, - 0.0065532275, - 0.0066559007, - 0.0006311053, - 0.009874482, - 0.0024708526, - -0.010838717, - 0.003633738, - -0.019516833, - -0.001304619, - -0.005633633, - -0.010803005, - 0.025016544, - 0.002497637, - 0.007932619, - 0.003122604, - 0.009338796, - 0.024105879, - 0.026373617, - -0.010124469, - 0.009294155, - -0.010374456, - -0.0069907047, - -0.0024396041, - 0.013909984, - 0.026623603, - 0.015302769, - -0.010481593, - -0.023855891, - -0.018374037, - 0.002005475, - 0.00030076547, - -0.026980728, - 0.018749017, - -0.008173678, - -0.0053881104, - -0.015267056, - -0.018766873, - -0.0011065268, - 0.017900847, - -0.010660155, - 0.0001821891, - 0.014177828, - 0.0065532275, - 0.009437005, - 0.002006591, - 0.0065934043, - 0.009329868, - 0.02583793, - -0.015695605, - -0.0018112889, - 0.0021137283, - 0.033337537, - -0.008222783, - 0.030248413, - -0.0039127413, - -0.009910194, - 0.017677644, - -0.0079951165, - -0.0025266532, - 0.023427343, - -0.013838559, - -0.01139226, - 0.035051733, - 0.007071058, - -0.018052625, - -0.025677225, - -0.002421748, - 0.0110708475, - 0.00088890427, - 0.017909775, - 0.00026310002, - -0.00035321809, - -0.002863689, - 0.03440891, - -0.010927998, - -0.0010289638, - -0.029302035, - 0.013526076, - 0.0013548397, - -0.02649861, - 0.018231187, - -0.0010111077, - -0.018856153, - -0.016740194, - 0.008477234, - 0.014999214, - -0.012061867, - -0.017454442, - 0.019695396, - -0.016374141, - -0.00896828, - -0.0046560057, - -0.0026293264, - 0.01939184, - 0.0065353713, - -0.013436795, - 0.005227404, - -0.0036962347, - 0.007164803, - 0.024766559, - 0.034319628, - -0.020570349, - 0.01948112, - -0.009258443, - -0.013981409, - -0.033391107, - -0.018695448, - 0.01953469, - -0.00866026, - -0.015124206, - 0.004575653, - 0.008209391, - -0.00011746035, - 0.050283078, - -0.0023123787, - 0.0010267318, - -0.007343365, - 0.008401345, - 0.006142535, - -0.008459378, - -0.0037475713, - 0.004414947, - -0.007071058, - -0.020302506, - 0.00066123763, - -0.018463317, - 0.023980886, - -0.023052363, - -0.009749489, - -0.01073158, - 1.721101E-05, - 0.007115698, - 0.021177461, - -0.010767292, - 0.024927264, - 0.011035135, - 0.009776273, - 0.021159604, - -0.002497637, - -0.018766873, - 0.006316633, - 0.03199832, - -0.013972482, - -0.0060309335, - -0.036123104, - -0.019284703, - 0.015418834, - -0.007972796, - -0.0037832838, - -0.0037832838, - -0.044319104, - -0.02189171, - -0.015034925, - 0.016570559, - -0.022998793, - 0.006142535, - 0.005374718, - -0.0020478836, - -0.020981042, - -0.012258286, - 0.014579592, - -0.0055577443, - -0.0231595, - -0.0064773387, - 0.013901057, - -0.011338691, - -1.8449087E-05, - -0.035855263, - 0.018240115, - -0.025587944, - -0.029909145, - -1.9233785E-05, - -0.010044116, - -0.012963606, - 0.02607006, - 0.016686624, - -0.015079566, - -0.016213436, - 0.012838612, - -0.02348091, - -0.010990495, - -0.012597553, - -0.0065442994, - -0.012267213, - 0.015240272, - -0.0056202407, - 0.011883305, - -0.021855997, - -0.010320887, - -0.002682895, - -0.0005859068, - -0.006892496, - 0.024980832, - -0.013115384, - 0.01566882, - 0.023730898, - 0.017070534, - -0.0005725146, - 0.0059952214, - -0.015749173, - 0.028373512, - -0.0006534255, - 0.013204665, - -0.028837774, - -0.024105879, - -0.016383069, - -0.008102254, - 0.02151673, - 0.004095767, - -0.015365265, - 0.011731528, - -0.0080219, - -0.010231606, - 0.00076893286, - -0.006240744, - 0.04589045, - 0.02969487, - -0.0039149732, - 0.0067407177, - -0.04606901, - 0.02301665, - 0.020016808, - 0.012535057, - -0.009963763, - -0.007017489, - 0.026462898, - 0.014445671, - -0.0036315059, - 0.020195369, - 0.010436952, - -0.0019876189, - -0.020838192, - 0.012490416, - -0.016070586, - 0.003209653, - 0.017686572, - 0.0043435222, - 0.008704901, - 0.03040912, - 0.011463684, - 0.0011617694, - 0.0045511005, - 0.019945383, - -0.017490154, - -0.009829842, - -0.0010551902, - 0.024659421, - -0.014972429, - 0.015508115, - -0.025659367, - -0.02151673, - 0.00795494, - 0.005468463, - -0.048926003, - -0.014106403, - -0.0035109764, - 0.018909723, - -0.013436795, - 0.0068567833, - 0.034444623, - 0.026605748, - 0.01543669, - -0.019552546, - -0.0018045928, - -0.015150991, - 0.0051291953, - -0.014936716, - 0.023570193, - -0.011195841, - 0.014034978, - 0.0007248504, - 0.016668769, - 9.1443304E-05, - -0.01548133, - 0.004339058, - -0.0140974745, - 0.0014552808, - -0.0014865291, - -0.005164908, - -0.003216349, - 0.012785044, - 0.03564099, - 0.006923744, - -0.012874325, - -0.012499345, - -0.0051559797, - -0.012624337, - 0.017409801, - -0.045211915, - 0.015177775, - 0.021177461, - -0.0015523739, - 0.013186809, - -0.017490154, - -0.0033123263, - -0.03144478, - -0.0015925504, - 0.018606167, - 0.020088231, - 0.0010836485, - 0.02123103, - -0.00018065459, - -0.004077911, - -0.012606482, - -0.015570612, - 0.0027878003, - 0.00571845, - 0.0076513845, - -0.013329658, - -0.00922273, - -0.0071424823, - 0.009651279, - 0.005312221, - 0.022534532, - 7.8260404E-05, - -0.0013191273, - -0.006347881, - -0.015267056 - ], - "SEARCH_VECTORIZE_DESCRIPTION": [ - -0.011113605, - -0.01902812, - 0.047524072, - -0.004909588, - -0.02193134, - -0.0024247447, - -0.017521033, - 0.020359533, - 0.008362942, - -0.0029471396, - -0.009930126, - 0.023872986, - 0.0032314518, - -0.006559986, - -3.7381E-05, - 0.017169688, - -0.027478898, - 0.0033747638, - 0.017373098, - 0.0042461925, - -0.009306027, - 0.012500495, - -0.0072580534, - -0.017974084, - 0.0152372895, - 0.010521866, - -0.034838658, - 0.014386664, - 0.023614101, - 0.020082155, - 0.009440092, - -0.013702465, - 0.029531494, - -4.2112315E-05, - -0.021764915, - 0.011612886, - 0.0010904416, - 0.030400611, - -0.0018688332, - -0.00045536197, - 0.02710906, - 0.012824102, - -0.033063438, - -0.0021751046, - -0.00647215, - -0.0067633963, - -0.015144831, - -0.0032823044, - -0.003850929, - 0.024723612, - 0.0061346735, - -0.018149758, - 0.020341042, - -0.031066319, - -0.017400837, - 0.013711711, - 0.013841154, - -0.028458966, - 0.024427742, - -0.013656236, - -0.0042901104, - 0.03385859, - 0.024335282, - -0.023799019, - -0.004003487, - -0.016651917, - -0.007475333, - 0.009435469, - -0.01843638, - 0.023392199, - 0.016836835, - -0.013480563, - -0.020470485, - 0.0032337634, - 0.0155793885, - 0.011427967, - -0.0038255027, - -0.0055568027, - 0.0042762416, - -0.0011950362, - -0.022578556, - 0.00080439576, - 0.00058162666, - 0.027460406, - -0.007849793, - -0.006157788, - -0.016411522, - 0.0013614629, - 0.0066200844, - 0.021210158, - 0.006291854, - 0.0066663143, - 0.015098601, - 0.0049142106, - -0.0027113685, - -0.011187573, - 0.014321943, - -0.01877848, - 0.016466998, - 0.035116035, - 0.041088905, - 0.0062733623, - -0.0036082235, - 0.0051777195, - -0.011538918, - 0.005663131, - 0.016245095, - -0.0070130364, - 0.0041514216, - 0.0025333844, - -0.014710272, - -0.021949833, - -0.019693827, - 0.016642671, - -0.021395078, - -0.00067841995, - -0.045563933, - -0.0076602516, - -0.012065936, - 0.04186556, - 0.025740664, - -0.0032684356, - 0.018676775, - 0.007701858, - -0.0063935593, - 0.010900949, - -0.014081549, - -0.03594817, - 7.56288E-05, - -0.0202116, - -0.004877227, - 0.004551308, - -0.019638352, - 0.014922928, - 0.022079276, - 0.013452825, - -0.007230316, - 0.0034880263, - -0.0012458888, - 0.006430543, - -0.009745209, - -0.0009673552, - 0.004089012, - 0.0064952644, - 0.010078061, - -0.03187996, - 0.00884373, - 0.019379465, - -0.010900949, - 0.042420316, - -0.013942859, - 0.013526793, - 0.020895798, - -0.009370748, - -0.010373931, - -0.01941645, - -0.012472757, - -0.016309816, - 0.02538932, - 0.014959912, - -0.023503149, - -0.014220238, - -0.017262148, - 0.016827589, - 0.0028939755, - 0.0069252, - -0.017631985, - 0.0044426685, - -0.0069945445, - -0.014811977, - 0.025814632, - 0.007724973, - 0.008409171, - 0.05321956, - 0.017317623, - 0.017104967, - -0.0077388417, - -0.012213871, - -0.032989472, - 0.007253431, - -0.01757651, - -0.01355453, - 0.039905425, - -0.009985602, - 0.016642671, - 0.020156123, - 0.0031621074, - 0.008362942, - 0.020988258, - 0.0007292726, - 0.009735962, - 0.00022392483, - -0.033729147, - -0.0004244459, - -0.0065877237, - 0.0067079207, - -0.02152452, - 0.0028477458, - 0.007859039, - -0.03415446, - 0.0026119747, - 0.00070442416, - 0.0032314518, - 0.010355439, - 0.0029933692, - -0.02011914, - -0.008251991, - 0.016836835, - -0.014266467, - -0.02450171, - -0.024982497, - 0.00016859372, - 0.023799019, - 0.026276927, - -0.019841762, - 0.00884373, - -0.046377577, - 0.0038278142, - -0.0072488077, - 0.030511564, - 0.016457751, - 0.0010476792, - 0.03489413, - -0.011622132, - -0.013989089, - 0.020082155, - -0.012158396, - 0.0026397125, - -0.0021704817, - 0.00041982293, - 0.012472757, - -0.014460632, - 0.009278289, - -0.038204174, - 0.023096329, - 0.008423041, - 0.022449113, - 0.013794925, - -0.030567039, - -0.023262756, - -0.023669576, - -0.023928462, - -0.0030650252, - -0.014035319, - -0.005649262, - -0.017539525, - 0.03975749, - 0.014340434, - 0.004988178, - 0.010725277, - -0.021395078, - 0.0204335, - 0.020969765, - -0.001508242, - 0.022338163, - 0.025111942, - -0.0220238, - -0.011150589, - -0.02113619, - 0.010170521, - -0.04145874, - 0.0031875337, - 0.019397957, - -0.014987649, - 0.0052239494, - -0.0027760898, - -0.027719293, - -0.0041930284, - 0.003980372, - -0.018880185, - -0.010503374, - 0.0015810537, - 0.021709438, - -0.02840349, - 0.026055025, - 0.0195274, - -0.014802731, - -0.033063438, - 0.002169326, - -0.030234184, - 0.017724445, - -0.024483217, - 0.030141726, - -0.0010927531, - 0.0030003036, - -0.009033272, - -0.022892918, - -0.013009021, - -0.032342255, - 0.011520427, - -0.0029956808, - 0.009976356, - -0.02231967, - -0.01941645, - 0.0033747638, - 0.021450553, - 0.002815385, - -0.021247143, - 0.023188788, - -0.026776208, - 0.0052470644, - 0.022948394, - 0.0055984096, - 0.009185829, - -0.0126854135, - 0.010373931, - 0.009680486, - 0.003423305, - -0.008321336, - 0.015070863, - 0.0077989404, - -0.02720152, - 0.022005308, - -0.019379465, - -0.021358093, - -0.035226986, - -0.01464555, - 0.021284126, - -0.0141092865, - -0.01364699, - 0.02172793, - 0.003841683, - 0.0023057032, - 0.008154908, - 0.009782192, - -0.024982497, - 0.0041560447, - 0.021265635, - -0.020341042, - 0.016411522, - 0.038389094, - 0.02729398, - 0.0078914, - 0.02899523, - -0.026665257, - 0.01569034, - -0.0048125056, - 0.01921304, - -0.017225165, - 0.016217358, - 0.023170296, - -0.012824102, - 0.015255782, - 0.008191892, - 0.0035781742, - -0.011326262, - -0.014756502, - 0.008293598, - -0.0021658586, - 0.010189013, - 0.02440925, - -0.0067633963, - -0.0093984855, - 0.007466087, - -0.007734219, - -0.017511789, - -0.0019751615, - 0.016115652, - -0.026572797, - 0.0039965524, - -0.011372492, - -0.024353774, - 0.0071378564, - -0.029365068, - 0.023003869, - 0.027460406, - -0.042087466, - 0.005626147, - 0.013203185, - -0.004863358, - -0.0013695532, - -0.02699811, - 0.0052424413, - 0.0038278142, - -0.009532552, - 0.01593998, - 0.022301178, - -8.660834E-05, - 0.015727324, - -0.019360973, - -0.0072580534, - -0.0061485423, - -0.014987649, - -0.042494286, - 0.0055891634, - -0.008621828, - 0.009865405, - -0.008977796, - -0.010170521, - -0.0018595873, - -0.010207505, - -0.0077527105, - -0.00094539614, - 0.002038727, - 0.014793485, - -0.012361806, - 0.007831302, - -0.0063935593, - 0.028274048, - 0.0011100892, - 0.006079198, - -0.012093674, - -0.0008309778, - -0.026221452, - -0.0070592663, - -0.031824484, - -0.04282714, - -0.01809428, - -0.0019127514, - -0.007026905, - 0.018011067, - 7.5267635E-05, - -0.0035619938, - 0.0058804103, - -0.015320503, - 0.039794475, - -0.02093278, - -0.008436909, - -0.015394471, - -0.0030858286, - -0.017141951, - 0.021783406, - -0.024316791, - -0.0004230012, - 0.012250855, - -0.008173401, - 0.007734219, - -0.029328084, - -0.026332403, - -0.012703905, - -0.019268515, - 0.0047708987, - -0.01569034, - -0.0014539222, - -0.0315656, - 0.013258661, - -0.004542062, - -0.0017682838, - 0.00438257, - -0.014081549, - -0.028052146, - -0.0015648734, - -0.016356047, - -0.011538918, - 0.011353999, - 0.008950058, - 0.038204174, - 0.008931567, - 0.032064877, - 0.010549604, - -0.015117092, - -0.008686549, - -0.018972645, - -0.020082155, - -0.0054088677, - 0.010179766, - 0.024945514, - -0.00090610096, - -0.0018249151, - -0.015033879, - 0.027682308, - -0.0003591465, - 0.01659644, - -0.02709057, - 0.029106181, - -0.05277576, - 0.014405156, - 0.019360973, - 0.01369322, - -0.01046639, - -0.0049511944, - -0.0025911713, - -0.0028801067, - 0.003284616, - 0.021080716, - -0.019268515, - -0.0022039982, - 0.0018688332, - 0.019786285, - -0.024668137, - -0.013406596, - -0.010179766, - -0.0059728697, - -0.005774082, - -0.017974084, - -0.6083081, - -0.021154683, - 0.011095114, - 0.015033879, - -0.0062132636, - -0.032933995, - 0.008839107, - -0.026221452, - 0.0910539, - 0.016827589, - 0.02688716, - -0.023558624, - -0.012583708, - 0.02182039, - -0.014210992, - 0.037409026, - -0.009366125, - 0.008335204, - 0.01729913, - 0.007355136, - 0.007087004, - 0.0024247447, - -0.0024270562, - -0.021154683, - -0.021487538, - 0.021561505, - 0.00622251, - -0.03735355, - -0.023521641, - 0.008626451, - 0.016624179, - 0.01993422, - 0.02211626, - -0.00705002, - -0.026055025, - 0.0023669575, - 0.018343922, - -0.018538086, - 0.031140286, - 0.014756502, - 0.015431454, - 0.012842594, - -0.07677819, - 0.009948619, - -0.005995984, - -0.011788558, - -0.043603797, - 0.010225996, - -0.017114213, - 0.00452357, - -0.001958981, - 0.026850175, - 0.0019404892, - 0.023540134, - 0.021062225, - 0.0062317555, - 0.016947785, - 0.0029841233, - -0.034061998, - -0.023595609, - -0.02132111, - -0.0134713175, - 0.0064998874, - 0.0058526723, - -0.0033747638, - 0.040682085, - 0.03596666, - 0.0027067454, - -0.010789998, - -0.0141092865, - -0.013369612, - 0.004206897, - 0.016679654, - 0.019508908, - 0.014821223, - 0.03705768, - -0.000522106, - 0.020063665, - -0.017021753, - -0.033359308, - 0.033710655, - 0.0044958326, - 0.029790381, - 0.02261554, - -0.0010742613, - 0.006042214, - 0.009125731, - -0.019508908, - 0.23876685, - 0.0040266016, - -0.0061346735, - 0.2037063, - -0.0011326262, - 0.004900342, - 0.024279807, - 0.011594394, - -0.00053424126, - 0.009661995, - 0.004923457, - 0.0026165976, - -0.015459192, - 0.040682085, - 0.010142783, - 0.015967717, - 0.009458585, - 0.010318456, - 0.008002351, - 0.0017463247, - -0.021783406, - 0.018926416, - -0.009819176, - -0.041421756, - 0.003173665, - -0.018362414, - 0.024427742, - -0.020341042, - 0.020803338, - -0.027737785, - 0.012001215, - -0.016938541, - 0.029642446, - -0.024150364, - -0.0045281933, - -0.007045397, - 0.0014169385, - 0.017474804, - -0.018815463, - 0.0019612925, - 0.015819782, - -0.030641006, - 0.016235849, - -0.014987649, - 0.0046391445, - 0.0081225475, - -0.01021675, - -0.00818727, - 0.020747863, - -0.0058665415, - 0.002690565, - -0.0050806375, - 0.030825924, - 0.024446234, - -0.034043506, - 0.02529686, - 0.0046761283, - 0.013702465, - 0.05188815, - 0.015958471, - 0.015329748, - -0.017012509, - 0.0121953795, - 0.01707723, - 0.013360366, - 0.0062733623, - 0.0015810537, - -0.00047154233, - -0.0030719596, - -0.0054458515, - 0.005136113, - -0.009504814, - 0.014904436, - 0.020045172, - 0.007313529, - 0.0020052106, - 0.0071239877, - -0.0048263744, - -0.00463221, - 0.0025102694, - 0.011529672, - 0.0036845023, - 0.018898677, - 0.012528232, - 0.0057232296, - -0.02102524, - 0.030049266, - 0.002618909, - 0.02390997, - -0.025333842, - -0.014321943, - -0.016171128, - -0.020137632, - -0.008834484, - -0.03187996, - -0.048337713, - -0.0031875337, - 0.046377577, - -0.015829029, - -0.0110119, - 0.0048125056, - 0.045415998, - 0.007826678, - 0.009412355, - -0.013526793, - -0.046932332, - -0.010679047, - 0.01782615, - 0.026424862, - -0.017151197, - 0.0073736277, - 0.02341069, - 0.019397957, - 0.018464118, - -0.009000911, - -0.0003967081, - 0.012925807, - -0.012491249, - 0.007433726, - -0.016725885, - 0.00027549977, - 0.012962791, - -0.006139296, - -0.015856767, - -0.0152372895, - -0.0152372895, - 0.046340592, - 0.009444715, - 0.012306331, - 0.016124899, - -0.031121794, - 0.013378858, - 0.009745209, - 0.017696707, - 0.017770674, - -0.0030488449, - -0.003934142, - -0.008852976, - -0.027312472, - 0.025259875, - -0.017243655, - -0.010697539, - 0.0039549456, - -0.015283519, - -0.004338652, - -0.01001334, - -0.044787277, - 0.012408036, - 0.026757715, - 0.011733083, - 0.01802956, - -0.009486322, - -0.0013267907, - 0.030659497, - -0.0037376664, - 0.0082704825, - 0.019638352, - -0.011002654, - 0.016466998, - -0.016799852, - -0.007567792, - 0.013184694, - 0.0029563855, - -0.016605686, - -0.00672179, - -0.0013267907, - 0.029845856, - 0.0058526723, - -0.017752182, - -0.017493296, - -0.013092234, - 0.023392199, - -0.037224106, - 0.030234184, - -0.031898454, - -0.04375173, - 0.010734523, - -0.04094097, - -0.09734113, - 0.016836835, - -0.015329748, - -0.014377418, - -0.033026457, - 0.010669801, - 0.0014978404, - 0.025074957, - 0.04094097, - 0.0058434266, - 0.009976356, - 0.027275488, - 0.018538086, - 0.0045374394, - -0.006703298, - 0.00071193645, - -0.0072210697, - -0.009463208, - 0.011520427, - -0.015727324, - 0.0036405842, - 0.0012736266, - -0.008589467, - -0.011612886, - -0.00818727, - -0.0009945151, - -0.006828118, - -0.010669801, - 0.0141555155, - -0.0025611222, - 0.0049327025, - 0.009024026, - 0.00010871189, - 0.011446459, - 0.021543013, - 0.0022143999, - 0.0031875337, - 0.013489809, - 0.013240169, - 0.0021300307, - 0.008899205, - 0.0128333485, - -0.028015163, - 0.011520427, - 0.015209552, - 0.012269347, - -0.009065633, - -0.013748695, - 0.0001798622, - 0.01055885, - 0.007452218, - 0.037704896, - -0.0050945063, - 0.007979236, - 0.01239879, - 0.0048171286, - -0.0016076358, - 0.0037538467, - -0.0012135281, - 0.033988032, - 0.001874612, - -0.018066544, - -0.016624179, - 0.0064629037, - 0.0009985602, - -0.025019482, - -0.012001215, - -0.00759553, - -0.005002047, - -0.0071563483, - 0.010826982, - 0.010605079, - 0.014969158, - 0.0006639732, - 0.018787727, - -0.035300955, - -0.0076556285, - 0.018880185, - 0.017178934, - -0.013388104, - 0.0028408114, - -0.012269347, - 0.029790381, - -0.010503374, - -0.0029217133, - -0.015265027, - -0.017243655, - 0.005089883, - -0.006777265, - -0.003423305, - 0.023484657, - -0.017437821, - 0.005288671, - -0.016624179, - -0.016041685, - 0.014275713, - 0.0021323422, - 0.007627891, - 0.008016219, - 0.041791596, - 0.0029402052, - 0.035911184, - -0.031103302, - -0.014848961, - 0.016272834, - -0.010688293, - 0.045674887, - 0.00550595, - -0.007896023, - -0.0155331595, - 0.022800459, - 0.0049743094, - -0.035023578, - -0.016272834, - 0.00772035, - -0.008728156, - -0.022356654, - -0.013110726, - 0.0143034505, - 0.009597274, - 0.0013129218, - -0.01280561, - -0.009426224, - 0.009241305, - 0.0057001146, - 0.005995984, - 0.021062225, - 0.0078035635, - 0.01319394, - 0.0004992801, - 0.0016839147, - 0.0005472434, - 0.0038717324, - 0.008959305, - -0.0006177436, - -0.019360973, - 0.02729398, - 0.014321943, - 0.010521866, - 0.014488369, - 0.026221452, - 0.011908756, - 0.007868284, - 0.020951273, - -0.005233195, - 0.016180374, - 0.041310806, - -0.0015671848, - 0.0062456243, - 0.010484883, - -0.013480563, - 0.009689732, - 0.033655178, - 0.00055273314, - 0.016430015, - -0.02450171, - 0.025574237, - 0.008312089, - -0.011270787, - -0.015357487, - -0.020285565, - -0.033285342, - 0.004965063, - -0.006795757, - 0.013064496, - 0.011169082, - -0.018464118, - -0.023133311, - 0.009181207, - -0.004186094, - 0.0068789707, - -0.0211177, - 0.013582269, - 0.0076325135, - 0.02122865, - -0.0042901104, - 0.012426527, - -0.01080849, - -0.009661995, - -0.0028269426, - 0.0070176595, - -0.015218798, - 0.0072904145, - 0.019656843, - 0.007905268, - 0.00012337536, - 0.022375146, - -0.011640623, - 0.0033262225, - 0.029771889, - 0.015736569, - -0.034283902, - -0.0009922037, - -0.02659129, - -0.02093278, - -0.024779087, - 0.010642063, - 0.02699811, - 0.008113302, - 0.009292157, - -0.025814632, - -0.016531719, - -0.026313912, - 0.0038393717, - -0.009352257, - -0.01414627, - 0.0014539222, - 0.008090187, - 0.008265859, - -0.009985602, - 0.00809481, - -0.0027691554, - 0.011076622, - -0.011520427, - -0.0072996602, - 0.0075354315, - 0.018667528, - -0.04182858, - -0.0015197995, - 0.0121953795, - 0.013536039, - 0.038906865, - -0.005922017, - -0.033729147, - 0.017844642, - 0.03794529, - 0.017863134, - 0.013942859, - -0.016060177, - -0.0047223577, - 0.011381738, - -0.018353168, - -0.014839714, - 0.028958246, - 0.029827364, - -0.010780753, - 0.033655178, - -0.01369322, - -0.010549604, - 0.017724445, - -0.023133311, - -0.010688293, - 0.025629712, - -0.0044287997, - -0.017585754, - 0.009698979, - 0.15015388, - -0.015274273, - 0.0128333485, - -0.009865405, - 0.0024848431, - -0.015884504, - -0.0070777577, - -0.009754454, - -0.009828421, - -0.013360366, - -0.0027853358, - 0.00034874486, - -0.00647215, - 0.01584752, - -0.0015810537, - -0.014848961, - -0.010753014, - -0.009745209, - 0.013989089, - 0.014580829, - -0.014553091, - -0.003975749, - -0.0050621456, - 0.0058572954, - 0.03554135, - 0.008783632, - 0.021043733, - -0.016300572, - 0.017012509, - 0.015459192, - -0.0034256163, - 0.0019705384, - 0.00092632644, - 0.023558624, - -0.011816296, - 0.02163547, - 0.002047973, - 0.008090187, - -0.010004094, - -0.00094192894, - 0.00402429, - 0.015995456, - 0.012463511, - -0.000361458, - -0.0126854135, - -0.0066200844, - 0.0005775816, - -0.013868893, - 0.021746423, - 0.0186213, - 0.03659538, - 0.028255556, - -0.019656843, - 0.011418722, - -0.021968326, - -0.009403109, - -0.028237065, - -0.02790421, - 0.0036267154, - -0.011206065, - -0.0037469123, - -0.014756502, - -0.040977955, - 0.008654188, - -0.0034325507, - -0.013610006, - -0.03415446, - -0.01971232, - 0.000308005, - -0.0021392766, - -0.0026235322, - -0.013369612, - 0.02193134, - 0.027645325, - 0.014469878, - 0.008113302, - -0.001891948, - 0.008127171, - -0.0024478594, - -0.009671241, - -0.011381738, - 0.03816719, - 0.033821605, - 0.026739225, - 0.0029956808, - -0.0071517252, - -0.01314771, - -0.029217133, - -0.0054458515, - 0.018870939, - -0.017317623, - 0.004109815, - -0.0016943163, - -0.004003487, - 0.012491249, - -0.021506028, - 0.014294205, - 0.023484657, - 0.00077319075, - 0.02729398, - -0.0022721868, - -0.013406596, - -0.017141951, - 0.0035643054, - -0.011483443, - 0.019860253, - 0.001200815, - 0.003307731, - -0.007849793, - -0.0292911, - 0.014007581, - 0.013915122, - -0.023891479, - -0.030530054, - 0.011483443, - -0.0044287997, - 0.019582875, - -0.011474197, - 0.010420161, - -0.0020699322, - -0.00023201501, - -0.003030353, - -0.018131265, - -0.0032522553, - 0.0036036004, - 0.02489004, - -0.0034256163, - 0.0012666922, - 0.022504589, - -0.0009003222, - -0.01888943, - 0.0009303715, - 0.0019347104, - 0.013203185, - 0.0051407362, - 0.009227436, - 0.0027067454, - -0.0042161434, - 0.011132098, - -0.008002351, - 0.023725051, - 0.001089286, - 0.0073690047, - -0.010928687, - -0.0015579389, - 0.021690948, - -0.011067376, - 0.00909337, - 0.004292422, - 0.0014781927, - 0.06771718, - 0.025259875, - -0.05610429, - 0.016115652, - 0.00045998493, - 0.019656843, - -0.013878138, - 0.0014007582, - -0.0004885895, - -0.014784239, - 0.0037815846, - -0.023373706, - -0.025463287, - -0.025962567, - -0.011390983, - -0.02032255, - 0.005501327, - 0.0123433145, - 0.015496176, - -0.008885337, - -0.00091996987, - 0.001263225, - -0.024076397, - -0.011797804, - 0.022837443, - -0.006569232, - -0.014460632, - -0.0068512326, - 0.0056954916, - 0.0034787804, - -0.03567079, - -0.022338163, - -0.021469045, - -0.024427742, - 0.023651084, - 0.0050575226, - -0.029919824, - 0.014904436, - -0.014081549, - 0.0027760898, - -0.021099208, - -0.005912771, - -0.0027298604, - -0.018556578, - 0.017807657, - -0.0050575226, - -0.019952713, - 0.0015671848, - -0.011862526, - -0.013129218, - -0.03169504, - -0.010447899, - -0.016679654, - -0.017169688, - 0.006449035, - -0.000691711, - -0.017271394, - -0.048670564, - 0.017151197, - 0.017456312, - -0.003284616, - 0.00022161334, - 0.004368701, - 0.0063658217, - 0.029180149, - -0.015958471, - -0.032249797, - 0.022504589, - -0.0059636235, - -0.0060052304, - -0.005233195, - 0.03149163, - 0.024483217, - -0.012472757, - 0.015625618, - -0.021006748, - 0.0077758254, - -0.00014042253, - -0.032101862, - 0.0075169397, - 0.0060699517, - -0.009213568, - 0.014756502, - -0.010050324, - -0.023392199, - -0.016846081, - 0.0535894, - 0.0061254273, - 0.03289701, - 0.011372492, - 0.0037446008, - -0.015006142, - -0.0062410017, - -0.018454872, - 0.010392423, - 0.031916942, - 0.016208112, - 0.03912877, - -0.031010842, - 0.011280032, - 0.02113619, - -0.008936189, - -0.032046385, - 0.0356523, - -0.01389663, - -0.022097768, - -0.009236682, - -0.004731604, - -0.006569232, - -0.02091429, - -0.011196819, - -0.0083675645, - 0.039387655, - -0.02638788, - 0.0011672984, - 0.0029702545, - -0.01789087, - -0.019471925, - -0.0021230963, - 0.011668362, - -0.010133537, - -0.008191892, - 0.01921304, - 0.0034209935, - 0.03408049, - -0.002093047, - -0.0062548704, - 0.00033227555, - 0.0011239582, - -0.00028171187, - 0.0017255213, - 0.0025726794, - -0.00492808, - 0.029272608, - 0.023743544, - 0.006287231, - -0.0070222826, - 0.017511789, - 0.020488977, - 0.017058738, - 0.051555295, - -0.0072395615, - 0.017049491, - 0.010725277, - 0.030067759, - 0.010595834, - -0.016799852, - -0.008839107, - -0.004040471, - 0.011686853, - -0.03713165, - 0.0148951905, - 0.00864032, - -0.008723533, - -0.0051638507, - -0.03186147, - 0.018806217, - -0.0129812835, - 0.030493071, - -0.0002360601, - -0.023429181, - 0.02061842, - -0.008552483, - 0.010420161, - 0.02629542, - 0.0051407362, - 0.004546685, - 0.011973477, - 0.007896023, - -0.024760595, - 0.030160217, - 0.017114213, - -0.02141357, - 0.00070789136, - -0.008825239, - 0.014664042, - -0.02808913, - -0.031621072, - 0.03445033, - -0.015338995, - -0.014534599, - 0.009920881, - 0.0052054576, - 0.0016700458, - 0.023614101, - 0.013526793, - -0.0042277006, - -0.024557184, - -0.010974917, - 0.012287838, - -0.01319394, - 0.004733915, - 0.025648205, - 0.011326262, - -0.010336948, - 0.0010690604, - -0.011326262, - 0.016420769, - -0.034006525, - -0.03208337, - 0.007350513, - -0.031010842, - 0.0070777577, - -0.0135175465, - -0.042383336, - 0.016753621, - 0.027275488, - -0.009010157, - 0.034283902, - -0.00083791226, - -0.0018260708, - -0.009994849, - 0.007207201, - 0.024871547, - -0.008043958, - -0.011141343, - -0.004840243, - 0.012713151, - -0.0030118611, - -0.012260101, - -0.005954378, - -0.018288447, - -0.018020313, - 0.006388936, - -0.009994849, - -0.01235256, - -0.00818727, - 0.0020237025, - -0.0035804857, - -0.025685187, - 0.007859039, - -0.001414627, - 0.028144605, - -0.0252044, - 0.019804778, - 0.0074059884, - -0.0023172607, - -0.00074083, - -0.044713307, - 0.009772946, - -0.0044149305, - -0.012065936, - -0.017012509, - -0.015662603, - -0.004900342, - 0.05211005, - 0.012324822, - -0.010799244, - -0.017539525, - 0.035116035, - -0.008538615, - 0.0031852222, - -0.009056387, - -0.0060838205, - -0.008242745, - 0.017465558, - 0.013082989, - 0.019065104, - -0.005542934, - -0.002896287, - -0.02011914, - -0.00023331522, - -0.036225546, - 0.013526793, - 0.019601367, - -0.00018853025, - 0.030104741, - 0.0292911, - -0.0044426685, - -0.008543237, - 0.0020202354, - 0.010799244, - 0.020174615, - 0.0030534677, - -0.03408049, - -0.0045767343, - -0.01753028, - 0.007442972, - 0.021450553, - 0.028921263, - -0.024390759, - 0.007484579, - 0.0054550976, - -0.006555363, - -0.00012590353, - -0.0065414943, - 0.007211824, - 0.00829822, - 0.012546725, - 0.0046252757, - -0.0063611986, - 0.008136417, - -0.017742936, - 0.014414402, - -0.0029170904, - -0.0013683974, - 0.03824116, - 0.0013244792, - -0.0026235322, - 0.009232059, - 0.01912058, - 0.010189013, - -0.025518762, - -0.0009159247, - -0.0053071626, - 0.029457526, - 0.011372492, - -0.0053210314, - -0.022874426, - -0.008779009, - -0.004285488, - 0.029697921, - 0.025241384, - 0.022338163, - -0.02152452, - 0.0077619567, - 0.010669801, - 0.018898677, - 0.009532552, - -0.011187573, - -0.0047015543, - -0.019490417, - -0.0033655178, - 0.00060791976, - -0.045489967, - -0.0015544717, - 0.017428575, - 0.017742936, - 0.011844034, - -0.0034926494, - 0.025019482, - 0.029975299, - 0.019545892, - -0.02640637, - -0.009282912, - -0.001642308, - -0.013942859, - -0.009920881, - 0.026831683, - -0.0005507106, - 0.039202735, - 0.011714591, - 0.018149758, - 0.008617205, - 0.0051176213, - 0.0367803, - -0.0055799177, - 0.0067911344, - 0.0074291034, - -0.005649262, - -0.0018110462, - 0.010420161, - 0.006014476, - -0.016023193, - 0.017770674, - -0.007687989, - 0.006573855, - -0.028625393, - -0.017012509, - -0.031121794, - 0.023743544, - 0.008737402, - 0.02061842, - -0.0022883671, - -0.029642446, - -0.0038486177, - -0.035282463, - -0.012879577, - 0.026554305, - 0.016753621, - 0.0038070108, - 0.02660978, - -0.0030118611, - -0.011400229, - 0.013064496, - -0.015431454, - 0.01380417, - -0.010503374, - 0.0083675645, - 0.010207505, - 0.0014296516, - 0.025574237, - 0.00039064046, - 0.008552483, - 0.011788558, - -0.0014781927, - -0.0072395615, - 0.027256995, - -0.013933614 - ], - "DEFAULT_VECTORIZE_DESCRIPTION": [ - -0.030846236, - -0.016767653, - 0.04531517, - 0.0015787444, - -0.005634036, - -0.0054431986, - -0.012959584, - 0.031661633, - 0.018511211, - 0.009455117, - -0.02827861, - 0.016698258, - 0.014815909, - -0.021304375, - -0.02569363, - 0.021113537, - -0.0116497455, - 0.008483583, - -0.0043762447, - 0.017687142, - -0.016099723, - -0.009507164, - -0.019326607, - 0.0021675206, - 0.029406283, - -0.0032789307, - -0.029944098, - -0.012786095, - -0.002337756, - 0.029701214, - 0.016255863, - -0.015535886, - 0.019413352, - 0.004996466, - -0.009810769, - 0.018875537, - -0.0104787, - -0.0044000996, - -0.017886654, - 0.009368373, - 0.047778703, - 0.005165617, - -0.030186981, - 0.005846559, - 0.00036622316, - -0.006796408, - 0.009298978, - 0.021946283, - 0.0061675124, - 0.02645698, - -0.022570841, - -0.004983454, - -0.007824327, - -0.03004819, - -0.014243398, - 0.012317676, - 0.022223864, - -0.01988177, - 0.004992129, - -0.011632397, - 0.013774979, - 0.029579772, - 0.011606374, - -0.005551629, - -0.0160737, - -0.011641071, - 0.013575467, - 0.032511726, - -0.016316583, - 0.0035803667, - 0.010869049, - -0.0036042214, - -0.008574664, - 0.004462989, - 0.004014088, - 0.001168878, - -0.015535886, - -0.024999678, - 0.01032256, - 0.037924565, - -0.0009297894, - -0.009567885, - -0.00093304226, - 0.02033284, - 0.01181456, - -0.026630469, - -0.03542633, - -0.0032876052, - 0.0016676572, - 0.025242561, - 0.007642164, - 0.0145730255, - 0.008661408, - -0.0075684316, - 0.0066836406, - -0.022518793, - -0.008444548, - -0.033691447, - 0.020384887, - -0.00086798414, - 0.035339586, - -0.0043784133, - -0.0015136863, - 0.008353466, - -0.003376518, - -0.020176701, - 0.023854654, - -0.015535886, - -0.012968258, - -0.0070132683, - -0.018372422, - -0.008600688, - -0.021616654, - 0.023351539, - -0.017661119, - -0.015787445, - -0.009984258, - -0.01322849, - -0.009750048, - 0.01733149, - 0.0291634, - -0.021651352, - 0.022917816, - -0.014260747, - -0.013063677, - 0.0075510824, - -0.016516095, - -0.01579612, - -0.02094005, - -0.036120284, - 0.01622984, - 0.0027541283, - -0.021009445, - 0.0015689858, - 0.013358607, - 3.7916703E-05, - -0.013774979, - 0.021616654, - 0.0009877996, - -0.0079978155, - 0.008327443, - 0.0144429095, - 0.010522071, - -0.005287059, - 0.012256956, - -0.009645955, - 0.025433399, - 0.003025204, - -0.020246096, - 0.02885112, - -0.0061414894, - 0.004541059, - 0.007473013, - -0.009064768, - -0.016464049, - -0.013861723, - -0.01705391, - -0.0149893975, - 0.027671399, - 0.024635352, - -0.007620478, - -0.020749213, - 0.001616695, - 0.017652445, - 0.0009406324, - 0.0023854654, - -0.012820792, - 0.012777421, - -0.0064754547, - -0.005495245, - 3.4680736E-05, - 0.021963632, - -0.005126582, - 0.043302704, - 0.014234723, - 0.02168605, - -0.001416099, - -0.021859538, - -0.021113537, - 0.017695816, - 0.03440275, - 0.002219567, - 0.017418236, - -0.03202596, - 0.027289726, - 0.0032572446, - -0.009316327, - 0.02376791, - 0.0143388165, - 0.004226611, - 0.0032594132, - -0.0023963086, - 0.0045974427, - -0.002695576, - 0.009602583, - 0.011094583, - -0.032858703, - -0.0016264537, - 0.033552658, - -0.011042536, - -0.0049053845, - -0.007954443, - 0.0109731415, - 0.0056817452, - 0.00096502923, - -0.013774979, - -0.00957656, - 0.0017327154, - -0.022171818, - -0.0057077683, - -0.0056687333, - 0.013020304, - 0.006978571, - 0.014564351, - -0.026543725, - -0.021616654, - -0.01428677, - -0.011059885, - -0.015336375, - -0.002261855, - 0.00478828, - -0.005143931, - 0.020749213, - -0.012066118, - -0.024947632, - 0.0031553202, - -0.015180235, - -0.017652445, - -0.007503373, - -0.0031314655, - -0.019239863, - -0.0157007, - 0.001172131, - -0.03544368, - 0.015865514, - 0.019847073, - -0.007256152, - -0.0058508962, - -0.0045584077, - 0.012942234, - -0.008873931, - 0.011458908, - -0.0068224315, - -0.018025445, - 0.006874478, - -0.03095033, - 0.020853305, - 0.03754289, - 0.018268328, - -0.016177794, - -0.0448641, - 0.018823491, - -0.0039381864, - -0.028937865, - 0.03127996, - 0.054232474, - -0.015726723, - 0.014312793, - 0.0017793403, - -0.0022857096, - -0.027480561, - -0.011129281, - 1.1884972E-05, - 0.009888839, - -0.0010170757, - -0.012690676, - 9.3792165E-05, - -0.0087785125, - -0.01428677, - -0.012074793, - -0.006137152, - -0.001885602, - 0.009489816, - -0.013297886, - 0.011120606, - -0.0043870877, - -0.0072995243, - -0.002266192, - -0.002509076, - -0.000304689, - -0.0047839424, - -0.021876886, - 0.010764955, - 0.0070956754, - 0.023039259, - 0.014685793, - -0.0032810993, - -0.007707222, - -0.0072995243, - 0.041776005, - -0.007707222, - 0.004083483, - -0.0035543435, - 0.0021122212, - 0.00601571, - -0.0022380003, - 0.028209213, - -0.00971535, - 0.032095354, - -0.03782047, - 0.029336888, - 0.010452676, - 0.017886654, - 0.0007606382, - -0.027289726, - 0.018198933, - -0.0018986136, - 0.009307653, - 0.022223864, - -0.012421769, - 0.00052968174, - -0.011129281, - -0.0056860824, - -0.009515839, - -0.017782561, - -0.015076142, - -0.02168605, - 0.010183769, - -0.023056608, - -0.01046135, - 0.03636317, - -0.00013919733, - -0.015683351, - 0.00043426314, - -0.009923536, - -0.020558376, - 0.015388421, - 0.000609378, - -0.008262385, - 0.0035131401, - 0.025763027, - 0.016203817, - 0.00609378, - 0.023230096, - 0.0020645119, - 0.037404098, - -0.0011200844, - 0.04021461, - -0.025086422, - -0.013297886, - 0.007126036, - -0.018719397, - -0.01899698, - 0.004497687, - -0.015848165, - -0.010712909, - -0.01638598, - -0.010374607, - 0.008765501, - -0.011528304, - 0.01927456, - 0.0011190001, - -0.0021772794, - 0.03466298, - -0.006115466, - -0.012413095, - 0.015240956, - 0.0024938958, - -0.024618004, - 0.005412838, - -0.016203817, - 0.0060851057, - 0.015952257, - -0.005104896, - -0.0040639658, - 0.02931954, - -0.029822655, - -0.004953094, - 0.026960097, - 0.013375956, - -0.017435584, - -0.0059810127, - 0.0069178496, - -0.012898862, - 0.0186847, - 0.007841676, - 0.02557219, - -0.022761678, - -0.02107884, - -0.015969606, - 0.0067486987, - -0.004269983, - -0.009038745, - -0.028035725, - 0.0209227, - -0.016039003, - 0.007021943, - 0.009272954, - -0.019378655, - 0.0113895135, - 0.009056094, - -0.0020796922, - -0.021408468, - 0.007143385, - -0.008952001, - -0.008062873, - -0.00075684313, - 0.0039598728, - 0.04021461, - -0.01807749, - -0.00013065845, - -0.016550792, - 0.00038167447, - -0.020280793, - 0.0014920002, - -0.041359633, - -0.037577588, - -0.021217631, - 0.011398188, - -0.01615177, - 0.0042027566, - -0.0019289742, - 0.0020016225, - 0.012916211, - -0.005417175, - 0.017435584, - 0.0012491165, - -0.012551886, - 0.014694467, - 0.004497687, - -0.008908629, - -0.0014952532, - 0.0012133345, - 0.0014507967, - 0.017374864, - 0.00018988847, - 0.006648943, - 0.0017988578, - -0.048160378, - -0.005994024, - -0.015258305, - -0.013870398, - 0.0026391922, - 0.0038405994, - -0.024114888, - 0.010721583, - 0.0050875475, - -0.018858189, - 0.010201118, - 0.010062327, - -0.0058378847, - 0.0040162564, - -0.0027085876, - 0.01083435, - 0.015310351, - 0.024271026, - 0.020228747, - 0.008917304, - 0.0042417916, - 0.017617747, - -0.016403329, - 0.002165352, - -0.021113537, - -0.015657328, - 8.288137E-05, - -0.0082060015, - 0.028174516, - 0.006527501, - 0.011536978, - -0.037646983, - 0.020749213, - 0.018650003, - 0.021564608, - -0.018927583, - 0.029336888, - -0.041463725, - 0.0014280264, - 0.013280537, - -0.01232635, - -0.024791492, - -0.028885819, - -0.02645698, - 0.026300842, - -0.015293002, - 0.0012317676, - 0.005226338, - -0.011667095, - 0.0011905641, - 0.031002376, - -0.0239414, - -0.009689327, - 0.010634839, - -0.010279188, - 0.015822142, - 2.5074494E-05, - -0.6445441, - -0.006197873, - 0.017383538, - 0.0064320825, - -0.0056860824, - -0.01024449, - 0.004688524, - -0.012508513, - 0.08611964, - -0.0020428258, - 0.025173167, - -0.015275653, - 0.0021848695, - 0.0016405496, - -0.003244233, - 0.023577074, - -0.0063323267, - -0.00886092, - 0.021946283, - 0.00071889255, - -0.009177536, - -0.03301484, - 0.020731863, - -0.016967166, - -0.027723446, - 0.003430733, - -0.0040596286, - -0.018667351, - -0.014937351, - 0.0044326284, - -0.0028256923, - 0.013644863, - 0.023715865, - -0.02735912, - -0.013315234, - -0.0020775236, - 0.02586712, - -0.01944805, - 0.019534793, - 0.027012143, - 0.014321467, - 0.025311958, - -0.063600846, - -0.0012827298, - -0.00011676583, - 0.011111932, - -0.0109731415, - 0.004753582, - 0.009004048, - -0.008015164, - -0.015102165, - -0.0053607915, - -0.013670886, - 0.012369723, - 0.008522618, - 0.012716699, - 0.005516931, - 0.00023475148, - -0.010591467, - -0.013506072, - 0.0075901174, - 0.00046082857, - -0.0036692796, - 0.01099049, - -0.00039387288, - 0.008088897, - 0.021755446, - 0.014226048, - -0.025745679, - -0.008583339, - -0.015830817, - 0.024583306, - 0.022362655, - 0.020749213, - 0.012786095, - 0.012439118, - 0.013237164, - 0.015553235, - -0.018181585, - -0.017010538, - 0.006488466, - 0.005165617, - 0.009429094, - 0.012777421, - -0.03664075, - 0.005352117, - 0.026630469, - -0.013419327, - 0.25676283, - -0.00792842, - -0.02154726, - 0.17917882, - -0.030030841, - -0.01106856, - 0.029614469, - 0.013610165, - -0.042816937, - -0.000580644, - -0.008652734, - -0.005287059, - -0.006197873, - 0.028521493, - 0.01703656, - -0.0010100277, - 0.0033548318, - 0.03154019, - 0.009914862, - -0.0035283202, - -0.0038839716, - 0.029128702, - -0.011190002, - -0.013939792, - -0.0027758144, - -0.025710981, - 0.008678757, - -0.021356422, - 0.0034741051, - -0.022674933, - -0.017452933, - -0.0076725245, - 0.00083491293, - -0.015518537, - 0.014668444, - -0.020072607, - -0.013150421, - 0.0010723751, - 0.008110583, - 0.024843538, - -0.006631594, - -0.02557219, - -0.010044978, - 0.0011764682, - -0.009776072, - 0.0032117038, - -0.00957656, - -0.013870398, - 0.010383281, - -0.0049877916, - 0.0075727687, - -0.009316327, - 0.031470794, - -0.003172669, - -0.008592013, - 0.019309258, - 0.0045757564, - 0.0019484916, - 0.046425495, - 0.016941141, - -0.013254514, - -0.04562745, - 0.020558376, - 0.008756827, - -0.0073775942, - 0.004428291, - -0.0055082566, - -0.0005638373, - -0.0010376775, - -0.0073428964, - 0.005577652, - 0.008509606, - -0.0044499775, - 0.021321723, - 0.0033548318, - 0.0059333034, - -0.0021935438, - -0.0024548608, - -0.0033136285, - -0.003940355, - 0.017834608, - -0.008483583, - 0.009602583, - 0.010417978, - 0.018112188, - 0.0021848695, - 0.014850607, - 0.012317676, - 0.008479245, - -0.023455631, - -0.005065861, - -0.009663303, - 0.006241245, - -0.009906188, - -0.015371072, - -0.018441817, - -0.013046327, - 0.052809868, - 0.00673135, - -0.010227141, - 0.0027432854, - 0.008865257, - -0.0018823491, - -0.005065861, - 0.01479856, - -0.028955214, - 0.0033570004, - -0.0027975005, - 0.01203142, - 0.016047677, - 0.005881257, - 0.00077364984, - 0.002480884, - 0.005521268, - -0.028920516, - -0.00258064, - 0.019899119, - -0.009177536, - 0.012170211, - -0.010114374, - -0.0024613666, - 0.030828888, - -0.007394943, - -0.013480049, - -0.029683866, - 0.020454282, - 0.098333225, - -0.0028126806, - 0.010140397, - 0.013879072, - -0.009481141, - 0.022622887, - 0.012083467, - 0.02317805, - 0.01091242, - 0.0009975582, - -0.006549187, - -0.00934235, - -0.031175865, - 0.010548094, - -0.02047163, - -0.0049270703, - -0.00012259395, - -0.020662468, - 0.011996723, - 0.020610422, - -0.008075885, - -0.021963632, - 0.011693118, - 0.017661119, - 0.0073515708, - -0.0073906058, - 0.011615048, - 0.018667351, - -0.0002638921, - -0.00031173698, - 0.012803444, - 0.002530762, - 0.03127996, - 0.0027758144, - -0.015084816, - 0.012959584, - 0.004319861, - -0.01232635, - 0.0027519597, - 0.00590728, - -0.0030056864, - 0.011476258, - 0.0047275587, - -0.011909978, - -0.01189263, - -0.002365948, - -0.027584655, - 0.045072287, - -0.027255027, - 0.014920002, - 0.02633554, - -0.009194885, - -0.091532476, - 0.016047677, - -0.0082060015, - -0.0065621985, - -0.036120284, - 0.0153276995, - 0.00028218972, - -0.0012306833, - 0.0077983034, - 0.0047969543, - 0.0060807685, - 0.01173649, - 0.030776842, - -0.0009531019, - -0.004541059, - -0.010721583, - -0.009307653, - -0.023438282, - 0.01721005, - -0.008071547, - -0.0052783843, - 0.0077158967, - -0.00609378, - 0.0060460707, - -0.01823363, - -0.0029796632, - -0.026300842, - -0.0024223318, - 0.0075901174, - -0.005477896, - 0.0021458347, - 0.0049661053, - -0.027289726, - 0.011051211, - 0.02781019, - -0.0064971405, - -0.00051883876, - 0.011632397, - 0.017027887, - -0.010721583, - 0.037404098, - 0.028469445, - -0.028642934, - 0.007767943, - 0.020280793, - -0.010808327, - 0.011632397, - -0.011163979, - -0.0072821756, - 0.031626936, - 0.008934652, - 0.018424468, - 0.001921384, - -0.016498746, - 0.0018693375, - 0.0048316517, - -0.0023746225, - 0.018441817, - -0.0071737454, - 0.012083467, - 0.006449431, - -0.015561909, - -0.0027866573, - 0.00087448995, - -0.0050441753, - -0.0130897, - -0.011320118, - -0.0151195135, - -0.026890703, - -0.0039815586, - -0.0012035758, - 0.017539676, - 0.01913577, - -0.016984515, - 0.038930796, - -0.0033613378, - 0.013245839, - 0.007433978, - -0.0024331748, - -1.3384359E-05, - -0.021807492, - -0.006115466, - 0.01218756, - 1.39858075E-05, - -0.0020601747, - -0.006865803, - -0.02871233, - 0.010999165, - -0.01256056, - 0.013028978, - 0.009828118, - -0.03348326, - 0.0117017925, - -0.003656268, - -0.006033059, - 0.009698002, - -0.02753261, - 0.014642421, - -0.00460178, - -0.00076443324, - 0.018962283, - 0.043753773, - -0.008219013, - -0.013349933, - 0.011172653, - -0.016160443, - 0.05475294, - -0.01913577, - -0.03379554, - -0.006345338, - 0.016264537, - 0.020228747, - -0.0114936065, - 0.0080238385, - -0.010600141, - 0.00646678, - -0.019708281, - 0.022987213, - -0.01293356, - 0.014147979, - -0.012118164, - -0.02947568, - -0.031731028, - 0.009914862, - 0.03079419, - 0.00033098334, - 0.024236329, - 0.019951167, - 0.0036540993, - 0.010140397, - -0.018719397, - 0.0025871457, - 0.0065014777, - 0.0067833965, - -0.0026543725, - -0.020523677, - 0.017730514, - 0.007876373, - -0.00023136304, - -0.018771445, - 0.022536144, - 0.023872003, - -0.013245839, - 0.019847073, - 0.005621024, - 0.004137698, - 0.037577588, - 0.0016080206, - -0.005599338, - 0.010738932, - -0.0119360015, - 0.0049877916, - 0.016949816, - -0.014226048, - 0.021634003, - -0.007911071, - 0.002305227, - 0.0019311428, - -0.0020471632, - -0.029944098, - -0.018008096, - -0.040735077, - 0.01195335, - -0.02213712, - 0.028348004, - -0.024305724, - -0.013254514, - -0.028330656, - 0.044655915, - 0.0020677648, - 0.019517444, - -0.030239027, - -0.0039772214, - 0.0012285147, - 0.004280826, - -0.017617747, - 0.010886397, - 0.013688235, - -0.014260747, - 0.0037191575, - 0.02184219, - 0.010001606, - -0.009671978, - 0.013827025, - 0.018303026, - -0.007828664, - 0.012534536, - -0.0067660473, - -0.006054745, - 0.0070523033, - -0.0049314075, - -0.027948981, - 0.02437512, - -0.009645955, - -0.01758305, - -0.02378526, - 0.009741373, - 0.02378526, - 0.028313307, - 0.02123498, - -0.019361306, - 0.0024310062, - 0.009802095, - 0.00848792, - 0.0070349546, - -0.033413865, - -0.0023616108, - -0.009810769, - -0.0019701775, - 0.0016654886, - 0.008054199, - 0.008084559, - -0.033136282, - 0.005989687, - 0.0032117038, - 0.011328792, - -0.0017890991, - -0.025589539, - -0.0056817452, - -0.014026537, - 0.005660059, - 0.0148072345, - -0.0006283533, - -0.02258819, - 0.023212748, - 0.021772794, - 0.01165842, - -0.02347298, - -0.017201375, - 0.0037126518, - 0.025242561, - -0.009064768, - -0.0030208668, - 0.011103258, - 0.042122982, - -0.001168878, - 0.034715027, - -0.011719141, - 0.01181456, - 0.0051135705, - -0.02616205, - 0.007208443, - 0.024392469, - 0.020055259, - -0.009038745, - 4.8725844E-05, - 0.1388601, - -0.010556769, - 0.02569363, - 0.00058877625, - 0.02453126, - -0.018736746, - -0.0061848615, - -0.00840985, - 0.001555974, - -0.009984258, - -0.013549444, - 0.006727013, - -0.012898862, - 0.006800745, - 0.0045757564, - 0.020697165, - -0.004172396, - -0.033066887, - 0.009628606, - 0.028226562, - -0.002476547, - 0.018771445, - -0.018424468, - -0.010903746, - 0.027862236, - 0.016195143, - -0.0032268842, - -0.016108397, - -0.0150154205, - 0.00934235, - -0.014520979, - 0.012751398, - 0.0072821756, - -0.018216282, - -0.01666356, - 0.027168283, - 0.025207864, - -0.0021599305, - -0.019829724, - -0.018493863, - -0.013783653, - 0.00443046, - 0.0057945126, - -0.012178886, - 0.0044174483, - -0.020089956, - -0.0039989077, - -0.0028668959, - 0.010157745, - 0.01615177, - 0.027844887, - 0.044482425, - -0.015692025, - 0.026578423, - 0.0021382445, - 0.0038579484, - -0.0071390476, - -0.02704684, - 0.025103772, - 0.010522071, - -0.00011974765, - 0.0038861402, - -0.027168283, - -0.00050908, - -0.00612414, - 0.004731896, - -0.02333419, - -0.0071173613, - -0.007269164, - 0.00077093905, - -0.005274047, - -0.035218146, - 0.024930283, - 0.035773307, - 0.009108141, - 0.0076334896, - 0.014217374, - 0.00851828, - 0.013159095, - -0.009602583, - -0.012430443, - 0.0113895135, - 0.02449656, - -0.0114155365, - 0.018008096, - 0.013107048, - 0.011875281, - -0.011398188, - -0.012317676, - 0.0038492738, - -0.01465977, - 0.00822335, - -0.010782304, - -0.02796633, - 0.033448562, - -0.020298142, - 0.011458908, - 0.015692025, - 0.0064147334, - 0.045835633, - -0.0065231635, - -0.0012989944, - 0.0114936065, - -0.0064190705, - -0.017886654, - 0.048923727, - -0.014625072, - 0.018285677, - -0.04996466, - -0.014616397, - -0.009116815, - -0.004014088, - -0.01613442, - -0.0149547, - 0.025763027, - -0.01083435, - 0.025919167, - 0.0011916484, - 0.015986957, - 0.0057337917, - -0.01442556, - 0.012812118, - -0.034350704, - -0.018459165, - -0.018927583, - 0.029146051, - -0.0038796342, - -0.005412838, - 0.012352373, - -0.008179978, - -0.0035066342, - 0.0001385874, - -0.009663303, - 0.010712909, - -0.008106246, - -0.0030512272, - 0.0008864173, - -0.0061067916, - 0.010643513, - -0.010496048, - 0.022640236, - 0.0068094195, - 0.019014329, - 0.0025047387, - -0.009802095, - 0.005226338, - -0.007941431, - 0.004849001, - 0.018268328, - -0.0038557795, - 0.0627681, - 0.0044456404, - -0.030880935, - 0.009680653, - -0.010201118, - 0.0025502795, - 0.002509076, - 0.010018955, - 0.011406862, - -0.012725374, - 0.013592816, - -0.010704234, - -0.011172653, - -0.008952001, - -0.0051873033, - -0.013896421, - 0.01792135, - -0.017218724, - 0.00034616358, - 0.020246096, - 0.019465398, - 0.011762514, - 0.006132815, - -0.017357513, - 0.027602004, - -0.021217631, - -0.013592816, - -0.018459165, - 0.0053607915, - -0.0017619915, - -0.008552978, - -0.0111813275, - 0.011710467, - -0.039798237, - 0.026387585, - 0.0033960354, - -0.011120606, - 0.013401979, - -0.019899119, - 0.010348583, - 0.012612606, - -0.015969606, - -0.018615305, - -0.0062455824, - 0.016984515, - -0.007126036, - -0.041949496, - -0.01046135, - -0.0032789307, - 0.0064928033, - 0.010712909, - -0.013532095, - 0.0003705604, - 0.0021512562, - 0.019031677, - 0.009767396, - -0.01960419, - -0.024271026, - 0.003860117, - 0.027567307, - 0.007008931, - -0.013688235, - -0.014711816, - 0.0038839716, - 0.019066375, - -0.013037653, - -0.02258819, - 0.012950909, - -0.022154469, - 0.011406862, - 0.004541059, - 0.021304375, - 0.009298978, - 8.227145E-05, - 0.017973399, - -0.031661633, - 0.002244506, - 0.027671399, - -0.015553235, - -0.0052133263, - -0.001709945, - -0.018268328, - 0.0019495758, - 0.008305757, - 0.00095093326, - -0.010496048, - 0.01629056, - 0.0073906058, - 0.032667864, - -0.004961768, - 0.026786609, - 0.0025893142, - -0.004506361, - -0.019239863, - 0.04115145, - 0.043302704, - 0.008097571, - 0.014390863, - -0.0027584655, - -0.0034047097, - -0.005417175, - -0.00590728, - -0.021200282, - 0.03395168, - -0.02047163, - -0.017661119, - -0.025346655, - 0.017383538, - 0.018910235, - -0.008878268, - 0.010010281, - -0.02213712, - 0.03618968, - -0.030186981, - 0.013644863, - 0.018042793, - 0.012066118, - 0.018823491, - 0.012118164, - 0.0052610356, - 0.0004182697, - -0.0042201052, - 0.0115716765, - -0.021130886, - 0.034923214, - -0.012300327, - -0.027098889, - 0.01807749, - 0.0055256053, - 0.01189263, - -0.008769838, - 0.012768746, - 0.00031715847, - 0.0065578613, - -0.004645152, - 0.005725117, - -0.0009877996, - 0.013098374, - -0.005373803, - 0.0068094195, - 0.014902653, - -0.0041637216, - 0.024010794, - 0.01988177, - 0.026387585, - 0.00407264, - -0.015431793, - 0.0037300005, - 0.026439631, - -0.0028625585, - -0.03495791, - 0.0062716054, - 0.002986169, - 0.0021414973, - -0.0014334479, - 0.0017489799, - -0.004419617, - -0.0031054423, - 0.01024449, - -0.0048620123, - -0.0025719656, - -0.0011054464, - -0.007004594, - -0.0016156107, - 0.027272375, - 0.012751398, - 0.014477607, - 0.0017131979, - -0.012664653, - -0.02199833, - 0.005230675, - 0.030932982, - -0.014685793, - 0.0045931055, - -0.0035608495, - -0.0051916405, - -0.021894235, - 2.5989375E-05, - 0.0020796922, - -0.008561652, - -0.032980144, - -0.009108141, - 0.0065968963, - 0.011693118, - 0.01629056, - -0.017409561, - 0.0038080704, - -0.017383538, - -0.03920838, - -0.0055299425, - 0.0037365064, - -0.015284328, - 0.032234143, - 0.033587355, - -0.03181777, - 0.0006657617, - -0.0032160413, - 0.015587932, - -0.007008931, - -0.025745679, - -0.023646468, - -0.027445864, - 0.01479856, - 0.023681166, - -0.004835989, - -0.0006657617, - 0.021200282, - 0.016984515, - 0.019847073, - -0.015440468, - -0.027549958, - 0.009030071, - 0.012577909, - 0.0054865708, - -0.0032529074, - -0.016585492, - -0.009142838, - 0.0023095643, - -0.004237454, - -0.003925175, - 0.009307653, - -0.019170469, - -0.018771445, - -0.019326607, - -0.001336945, - -0.028001027, - -0.0028191865, - -0.0009872575, - -0.0059376406, - -0.031921864, - 0.0077332454, - 0.009194885, - 0.014330141, - -0.027931632, - -0.0028343666, - 0.013835699, - -0.016654886, - 0.024565957, - -0.039728843, - 0.01899698, - 0.011276746, - 0.019482747, - -0.007021943, - -0.0012350206, - 0.0057728263, - 0.03273726, - -0.010140397, - -0.00425914, - -0.013454026, - 0.009628606, - 0.0013965816, - 0.010790979, - -0.008852245, - -0.006471117, - -0.012829467, - 0.023247445, - 0.0029666517, - 0.00811492, - -0.005699094, - 0.0040054135, - -0.020367539, - -0.03006554, - -0.010383281, - 0.028174516, - 0.029718563, - 0.006657617, - 0.008435873, - 0.010799653, - -0.00904742, - -0.003096768, - -0.009429094, - 0.023351539, - 0.019951167, - 0.01165842, - 0.0020916194, - -0.003057733, - -0.013358607, - -0.014104607, - 0.017904002, - -0.0021686049, - -0.025988562, - -0.00508321, - -0.0011916484, - -0.012413095, - 0.014642421, - 0.008539966, - 0.020835957, - 0.018320374, - 0.009272954, - 0.0020710176, - -0.054371264, - 0.0048446637, - 0.0075684316, - 0.0060807685, - 0.011450234, - -0.0057164426, - 0.03473238, - -0.0010989406, - 0.0006278111, - 0.0034394076, - 0.009099467, - 0.00304689, - -0.028226562, - 0.0054258495, - -0.012595258, - 0.009142838, - 0.011693118, - 0.021772794, - -0.01825098, - -0.022518793, - 0.01852856, - 0.010652187, - -0.0068874895, - 0.026040608, - -0.0070696524, - -0.0042070937, - -0.00489671, - 0.033934332, - 0.014200025, - 0.01635128, - -0.031002376, - -0.022622887, - -0.0056774076, - 0.014182677, - -0.041047353, - 0.012387072, - 0.03336182, - 0.02631819, - 0.009220908, - 0.001451881, - 0.015379746, - 0.025988562, - 0.003096768, - -0.013367281, - 0.0026630468, - -0.0074556638, - -0.004571419, - -0.021477863, - 0.016481398, - 0.02812247, - 0.028330656, - -0.006978571, - 0.013375956, - -0.010131722, - -0.0075337337, - -0.017314142, - -0.016455375, - 0.0005326636, - 0.003025204, - -0.0070132683, - -0.009854141, - 0.038826704, - 0.0017435584, - -0.008418525, - -0.009151513, - 0.019569492, - 0.00676171, - -0.04292103, - -0.015613955, - -0.013193793, - 0.034125168, - 0.00800649, - 0.012603932, - -0.0059593264, - -0.050866798, - 0.00059745065, - -0.012074793, - -0.002437512, - 0.02513847, - 0.030256376, - -0.0014464596, - 0.016143095, - -0.0031358027, - 0.0006337748, - 0.026196748, - -0.01232635, - 0.006696652, - 0.00065546087, - 0.0018671689, - -0.004467326, - 0.018615305, - -0.0063496754, - 0.007624815, - 0.0261794, - 0.016091049, - -0.02064512, - -0.002111137, - 0.009030071, - -0.0045367214 - ] -} diff --git a/sdk/search/azure-search-documents/swagger/README.md b/sdk/search/azure-search-documents/swagger/README.md deleted file mode 100644 index fbe07e9b94c9..000000000000 --- a/sdk/search/azure-search-documents/swagger/README.md +++ /dev/null @@ -1,487 +0,0 @@ -# Azure Search Documents for Java - -> see https://aka.ms/autorest - -This is the AutoRest configuration file for SearchServiceClient and SearchIndexClient. ---- -## Getting Started - -To build the SDK for SearchServiceClient and SearchIndexClient, simply [Install AutoRest](https://aka.ms/autorest) and -in this folder, run: - -> `autorest` - -To see additional help and options, run: - -> `autorest --help` - -### Setup -```ps -npm install -g autorest -``` - -### Generation - -There are two swaggers for Azure Search, `searchindex` and `searchservice`. They always under same package version, e.g. -`--tag=searchindex` and `--tag=searchservice`. - -```ps -cd -autorest -``` - -e.g. -```ps -cd -autorest --tag=searchindex -autorest --tag=searchservice -``` - -## Manual Changes - -This section outlines all the checks that should be done to a newly generated Swagger as Azure Search Documents for Java -contains manual translations of generated code to public API. - -### SearchPagedFlux, SearchPagedIterable, and SearchPagedResponse - -New properties added to `SearchPagedResponse` need to be exposed as getter properties on `SearchPagedFlux` and -`SearchPagedIterable`. Only the first `SearchPagedResponse` properties are exposed on `SearchPagedFlux` and -`SearchPagedIterable`. - -### Converters - -There are a set of `*Converter` classes in the package `com.azure.search.documents.implementation.converters` that will -need to be updated if any of the models that get converted have new properties added. The converted model types are -`AnalyzeRequest`, `IndexAction`, `SearchResult`, and `SuggestResult`. - -### SearchOptions - -There is `SearchOptions` in both implementation and public API, any time new properties are added to the implementation -`SearchOptions` they need to be included in the public API model. Additionally, `List`-based properties use varargs -setters instead of `List` setters in the public API and `QueryAnswerType` and `QueryCaptionType` properties need special -handling. `QueryAnswerType` and `QueryCaptionType` are defined as `ExpandableStringEnum`s but they have special -configurations based on the String value that Autorest cannot generate, `QueryAnswerType` has special configurations -`answerCount` and `answerThreshold` and `QueryCaptionType` has special configuration `highlight` that need to be added -as additional properties on the public `SearchOptions`. - -### AutocompleteOptions and SuggestOptions - -`AutocompleteOptions` and `SuggestOptions` have converters that need to be updated with new properties are added so they -match `AutocompleteRequest` or `SuggestRequest`. The options-based and request-based models are code generated but only -the options-based models are generated into the public API. - -## Configuration - -### Basic Information -These are the global settings for SearchServiceClient and SearchIndexClient. - -``` yaml -opt-in-extensible-enums: true -openapi-type: data-plane -``` - -### Tag: searchindex - -These settings apply only when `--tag=searchindex` is specified on the command line. - -``` yaml $(tag) == 'searchindex' -namespace: com.azure.search.documents -input-file: -- https://raw.githubusercontent.com/Azure/azure-rest-api-specs/14531a7cf6101c1dd57e7c1c83103a047bb8f5bb/specification/search/data-plane/Azure.Search/preview/2024-11-01-preview/searchindex.json -models-subpackage: models -custom-types-subpackage: implementation.models -custom-types: AutocompleteRequest,IndexAction,IndexBatch,RequestOptions,SearchDocumentsResult,SearchErrorException,SearchOptions,SearchRequest,SearchResult,SuggestDocumentsResult,SuggestRequest,SuggestResult,ErrorAdditionalInfo,ErrorDetail,ErrorResponse,ErrorResponseException,Speller -customization-class: src/main/java/SearchIndexCustomizations.java -directive: - - rename-model: - from: RawVectorQuery - to: VectorizedQuery -``` - -### Tag: searchservice - -These settings apply only when `--tag=searchservice` is specified on the commandSearchServiceCounters line. - -``` yaml $(tag) == 'searchservice' -namespace: com.azure.search.documents.indexes -input-file: -- https://raw.githubusercontent.com/Azure/azure-rest-api-specs/14531a7cf6101c1dd57e7c1c83103a047bb8f5bb/specification/search/data-plane/Azure.Search/preview/2024-11-01-preview/searchservice.json -models-subpackage: models -custom-types-subpackage: implementation.models -custom-types: AnalyzeRequest,AnalyzeResult,AzureActiveDirectoryApplicationCredentials,DataSourceCredentials,DocumentKeysOrIds,EdgeNGramTokenFilterV1,EdgeNGramTokenFilterV2,EntityRecognitionSkillV1,EntityRecognitionSkillV3,KeywordTokenizerV1,KeywordTokenizerV2,ListAliasesResult,ListDataSourcesResult,ListIndexersResult,ListIndexesResult,ListSkillsetsResult,ListSynonymMapsResult,LuceneStandardTokenizerV1,LuceneStandardTokenizerV2,NGramTokenFilterV1,NGramTokenFilterV2,RequestOptions,SearchErrorException,SentimentSkillV1,SentimentSkillV3,SkillNames,ErrorAdditionalInfo,ErrorDetail,ErrorResponse,ErrorResponseException -customization-class: src/main/java/SearchServiceCustomizations.java -directive: - - rename-model: - from: ClassicSimilarity - to: ClassicSimilarityAlgorithm - - rename-model: - from: BM25Similarity - to: BM25SimilarityAlgorithm - - rename-model: - from: Similarity - to: SimilarityAlgorithm - - rename-model: - from: GetIndexStatisticsResult - to: SearchIndexStatistics - - rename-model: - from: Suggester - to: SearchSuggester - - rename-model: - from: PIIDetectionSkill - to: PiiDetectionSkill - - rename-model: - from: EntityRecognitionSkill - to: EntityRecognitionSkillV1 - - rename-model: - from: SentimentSkill - to: SentimentSkillV1 - - rename-model: - from: EdgeNGramTokenFilter - to: EdgeNGramTokenFilterV1 - - rename-model: - from: NGramTokenFilter - to: NGramTokenFilterV1 - - rename-model: - from: PathHierarchyTokenizerV2 - to: PathHierarchyTokenizer - - rename-model: - from: LuceneStandardTokenizer - to: LuceneStandardTokenizerV1 - - rename-model: - from: KeywordTokenizer - to: KeywordTokenizerV1 - - rename-model: - from: SearchIndexerDataSource - to: SearchIndexerDataSourceConnection -``` - ---- -# Code Generation - -!!! READ THIS !!! -This swagger is ready for C# and Java. -!!! READ THIS !!! - -## Java - -``` yaml -output-folder: ../ -java: true -use: '@autorest/java@4.1.42' -enable-sync-stack: true -generate-client-as-impl: true -required-fields-as-ctor-args: true -license-header: MICROSOFT_MIT_SMALL_NO_VERSION -disable-client-builder: true -include-read-only-in-constructor-args: true -``` - -### Set odata.metadata Accept header in operations - -searchindex.json needs odata.metadata=none and searchservice.json needs odata.metadata=minimal as the "Accept" header. - -``` yaml $(java) -directive: - - from: swagger-document - where: $.paths - transform: > - for (var path in $) { - for (var opName in $[path]) { - let accept = "application/json; odata.metadata="; - accept += path.startsWith("/docs") ? "none" : "minimal"; - - let op = $[path][opName]; - let param = op.parameters.find(p => p.name === "Accept"); - if (param === null) { - param.enum = [ accept ]; - } else { - op.parameters.push({ - name: "Accept", - "in": "header", - required: true, - type: "string", - enum: [ accept ], - "x-ms-parameter-location": "method" - }); - } - } - } - - return $; -``` - -### Remove required from properties that are optional - -``` yaml $(tag) == 'searchservice' -directive: - - from: "searchservice.json" - where: $.definitions - transform: > - $.SearchIndex.required = $.SearchIndex.required.filter(required => required === 'name'); - $.SearchIndexer.required = $.SearchIndexer.required.filter(required => required === 'name'); - $.SearchIndexerDataSourceConnection.required = $.SearchIndexerDataSourceConnection.required.filter(required => required === 'name'); - $.SearchIndexerSkillset.required = $.SearchIndexerSkillset.required.filter(required => required === 'name'); - delete $.SynonymMap.required; - $.ServiceCounters.required = $.ServiceCounters.required.filter(required => required !== 'aliasesCount' && required !== 'skillsetCount' && required !== 'vectorIndexSize'); - $.SearchIndexStatistics.required = $.SearchIndexStatistics.required.filter(required => required !== 'vectorIndexSize'); -``` - -### Renames -``` yaml $(tag) == 'searchservice' -directive: - - from: "searchservice.json" - where: $.definitions - transform: > - $.ServiceCounters["x-ms-client-name"] = "SearchServiceCounters"; - $.ServiceLimits["x-ms-client-name"] = "SearchServiceLimits"; - $.ServiceLimits.properties.maxStoragePerIndex["x-ms-client-name"] = "maxStoragePerIndexInBytes"; - $.ServiceStatistics["x-ms-client-name"] = "SearchServiceStatistics"; -``` - -``` yaml $(java) -directive: - - from: swagger-document - where: $.definitions.PdfTextRotationAlgorithm - transform: > - $["x-ms-enum"].name = "BlobIndexerPdfTextRotationAlgorithm"; -``` - -### Add serialization discriminator to LexicalNormalizer -``` yaml $(java) -directive: - - from: swagger-document - where: $.definitions.LexicalNormalizer - transform: > - $.discriminator = "@odata.type"; -``` - -### Change SearchField retrievable to hidden -```yaml $(tag) == 'searchservice' -directive: - - from: swagger-document - where: $.definitions.SearchField.properties - transform: > - $.retrievable["x-ms-client-name"] = "hidden"; - $.retrievable.description = "A value indicating whether the field will be returned in a search result. This property must be false for key fields, and must be null for complex fields. You can hide a field from search results if you want to use it only as a filter, for sorting, or for scoring. This property can also be changed on existing fields and enabling it does not cause an increase in index storage requirements."; - $.analyzer["x-ms-client-name"] = "analyzerName"; - $.searchAnalyzer["x-ms-client-name"] = "searchAnalyzerName"; - $.indexAnalyzer["x-ms-client-name"] = "indexAnalyzerName"; - $.synonymMaps["x-ms-client-name"] = "synonymMapNames"; -``` - -### Rename includeTotalResultCount to includeTotalCount -``` yaml $(java) -directive: - - from: swagger-document - where: $.paths["/docs"].get.parameters - transform: > - let param = $.find(p => p.name === "$count"); - param["x-ms-client-name"] = "includeTotalCount"; -``` - -### Change Answers, Captions, and QueryRewrites to a string in SearchOptions and SearchRequest -``` yaml $(java) -directive: - - from: swagger-document - where: $.paths["/docs"].get.parameters - transform: > - let param = $.find(p => p.name === "answers"); - param.type = "string"; - delete param.enum; - delete param["x-ms-enum"]; - - param = $.find(p => p.name == "captions"); - param.type = "string"; - delete param.enum; - delete param["x-ms-enum"]; - - param = $.find(p => p.name == "queryRewrites"); - param.type = "string"; - delete param.enum; - delete param["x-ms-enum"]; - - -``` - -``` yaml $(tag) == 'searchindex' -directive: - - from: "searchindex.json" - where: $.definitions - transform: > - let param = $.SearchRequest.properties.answers; - param.type = "string"; - param.description = $.Answers.description; - delete param["$ref"]; - - param = $.SearchRequest.properties.captions; - param.type = "string"; - param.description = $.Captions.description; - delete param["$ref"]; - - param = $.SearchRequest.properties.queryRewrites; - param.type = "string"; - param.description = $.QueryRewrites.description; - delete param["$ref"]; -``` - -### Remove applicationId from being required in AzureActiveDirectoryApplicationCredentials -``` yaml $(java) -directive: - - from: swagger-document - where: $.definitions.AzureActiveDirectoryApplicationCredentials - transform: > - delete $.required; -``` - -### Client side rename of SearchResourceEncryptionKey's vaultUri to vaultUrl -``` yaml $(java) -directive: - - from: swagger-document - where: $.definitions.SearchResourceEncryptionKey - transform: > - $.properties.keyVaultUri["x-ms-client-name"] = "vaultUrl"; -``` - -### Remove Suggester's SearchMode from being required -``` yaml $(java) -directive: - - from: swagger-document - where: $.definitions.SearchSuggester - transform: > - $.required = [ "name", "sourceFields" ]; -``` - -### Rename PIIDetectionSkillMaskingMode to PiiDetectionSkillMaskingMode -```yaml $(tag) == 'searchservice' -directive: - - from: swagger-document - where: $.definitions.PIIDetectionSkillMaskingMode - transform: > - $["x-ms-enum"].name = "PiiDetectionSkillMaskingMode"; -``` - -### Rename client parameter names -``` yaml $(tag) == 'searchservice' -directive: - - from: "searchservice.json" - where: $.definitions - transform: > - $.CommonGramTokenFilter.properties.ignoreCase["x-ms-client-name"] = "caseIgnored"; - $.CommonGramTokenFilter.properties.queryMode["x-ms-client-name"] = "queryModeUsed"; - $.DictionaryDecompounderTokenFilter.properties.onlyLongestMatch["x-ms-client-name"] = "onlyLongestMatched"; - $.KeywordMarkerTokenFilter.properties.ignoreCase["x-ms-client-name"] = "caseIgnored"; - $.LimitTokenFilter.properties.consumeAllTokens["x-ms-client-name"] = "allTokensConsumed"; - $.MicrosoftLanguageStemmingTokenizer.properties.isSearchTokenizer["x-ms-client-name"] = "isSearchTokenizerUsed"; - $.PathHierarchyTokenizer.properties.reverse["x-ms-client-name"] = "tokenOrderReversed"; - $.PhoneticTokenFilter.properties.replace["x-ms-client-name"] = "originalTokensReplaced"; - $.StopwordsTokenFilter.properties.ignoreCase["x-ms-client-name"] = "caseIgnored"; - $.StopwordsTokenFilter.properties.removeTrailing["x-ms-client-name"] = "trailingStopWordsRemoved"; - $.SynonymTokenFilter.properties.ignoreCase["x-ms-client-name"] = "caseIgnored"; - $.WordDelimiterTokenFilter.properties.catenateWords["x-ms-client-name"] = "wordsCatenated"; - $.WordDelimiterTokenFilter.properties.catenateNumbers["x-ms-client-name"] = "numbersCatenated"; -``` - -### Add `arm-id` format for `AuthResourceId` - -Add `"format": "arm-id"` for `AuthResourceId` to generate as [Azure.Core.ResourceIdentifier](https://learn.microsoft.com/dotnet/api/azure.core.resourceidentifier?view=azure-dotnet). - -```yaml $(tag) == 'searchservice' -directive: -- from: swagger-document - where: $.definitions.WebApiSkill.properties.authResourceId - transform: $["x-ms-format"] = "arm-id"; -``` - -### Rename VectorQuery property `K` - -Rename VectorQuery property `K` to `KNearestNeighborsCount` - -```yaml $(tag) == 'searchindex' -directive: -- from: swagger-document - where: $.definitions.VectorQuery.properties.k - transform: $["x-ms-client-name"] = "KNearestNeighborsCount"; -``` - -### Rename `AMLVectorizer` to `AzureMachineLearningVectorizer` - -```yaml $(tag) == 'searchservice' -directive: -- from: swagger-document - where: $.definitions.AMLVectorizer - transform: $["x-ms-client-name"] = "AzureMachineLearningVectorizer"; -``` - -### Rename `AMLParameters` to `AzureMachineLearningParameters` - -```yaml $(tag) == 'searchservice' -directive: -- from: swagger-document - where: $.definitions.AMLParameters - transform: $["x-ms-client-name"] = "AzureMachineLearningParameters"; -``` - -### Archboard feedback for 2024-07-01 - -```yaml $(tag) == 'searchservice' -directive: -- from: "searchservice.json" - where: $.definitions - transform: > - $.AzureOpenAIParameters["x-ms-client-name"] = "AzureOpenAIVectorizerParameters"; - $.AzureOpenAIParameters.properties.resourceUri["x-ms-client-name"] = "resourceUrl"; - - $.AzureOpenAIVectorizer.properties.azureOpenAIParameters["x-ms-client-name"] = "parameters"; - - $.SearchIndexerDataUserAssignedIdentity.properties.userAssignedIdentity["x-ms-client-name"] = "resourceId"; - - $.SearchIndexerIndexProjections["x-ms-client-name"] = "SearchIndexerIndexProjection"; - $.SearchIndexerSkillset.properties.indexProjections["x-ms-client-name"] = "indexProjection"; - - $.VectorSearchCompressionConfiguration["x-ms-client-name"] = "VectorSearchCompression"; - $.VectorSearchCompressionConfiguration.properties.name["x-ms-client-name"] = "compressionName"; - $.ScalarQuantizationVectorSearchCompressionConfiguration["x-ms-client-name"] = "ScalarQuantizationCompression"; - $.BinaryQuantizationVectorSearchCompressionConfiguration["x-ms-client-name"] = "BinaryQuantizationCompression"; - $.VectorSearchProfile.properties.compression["x-ms-client-name"] = "compressionName"; - - $.VectorSearchVectorizer.properties.name["x-ms-client-name"] = "vectorizerName"; - - $.WebApiParameters["x-ms-client-name"] = "WebApiVectorizerParameters"; - $.WebApiParameters.properties.uri["x-ms-client-name"] = "url"; - - $.VectorSearchCompressionTargetDataType["x-ms-client-name"] = "VectorSearchCompressionTarget"; - $.VectorSearchCompressionTargetDataType["x-ms-enum"].name = "VectorSearchCompressionTarget"; - - $.OcrSkillLineEnding["x-ms-client-name"] = "OcrLineEnding"; - $.OcrSkillLineEnding["x-ms-enum"].name = "OcrLineEnding"; -``` - -### Rename Speller to QuerySpellerType -``` yaml $(java) -directive: - - from: swagger-document - where: $.paths["/docs"].get.parameters - transform: > - $.find(p => p.name === "speller")["x-ms-enum"].name = "QuerySpellerType"; -``` - -### Fix `SearchResult["@search.documentDebugInfo"]` -``` yaml $(tag) == 'searchindex' -directive: - - from: swagger-document - where: $.definitions.SearchResult.properties - transform: > - $["@search.documentDebugInfo"]["$ref"] = $["@search.documentDebugInfo"].items["$ref"]; - delete $["@search.documentDebugInfo"].type; - delete $["@search.documentDebugInfo"].items; -``` - -### `SearchDocumentsResult["@search.debugInfo"]` -> `SearchDocumentsResult["@search.debug"]` -``` yaml $(tag) == 'searchindex' -directive: - - from: swagger-document - where: $.definitions.SearchDocumentsResult.properties - transform: > - $["@search.debug"] = $["@search.debugInfo"]; - delete $["@search.debugInfo"]; -``` diff --git a/sdk/search/azure-search-documents/swagger/Update-Codegeneration.ps1 b/sdk/search/azure-search-documents/swagger/Update-Codegeneration.ps1 deleted file mode 100644 index d97b18f6df8c..000000000000 --- a/sdk/search/azure-search-documents/swagger/Update-Codegeneration.ps1 +++ /dev/null @@ -1,2 +0,0 @@ -& (Join-Path $PSScriptRoot ".." ".." ".." ".." eng scripts Invoke-Codegeneration.ps1) -Directory $PSScriptRoot -AutorestOptions '--tag=searchindex' -& (Join-Path $PSScriptRoot ".." ".." ".." ".." eng scripts Invoke-Codegeneration.ps1) -Directory $PSScriptRoot -AutorestOptions '--tag=searchservice' diff --git a/sdk/search/azure-search-documents/swagger/pom.xml b/sdk/search/azure-search-documents/swagger/pom.xml deleted file mode 100644 index 23dcd3377ae8..000000000000 --- a/sdk/search/azure-search-documents/swagger/pom.xml +++ /dev/null @@ -1,21 +0,0 @@ - - - 4.0.0 - - - com.azure - azure-code-customization-parent - 1.0.0-beta.1 - ../../../parents/azure-code-customization-parent - - - Microsoft Azure AI Search client for Java - This package contains client functionality for Microsoft Azure AI Search - - com.azure.tools - azure-search-documents-autorest-customization - 1.0.0-beta.1 - jar - diff --git a/sdk/search/azure-search-documents/swagger/src/main/java/SearchIndexCustomizations.java b/sdk/search/azure-search-documents/swagger/src/main/java/SearchIndexCustomizations.java deleted file mode 100644 index 4e8939fe1f99..000000000000 --- a/sdk/search/azure-search-documents/swagger/src/main/java/SearchIndexCustomizations.java +++ /dev/null @@ -1,424 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -import com.azure.autorest.customization.ClassCustomization; -import com.azure.autorest.customization.Customization; -import com.azure.autorest.customization.LibraryCustomization; -import com.azure.autorest.customization.PackageCustomization; -import com.azure.json.JsonReader; -import com.azure.json.JsonSerializable; -import com.azure.json.JsonToken; -import com.azure.json.JsonWriter; -import com.github.javaparser.StaticJavaParser; -import com.github.javaparser.ast.Modifier; -import com.github.javaparser.ast.NodeList; -import com.github.javaparser.ast.body.BodyDeclaration; -import com.github.javaparser.ast.body.ClassOrInterfaceDeclaration; -import com.github.javaparser.ast.body.FieldDeclaration; -import com.github.javaparser.ast.body.MethodDeclaration; -import com.github.javaparser.ast.body.Parameter; -import com.github.javaparser.ast.expr.LongLiteralExpr; -import com.github.javaparser.ast.expr.MarkerAnnotationExpr; -import com.github.javaparser.ast.stmt.BlockStmt; -import com.github.javaparser.ast.type.Type; -import com.github.javaparser.javadoc.Javadoc; -import com.github.javaparser.javadoc.description.JavadocDescription; -import org.slf4j.Logger; - -import java.io.IOException; -import java.io.Serializable; -import java.util.Arrays; -import java.util.Locale; -import java.util.function.Consumer; - -/** - * Contains customizations for Azure Search's index swagger code generation. - */ -public class SearchIndexCustomizations extends Customization { - private static final String VARARG_METHOD_TEMPLATE = joinWithNewline("{", - " this.%1$s = (%1$s == null) ? null : Arrays.asList(%1$s);", " return this;", "}"); - - @Override - public void customize(LibraryCustomization libraryCustomization, Logger logger) { - customizeModelsPackage(libraryCustomization.getPackage("com.azure.search.documents.models")); - customizeImplementationModelsPackage( - libraryCustomization.getPackage("com.azure.search.documents.implementation.models")); - - // Remove all GET-based documents APIs as the SDK doesn't use them. - libraryCustomization.getPackage("com.azure.search.documents.implementation") - .getClass("DocumentsImpl") - .customizeAst(ast -> { - ClassOrInterfaceDeclaration clazz = ast.getClassByName("DocumentsImpl").get(); - clazz.getMethodsByName("searchGetWithResponseAsync").forEach(MethodDeclaration::remove); - clazz.getMethodsByName("searchGetWithResponse").forEach(MethodDeclaration::remove); - clazz.getMethodsByName("searchGetAsync").forEach(MethodDeclaration::remove); - clazz.getMethodsByName("searchGet").forEach(MethodDeclaration::remove); - clazz.getMethodsByName("suggestGetWithResponseAsync").forEach(MethodDeclaration::remove); - clazz.getMethodsByName("suggestGetWithResponse").forEach(MethodDeclaration::remove); - clazz.getMethodsByName("suggestGetAsync").forEach(MethodDeclaration::remove); - clazz.getMethodsByName("suggestGet").forEach(MethodDeclaration::remove); - clazz.getMethodsByName("autocompleteGetWithResponseAsync").forEach(MethodDeclaration::remove); - clazz.getMethodsByName("autocompleteGetWithResponse").forEach(MethodDeclaration::remove); - clazz.getMethodsByName("autocompleteGetAsync").forEach(MethodDeclaration::remove); - clazz.getMethodsByName("autocompleteGet").forEach(MethodDeclaration::remove); - - clazz.getMembers() - .stream() - .filter(BodyDeclaration::isClassOrInterfaceDeclaration) - .filter( - member -> "DocumentsService".equals(member.asClassOrInterfaceDeclaration().getNameAsString())) - .map(BodyDeclaration::asClassOrInterfaceDeclaration) - .findFirst() - .ifPresent(interfaceClazz -> { - interfaceClazz.getMethodsByName("searchGet").forEach(MethodDeclaration::remove); - interfaceClazz.getMethodsByName("searchGetSync").forEach(MethodDeclaration::remove); - interfaceClazz.getMethodsByName("suggestGet").forEach(MethodDeclaration::remove); - interfaceClazz.getMethodsByName("suggestGetSync").forEach(MethodDeclaration::remove); - interfaceClazz.getMethodsByName("autocompleteGet").forEach(MethodDeclaration::remove); - interfaceClazz.getMethodsByName("autocompleteGetSync").forEach(MethodDeclaration::remove); - }); - }); - } - - private void customizeModelsPackage(PackageCustomization packageCustomization) { - customizeAutocompleteOptions(packageCustomization.getClass("AutocompleteOptions")); - customizeSuggestOptions(packageCustomization.getClass("SuggestOptions")); - customizeIndexingResult(packageCustomization.getClass("IndexingResult")); - customizeVectorQuery(packageCustomization.getClass("VectorQuery")); - customizeVectorizedQuery(packageCustomization.getClass("VectorizedQuery")); - customizeVectorizableTextQuery(packageCustomization.getClass("VectorizableTextQuery")); - customizeVectorizableImageUrlQuery(packageCustomization.getClass("VectorizableImageUrlQuery")); - customizeVectorizableImageBinaryQuery(packageCustomization.getClass("VectorizableImageBinaryQuery")); - customizeSearchScoreThreshold(packageCustomization.getClass("SearchScoreThreshold")); - - packageCustomization.getClass("QueryAnswerResult").removeMethod("setAdditionalProperties"); - packageCustomization.getClass("QueryCaptionResult").removeMethod("setAdditionalProperties"); - } - - private void customizeAutocompleteOptions(ClassCustomization classCustomization) { - customizeAst(classCustomization, clazz -> { - clazz.tryAddImportToParentCompilationUnit(JsonSerializable.class); - clazz.tryAddImportToParentCompilationUnit(JsonReader.class); - clazz.tryAddImportToParentCompilationUnit(JsonWriter.class); - clazz.tryAddImportToParentCompilationUnit(JsonToken.class); - clazz.tryAddImportToParentCompilationUnit(IOException.class); - - clazz.addImplementedType("JsonSerializable"); - - clazz.getMethodsByName("isUseFuzzyMatching").get(0).setName("useFuzzyMatching"); - addVarArgsOverload(clazz, "searchFields", "String"); - - clazz.addMethod("toJson", Modifier.Keyword.PUBLIC) - .addAnnotation(new MarkerAnnotationExpr("Override")) - .setType("JsonWriter") - .addParameter("JsonWriter", "jsonWriter") - .addThrownException(IOException.class) - .setBody(StaticJavaParser.parseBlock(joinWithNewline("{", "jsonWriter.writeStartObject();", - "jsonWriter.writeStringField(\"autocompleteMode\", this.autocompleteMode == null ? null : this.autocompleteMode.toString());", - "jsonWriter.writeStringField(\"$filter\", this.filter);", - "jsonWriter.writeBooleanField(\"UseFuzzyMatching\", this.useFuzzyMatching);", - "jsonWriter.writeStringField(\"highlightPostTag\", this.highlightPostTag);", - "jsonWriter.writeStringField(\"highlightPreTag\", this.highlightPreTag);", - "jsonWriter.writeNumberField(\"minimumCoverage\", this.minimumCoverage);", - "jsonWriter.writeArrayField(\"searchFields\", this.searchFields, (writer, element) -> writer.writeString(element));", - "jsonWriter.writeNumberField(\"$top\", this.top);", "return jsonWriter.writeEndObject();", "}"))) - .setJavadocComment("{@inheritDoc}"); - - clazz.addMethod("fromJson", Modifier.Keyword.PUBLIC, Modifier.Keyword.STATIC) - .setType("AutocompleteOptions") - .addParameter("JsonReader", "jsonReader") - .addThrownException(IOException.class) - .setBody(StaticJavaParser.parseBlock(joinWithNewline("{", "return jsonReader.readObject(reader -> {", - " AutocompleteOptions deserializedAutocompleteOptions = new AutocompleteOptions();", - " while (reader.nextToken() != JsonToken.END_OBJECT) {", - " String fieldName = reader.getFieldName();", " reader.nextToken();", - " if (\"autocompleteMode\".equals(fieldName)) {", - " deserializedAutocompleteOptions.autocompleteMode = AutocompleteMode.fromString(reader.getString());", - " } else if (\"$filter\".equals(fieldName)) {", - " deserializedAutocompleteOptions.filter = reader.getString();", - " } else if (\"UseFuzzyMatching\".equals(fieldName)) {", - " deserializedAutocompleteOptions.useFuzzyMatching = reader.getNullable(JsonReader::getBoolean);", - " } else if (\"highlightPostTag\".equals(fieldName)) {", - " deserializedAutocompleteOptions.highlightPostTag = reader.getString();", - " } else if (\"highlightPreTag\".equals(fieldName)) {", - " deserializedAutocompleteOptions.highlightPreTag = reader.getString();", - " } else if (\"minimumCoverage\".equals(fieldName)) {", - " deserializedAutocompleteOptions.minimumCoverage = reader.getNullable(JsonReader::getDouble);", - " } else if (\"searchFields\".equals(fieldName)) {", - " List searchFields = reader.readArray(reader1 -> reader1.getString());", - " deserializedAutocompleteOptions.searchFields = searchFields;", - " } else if (\"$top\".equals(fieldName)) {", - " deserializedAutocompleteOptions.top = reader.getNullable(JsonReader::getInt);", - " } else {", " reader.skipChildren();", " }", " }", - " return deserializedAutocompleteOptions;", "});", "}"))) - .setJavadocComment(new Javadoc(JavadocDescription.parseText( - "Reads an instance of AutocompleteOptions from the JsonReader.")).addBlockTag("param", "jsonReader", - "The JsonReader being read.") - .addBlockTag("return", - "An instance of AutocompleteOptions if the JsonReader was pointing to an instance of it, or null if it was pointing to JSON null.") - .addBlockTag("throws", "IOException If an error occurs while reading the AutocompleteOptions.")); - }); - } - - private void customizeSuggestOptions(ClassCustomization classCustomization) { - customizeAst(classCustomization, clazz -> { - clazz.tryAddImportToParentCompilationUnit(JsonSerializable.class); - clazz.tryAddImportToParentCompilationUnit(JsonReader.class); - clazz.tryAddImportToParentCompilationUnit(JsonWriter.class); - clazz.tryAddImportToParentCompilationUnit(JsonToken.class); - clazz.tryAddImportToParentCompilationUnit(IOException.class); - - clazz.addImplementedType("JsonSerializable"); - - clazz.getMethodsByName("isUseFuzzyMatching").get(0).setName("useFuzzyMatching"); - - addVarArgsOverload(clazz, "orderBy", "String"); - addVarArgsOverload(clazz, "searchFields", "String"); - addVarArgsOverload(clazz, "select", "String"); - - clazz.addMethod("toJson", Modifier.Keyword.PUBLIC) - .addAnnotation(new MarkerAnnotationExpr("Override")) - .setType("JsonWriter") - .addParameter("JsonWriter", "jsonWriter") - .addThrownException(IOException.class) - .setBody(StaticJavaParser.parseBlock(joinWithNewline("{", "jsonWriter.writeStartObject();", - "jsonWriter.writeStringField(\"$filter\", this.filter);", - "jsonWriter.writeBooleanField(\"UseFuzzyMatching\", this.useFuzzyMatching);", - "jsonWriter.writeStringField(\"highlightPostTag\", this.highlightPostTag);", - "jsonWriter.writeStringField(\"highlightPreTag\", this.highlightPreTag);", - "jsonWriter.writeNumberField(\"minimumCoverage\", this.minimumCoverage);", - "jsonWriter.writeArrayField(\"OrderBy\", this.orderBy, (writer, element) -> writer.writeString(element));", - "jsonWriter.writeArrayField(\"searchFields\", this.searchFields, (writer, element) -> writer.writeString(element));", - "jsonWriter.writeArrayField(\"$select\", this.select, (writer, element) -> writer.writeString(element));", - "jsonWriter.writeNumberField(\"$top\", this.top);", "return jsonWriter.writeEndObject();", "}"))) - .setJavadocComment("{@inheritDoc}"); - - clazz.addMethod("fromJson", Modifier.Keyword.PUBLIC, Modifier.Keyword.STATIC) - .setType("SuggestOptions") - .addParameter("JsonReader", "jsonReader") - .addThrownException(IOException.class) - .setBody(StaticJavaParser.parseBlock(joinWithNewline("{", "return jsonReader.readObject(reader -> {", - " SuggestOptions deserializedSuggestOptions = new SuggestOptions();", - " while (reader.nextToken() != JsonToken.END_OBJECT) {", - " String fieldName = reader.getFieldName();", " reader.nextToken();", - " if (\"$filter\".equals(fieldName)) {", - " deserializedSuggestOptions.filter = reader.getString();", - " } else if (\"UseFuzzyMatching\".equals(fieldName)) {", - " deserializedSuggestOptions.useFuzzyMatching = reader.getNullable(JsonReader::getBoolean);", - " } else if (\"highlightPostTag\".equals(fieldName)) {", - " deserializedSuggestOptions.highlightPostTag = reader.getString();", - " } else if (\"highlightPreTag\".equals(fieldName)) {", - " deserializedSuggestOptions.highlightPreTag = reader.getString();", - " } else if (\"minimumCoverage\".equals(fieldName)) {", - " deserializedSuggestOptions.minimumCoverage = reader.getNullable(JsonReader::getDouble);", - " } else if (\"OrderBy\".equals(fieldName)) {", - " List orderBy = reader.readArray(reader1 -> reader1.getString());", - " deserializedSuggestOptions.orderBy = orderBy;", - " } else if (\"searchFields\".equals(fieldName)) {", - " List searchFields = reader.readArray(reader1 -> reader1.getString());", - " deserializedSuggestOptions.searchFields = searchFields;", - " } else if (\"$select\".equals(fieldName)) {", - " List select = reader.readArray(reader1 -> reader1.getString());", - " deserializedSuggestOptions.select = select;", - " } else if (\"$top\".equals(fieldName)) {", - " deserializedSuggestOptions.top = reader.getNullable(JsonReader::getInt);", - " } else {", " reader.skipChildren();", " }", " }", - " return deserializedSuggestOptions;", "});", "}"))) - .setJavadocComment(new Javadoc(JavadocDescription.parseText( - "Reads an instance of SuggestOptions from the JsonReader.")).addBlockTag("param", "jsonReader", - "The JsonReader being read.") - .addBlockTag("return", - "An instance of SuggestOptions if the JsonReader was pointing to an instance of it, or null if it was pointing to JSON null.") - .addBlockTag("throws", "IOException If an error occurs while reading the SuggestOptions.")); - }); - } - - private void customizeImplementationModelsPackage(PackageCustomization packageCustomization) { - customizeSearchOptions(packageCustomization.getClass("SearchOptions")); - customizeIndexAction(packageCustomization.getClass("IndexAction")); - // customizeSearchError(packageCustomization.getClass("SearchError")); - } - - private void customizeSearchOptions(ClassCustomization classCustomization) { - customizeAst(classCustomization, clazz -> { - ; - clazz.getMethodsByName("isIncludeTotalCount").get(0).setName("isTotalCountIncluded"); - - addVarArgsOverload(clazz, "facets", "String"); - addVarArgsOverload(clazz, "orderBy", "String"); - addVarArgsOverload(clazz, "searchFields", "String"); - addVarArgsOverload(clazz, "select", "String"); - addVarArgsOverload(clazz, "highlightFields", "String"); - }); - - // Can't be done right now as setScoringParameters uses String. - // // Scoring parameters are slightly different as code generates them as String. - // classCustomization.getMethod("setScoringParameters").replaceParameters("ScoringParameter... scoringParameters") - // .replaceBody( - // "this.scoringParameters = (scoringParameters == null)" - // + " ? null" - // + " : java.util.Arrays.stream(scoringParameters)" - // + " .map(ScoringParameter::toString)" - // + " .collect(java.util.stream.Collectors.toList());" - // + "return this;"); - // - // classCustomization.getMethod("getScoringParameters") - // .setReturnType("List", - // "this.scoringParameters.stream().map(ScoringParameter::new).collect(java.util.stream.Collectors.toList())"); - } - - private void customizeVectorQuery(ClassCustomization classCustomization) { - customizeAst(classCustomization, clazz -> clazz.getMethodsByName("setFields") - .get(0) - .setParameters(new NodeList<>(new Parameter().setType("String").setName("fields").setVarArgs(true))) - .setBody(StaticJavaParser.parseBlock( - joinWithNewline("{", " this.fields = (fields == null) ? null : String.join(\",\", fields);", - " return this;", "}")))); - } - - private void customizeVectorizedQuery(ClassCustomization classCustomization) { - customizeAst(classCustomization, clazz -> clazz.getMethodsByName("setFields") - .get(0) - .setParameters(new NodeList<>(new Parameter().setType("String").setName("fields").setVarArgs(true)))); - } - - private void customizeVectorizableTextQuery(ClassCustomization classCustomization) { - customizeAst(classCustomization, clazz -> { - clazz.getFieldByName("queryRewrites").get().getVariable(0).setType("QueryRewrites"); - clazz.getMethodsByName("getQueryRewrites").getFirst().setType("QueryRewrites"); - clazz.getMethodsByName("setQueryRewrites").getFirst().setParameters(new NodeList<>(new Parameter().setType("QueryRewrites").setName("queryRewrites"))); - String newBodyFromJson = clazz.getMethodsByName("fromJson").getFirst().getBody().get().toString().replaceAll("QueryRewritesType", "QueryRewrites"); - clazz.getMethodsByName("fromJson").getFirst().setBody(StaticJavaParser.parseBlock(newBodyFromJson)); - }); - customizeAst(classCustomization, clazz -> clazz.getMethodsByName("setFields") - .get(0) - .setParameters(new NodeList<>(new Parameter().setType("String").setName("fields").setVarArgs(true)))); - } - - private void customizeIndexAction(ClassCustomization classCustomization) { - customizeAst(classCustomization, clazz -> { - clazz.addPrivateField("String", "rawDocument"); - clazz.addMethod("getRawDocument", Modifier.Keyword.PUBLIC) - .setType("String") - .setBody(new BlockStmt(new NodeList<>(StaticJavaParser.parseStatement("return this.rawDocument;")))) - .setJavadocComment(StaticJavaParser.parseJavadoc( - joinWithNewline("/**", " * Gets the raw JSON document.", " * @return The raw JSON document.", - " */"))); - - clazz.addMethod("setRawDocument", Modifier.Keyword.PUBLIC) - .setType("IndexAction") - .addParameter("String", "rawDocument") - .setBody(new BlockStmt( - new NodeList<>(StaticJavaParser.parseStatement("this.rawDocument = rawDocument;"), - StaticJavaParser.parseStatement("return this;")))) - .setJavadocComment(StaticJavaParser.parseJavadoc( - joinWithNewline("/**", " * Sets the raw JSON document.", - " * @param rawDocument The raw JSON document.", " * @return the IndexAction object itself.", - " */"))); - }); - } - - private void customizeIndexingResult(ClassCustomization classCustomization) { - customizeAst(classCustomization, clazz -> { - clazz.addImplementedType(Serializable.class); - clazz.addFieldWithInitializer("long", "serialVersionUID", new LongLiteralExpr("-8604424005271188140L"), - Modifier.Keyword.PRIVATE, Modifier.Keyword.STATIC, Modifier.Keyword.FINAL); - - FieldDeclaration field = clazz.getFieldByName("key").get(); - field.setJavadocComment(field.getComment().get().asBlockComment().getContent()); - - field = clazz.getFieldByName("errorMessage").get(); - field.setJavadocComment(field.getComment().get().asBlockComment().getContent()); - - field = clazz.getFieldByName("succeeded").get(); - field.setJavadocComment(field.getComment().get().asBlockComment().getContent()); - - field = clazz.getFieldByName("statusCode").get(); - field.setJavadocComment(field.getComment().get().asBlockComment().getContent()); - }); - } - - private void customizeSearchError(ClassCustomization classCustomization) { - customizeAst(classCustomization, clazz -> { - MethodDeclaration fromJson = clazz.getMethodsByName("fromJson").get(0); - - clazz.addMethod("readSearchError", Modifier.Keyword.PRIVATE, Modifier.Keyword.STATIC) - .setType("SearchError") - .addParameter("JsonReader", "jsonReader") - .addThrownException(IOException.class) - .setBody(fromJson.getBody().get()); - - fromJson.setBody(StaticJavaParser.parseBlock( - joinWithNewline("{", "return jsonReader.readObject(reader -> {", - " // Buffer the next JSON object as SearchError can take two forms:", " //", - " // - A SearchError object", " // - A SearchError object wrapped in an \"error\" node.", - " JsonReader bufferedReader = reader.bufferObject();", - " bufferedReader.nextToken(); // Get to the START_OBJECT token.", - " while (bufferedReader.nextToken() != JsonToken.END_OBJECT) {", - " String fieldName = bufferedReader.getFieldName();", " bufferedReader.nextToken();", - "", " if (\"error\".equals(fieldName)) {", - " // If the SearchError was wrapped in the \"error\" node begin reading it now.", - " return readSearchError(bufferedReader);", " } else {", - " bufferedReader.skipChildren();", " }", " }", "", - " // Otherwise reset the JsonReader and read the whole JSON object.", - " return readSearchError(bufferedReader.reset());", "});", "}"))); - }); - } - - private void customizeVectorizableImageUrlQuery(ClassCustomization classCustomization) { - customizeAst(classCustomization, clazz -> clazz.getMethodsByName("setFields") - .get(0) - .setParameters(new NodeList<>(new Parameter().setType("String").setName("fields").setVarArgs(true))) - .setBody(StaticJavaParser.parseBlock( - "{\n" + " super.setFields(fields);\n" + " return this;\n" + " }"))); - } - - private void customizeVectorizableImageBinaryQuery(ClassCustomization classCustomization) { - customizeAst(classCustomization, clazz -> clazz.getMethodsByName("setFields") - .get(0) - .setParameters(new NodeList<>(new Parameter().setType("String").setName("fields").setVarArgs(true))) - .setBody(StaticJavaParser.parseBlock( - "{\n" + " super.setFields(fields);\n" + " return this;\n" + " }"))); - } - - private void customizeSearchScoreThreshold(ClassCustomization classCustomization) { - customizeAst(classCustomization, clazz -> { - clazz.getMethodsByName("getValue") - .get(0) - .setJavadocComment(StaticJavaParser.parseJavadoc(joinWithNewline("/**", - " * Get the value property: 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`.", " *", " * @return the value.", " */"))); - }); - } - - private static void customizeAst(ClassCustomization classCustomization, - Consumer consumer) { - classCustomization.customizeAst(ast -> consumer.accept(ast.getClassByName(classCustomization.getClassName()) - .orElseThrow(() -> new RuntimeException("Class not found. " + classCustomization.getClassName())))); - } - - /* - * This helper function adds a varargs overload in addition to a List setter. - */ - private static void addVarArgsOverload(ClassOrInterfaceDeclaration clazz, String parameterName, - String parameterType) { - clazz.tryAddImportToParentCompilationUnit(Arrays.class); - - String methodName = "set" + parameterName.substring(0, 1).toUpperCase(Locale.ROOT) + parameterName.substring(1); - - String varargMethod = String.format(VARARG_METHOD_TEMPLATE, parameterName); - - Javadoc copyJavadoc = clazz.getMethodsByName(methodName).get(0).getJavadoc().get(); - clazz.addMethod(methodName, Modifier.Keyword.PUBLIC) - .setType(clazz.getNameAsString()) - .addParameter(StaticJavaParser.parseParameter(parameterType + "... " + parameterName)) - .setBody(StaticJavaParser.parseBlock(varargMethod)) - .setJavadocComment(copyJavadoc); - } - - private static String joinWithNewline(String... lines) { - return String.join("\n", lines); - } -} diff --git a/sdk/search/azure-search-documents/swagger/src/main/java/SearchServiceCustomizations.java b/sdk/search/azure-search-documents/swagger/src/main/java/SearchServiceCustomizations.java deleted file mode 100644 index 8a7d53a48f7a..000000000000 --- a/sdk/search/azure-search-documents/swagger/src/main/java/SearchServiceCustomizations.java +++ /dev/null @@ -1,724 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -import com.azure.autorest.customization.ClassCustomization; -import com.azure.autorest.customization.Customization; -import com.azure.autorest.customization.Editor; -import com.azure.autorest.customization.LibraryCustomization; -import com.azure.autorest.customization.PackageCustomization; -import com.github.javaparser.StaticJavaParser; -import com.github.javaparser.ast.CompilationUnit; -import com.github.javaparser.ast.Modifier; -import com.github.javaparser.ast.NodeList; -import com.github.javaparser.ast.body.ClassOrInterfaceDeclaration; -import com.github.javaparser.ast.body.MethodDeclaration; -import com.github.javaparser.ast.body.Parameter; -import com.github.javaparser.ast.stmt.BlockStmt; -import org.slf4j.Logger; - -import java.io.IOException; -import java.util.Arrays; -import java.util.Locale; -import java.util.Map; -import java.util.function.Consumer; -import java.util.stream.Collectors; - -/** - * Contains customizations for Azure Search's service swagger code generation. - */ -public class SearchServiceCustomizations extends Customization { - private static final String VARARG_METHOD_BLOCK_TEMPLATE = joinWithNewline("{", - " this.%1$s = (%1$s == null) ? null : Arrays.asList(%1$s);", " return this;", "}"); - - // Packages - private static final String IMPLEMENTATION_MODELS = "com.azure.search.documents.indexes.implementation.models"; - private static final String MODELS = "com.azure.search.documents.indexes.models"; - - @Override - public void customize(LibraryCustomization libraryCustomization, Logger logger) { - PackageCustomization implCustomization = libraryCustomization.getPackage(IMPLEMENTATION_MODELS); - PackageCustomization publicCustomization = libraryCustomization.getPackage(MODELS); - - // Customize implementation models. - - // Customize models. - - // Add vararg overloads to list setters. - customizeAst(publicCustomization.getClass("InputFieldMappingEntry"), - clazz -> addVarArgsOverload(clazz, "inputs", "InputFieldMappingEntry")); - customizeAst(publicCustomization.getClass("ScoringProfile"), - clazz -> addVarArgsOverload(clazz, "functions", "ScoringFunction")); - - // More complex customizations. - customizeSearchIndex(publicCustomization.getClass("SearchIndex")); - customizeSearchIndexer(publicCustomization.getClass("SearchIndexer")); - customizeSearchIndexerSkill(publicCustomization.getClass("SearchIndexerSkill"), - libraryCustomization.getRawEditor()); - customizeTokenFilter(publicCustomization.getClass("TokenFilter"), libraryCustomization.getRawEditor()); - customizeLexicalTokenizer(publicCustomization.getClass("LexicalTokenizer"), - libraryCustomization.getRawEditor()); - customizeMagnitudeScoringParameters(publicCustomization.getClass("MagnitudeScoringParameters")); - customizeSearchFieldDataType(publicCustomization.getClass("SearchFieldDataType")); - customizeCognitiveServicesAccountKey(publicCustomization.getClass("CognitiveServicesAccountKey")); - customizeOcrSkill(publicCustomization.getClass("OcrSkill")); - customizeImageAnalysisSkill(publicCustomization.getClass("ImageAnalysisSkill")); - customizeCustomEntityLookupSkill(publicCustomization.getClass("CustomEntityLookupSkill")); - customizeSearchField(publicCustomization.getClass("SearchField")); - customizeSynonymMap(publicCustomization.getClass("SynonymMap")); - customizeSearchResourceEncryptionKey(publicCustomization.getClass("SearchResourceEncryptionKey"), - implCustomization.getClass("AzureActiveDirectoryApplicationCredentials")); - customizeSearchSuggester(publicCustomization.getClass("SearchSuggester")); - customizeCustomAnalyzer(publicCustomization.getClass("CustomAnalyzer")); - customizePatternAnalyzer(publicCustomization.getClass("PatternAnalyzer")); - customizeLuceneStandardAnalyzer(publicCustomization.getClass("LuceneStandardAnalyzer")); - customizeStopAnalyzer(publicCustomization.getClass("StopAnalyzer")); - customizeSearchIndexerSkillset(publicCustomization.getClass("SearchIndexerSkillset")); - customizeCjkBigramTokenFilter(publicCustomization.getClass("CjkBigramTokenFilter")); - customizeKeepTokenFilter(publicCustomization.getClass("KeepTokenFilter")); - customizeSynonymTokenFilter(publicCustomization.getClass("SynonymTokenFilter")); - customizeShingleTokenFilter(publicCustomization.getClass("ShingleTokenFilter")); - customizeLimitTokenFilter(publicCustomization.getClass("LimitTokenFilter")); - customizePhoneticTokenFilter(publicCustomization.getClass("PhoneticTokenFilter")); - customizeStopwordsTokenFilter(publicCustomization.getClass("StopwordsTokenFilter")); - customizeWordDelimiterTokenFilter(publicCustomization.getClass("WordDelimiterTokenFilter")); - customizeElisionTokenFilter(publicCustomization.getClass("ElisionTokenFilter")); - customizeNGramTokenizer(publicCustomization.getClass("NGramTokenizer")); - customizeEdgeNGramTokenizer(publicCustomization.getClass("EdgeNGramTokenizer")); - customizeMicrosoftLanguageStemmingTokenizer(publicCustomization.getClass("MicrosoftLanguageStemmingTokenizer")); - customizePatternTokenizer(publicCustomization.getClass("PatternTokenizer")); - customizeIndexingParameters(publicCustomization.getClass("IndexingParameters"), - libraryCustomization.getRawEditor()); - customizeSearchIndexerDataSourceConnection(publicCustomization.getClass("SearchIndexerDataSourceConnection")); - customizeSemanticPrioritizedFields(publicCustomization.getClass("SemanticPrioritizedFields")); - customizeVectorSearch(publicCustomization.getClass("VectorSearch")); - customizeAzureOpenAIModelName(publicCustomization.getClass("AzureOpenAIModelName")); - // customizeSearchError(implCustomization.getClass("SearchError")); - customizeSplitSkillEncoderModelName(publicCustomization.getClass("SplitSkillEncoderModelName")); - - bulkRemoveFromJsonMethods(publicCustomization.getClass("SearchIndexerKnowledgeStoreProjectionSelector"), - publicCustomization.getClass("SearchIndexerKnowledgeStoreBlobProjectionSelector")); - } - - private static void customizeAst(ClassCustomization classCustomization, - Consumer consumer) { - classCustomization.customizeAst(ast -> consumer.accept(ast.getClassByName(classCustomization.getClassName()) - .orElseThrow(() -> new RuntimeException("Class not found. " + classCustomization.getClassName())))); - } - - private void customizeSearchIndex(ClassCustomization classCustomization) { - customizeAst(classCustomization, clazz -> { - clazz.addConstructor(com.github.javaparser.ast.Modifier.Keyword.PUBLIC) - .addParameter("String", "name") - .addParameter("List", "fields") - .setBody(StaticJavaParser.parseBlock( - joinWithNewline("{", " this.name = name;", " this.fields = fields;", "}"))) - .setJavadocComment(StaticJavaParser.parseJavadoc( - joinWithNewline("Constructor of {@link SearchIndex}.", "@param name The name of the index.", - "@param fields The fields of the index."))); - - addVarArgsOverload(clazz, "fields", "SearchField"); - addVarArgsOverload(clazz, "scoringProfiles", "ScoringProfile"); - addVarArgsOverload(clazz, "suggesters", "SearchSuggester"); - addVarArgsOverload(clazz, "analyzers", "LexicalAnalyzer"); - addVarArgsOverload(clazz, "tokenizers", "LexicalTokenizer"); - addVarArgsOverload(clazz, "tokenFilters", "TokenFilter"); - addVarArgsOverload(clazz, "charFilters", "CharFilter"); - }); - } - - private void customizeSearchIndexer(ClassCustomization classCustomization) { - customizeAst(classCustomization, clazz -> { - clazz.addConstructor(com.github.javaparser.ast.Modifier.Keyword.PUBLIC) - .addParameter("String", "name") - .addParameter("String", "dataSourceName") - .addParameter("String", "targetIndexName") - .setBody(StaticJavaParser.parseBlock( - joinWithNewline("{", " this.name = name;", " this.dataSourceName = dataSourceName;", - " this.targetIndexName = targetIndexName;", "}"))) - .setJavadocComment(StaticJavaParser.parseJavadoc( - joinWithNewline("Constructor of {@link SearchIndexer}.", "", "@param name The name of the indexer.", - "@param dataSourceName The name of the datasource from which this indexer reads data.", - "@param targetIndexName The name of the index to which this indexer writes data."))); - - addVarArgsOverload(clazz, "fieldMappings", "FieldMapping"); - addVarArgsOverload(clazz, "outputFieldMappings", "FieldMapping"); - }); - } - - private void customizeSearchFieldDataType(ClassCustomization classCustomization) { - customizeAst(classCustomization, clazz -> { - clazz.addMethod("collection", com.github.javaparser.ast.Modifier.Keyword.PUBLIC, - com.github.javaparser.ast.Modifier.Keyword.STATIC) - .setType(classCustomization.getClassName()) - .addParameter(classCustomization.getClassName(), "dataType") - .setBody(StaticJavaParser.parseBlock(joinWithNewline("{", - " return fromString(String.format(\"Collection(%s)\", dataType.toString()));", "}"))) - .setJavadocComment(StaticJavaParser.parseJavadoc( - joinWithNewline("Returns a collection of a specific SearchFieldDataType.", "", - "@param dataType the corresponding SearchFieldDataType", - "@return a Collection of the corresponding SearchFieldDataType"))); - }); - } - - private void customizeSearchIndexerSkill(ClassCustomization classCustomization, Editor editor) { - String fileContents = editor.getFileContent(classCustomization.getFileName()); - - fileContents = updateVersionedDeserialization(fileContents, "EntityRecognitionSkillV1", - "EntityRecognitionSkill"); - fileContents = updateVersionedDeserialization(fileContents, "EntityRecognitionSkillV3", - "EntityRecognitionSkill"); - fileContents = updateVersionedDeserialization(fileContents, "SentimentSkillV1", "SentimentSkill"); - fileContents = updateVersionedDeserialization(fileContents, "SentimentSkillV3", "SentimentSkill"); - - editor.replaceFile(classCustomization.getFileName(), fileContents); - } - - private void customizeTokenFilter(ClassCustomization classCustomization, Editor editor) { - String fileContents = editor.getFileContent(classCustomization.getFileName()); - - fileContents = updateVersionedDeserialization(fileContents, "EdgeNGramTokenFilterV1", "EdgeNGramTokenFilter"); - fileContents = updateVersionedDeserialization(fileContents, "EdgeNGramTokenFilterV2", "EdgeNGramTokenFilter"); - fileContents = updateVersionedDeserialization(fileContents, "NGramTokenFilterV1", "NGramTokenFilter"); - fileContents = updateVersionedDeserialization(fileContents, "NGramTokenFilterV2", "NGramTokenFilter"); - - editor.replaceFile(classCustomization.getFileName(), fileContents); - } - - private void customizeLexicalTokenizer(ClassCustomization classCustomization, Editor editor) { - String fileContents = editor.getFileContent(classCustomization.getFileName()); - - fileContents = updateVersionedDeserialization(fileContents, "KeywordTokenizerV1", "KeywordTokenizer"); - fileContents = updateVersionedDeserialization(fileContents, "KeywordTokenizerV2", "KeywordTokenizer"); - fileContents = updateVersionedDeserialization(fileContents, "LuceneStandardTokenizerV1", - "LuceneStandardTokenizer"); - fileContents = updateVersionedDeserialization(fileContents, "LuceneStandardTokenizerV2", - "LuceneStandardTokenizer"); - - editor.replaceFile(classCustomization.getFileName(), fileContents); - } - - private String updateVersionedDeserialization(String fileContents, String codegenName, String Name) { - String target = String.format("return %1$s.fromJson(readerToUse);", codegenName); - String replacement = String.format(joinWithNewline("%1$s codegen = %1$s.fromJson(readerToUse);", - "return (codegen == null) ? null : new %2$s(codegen);"), codegenName, Name); - - return fileContents.replace(target, replacement); - } - - private void customizeMagnitudeScoringParameters(ClassCustomization classCustomization) { - customizeAst(classCustomization, clazz -> clazz.getMethodsByName("isShouldBoostBeyondRangeByConstant") - .get(0) - .setName("shouldBoostBeyondRangeByConstant")); - } - - private void customizeCognitiveServicesAccountKey(ClassCustomization classCustomization) { - customizeAst(classCustomization, clazz -> { - clazz.getFieldByName("key").get().setModifiers(com.github.javaparser.ast.Modifier.Keyword.PRIVATE); - clazz.addMethod("setKey", com.github.javaparser.ast.Modifier.Keyword.PUBLIC) - .setType(classCustomization.getClassName()) - .addParameter("String", "key") - .setBody( - StaticJavaParser.parseBlock(joinWithNewline("{", " this.key = key;", " return this;", "}"))) - .setJavadocComment(StaticJavaParser.parseJavadoc(joinWithNewline( - "Set the key property: The key used to provision the cognitive service resource attached to a skillset.", - "", "@param key the key value to set.", "@return the CognitiveServicesAccountKey object itself."))); - }); - } - - private void customizeOcrSkill(ClassCustomization classCustomization) { - customizeAst(classCustomization, clazz -> { - clazz.addMethod("setShouldDetectOrientation", com.github.javaparser.ast.Modifier.Keyword.PUBLIC) - .setType("Boolean") - .setBody( - StaticJavaParser.parseBlock(joinWithNewline("{", " return this.shouldDetectOrientation;", "}"))) - .addAnnotation("Deprecated") - .setJavadocComment(StaticJavaParser.parseJavadoc(joinWithNewline( - "Get the shouldDetectOrientation property: A value indicating to turn orientation detection on or not. Default is", - "false.", "", "@return the shouldDetectOrientation value.", - "@deprecated Use {@link #isShouldDetectOrientation()} instead."))); - }); - } - - private void customizeImageAnalysisSkill(ClassCustomization classCustomization) { - customizeAst(classCustomization, clazz -> { - addVarArgsOverload(clazz, "visualFeatures", "VisualFeature"); - addVarArgsOverload(clazz, "details", "ImageDetail"); - }); - } - - private void customizeCustomEntityLookupSkill(ClassCustomization classCustomization) { - customizeAst(classCustomization, - clazz -> addVarArgsOverload(clazz, "inlineEntitiesDefinition", "CustomEntity")); - } - - private void customizeSearchField(ClassCustomization classCustomization) { - customizeAst(classCustomization, clazz -> { - clazz.getMethodsByName("setHidden") - .get(0) - .setBody(StaticJavaParser.parseBlock( - joinWithNewline("{", " this.hidden = (hidden == null) ? null : !hidden;", " return this;", - "}"))); - - clazz.getMethodsByName("isHidden") - .get(0) - .setBody(StaticJavaParser.parseBlock( - joinWithNewline("{", " return (this.hidden == null) ? null : !this.hidden;", "}"))); - - addVarArgsOverload(clazz, "fields", "SearchField"); - addVarArgsOverload(clazz, "synonymMapNames", "String"); - }); - } - - private void customizeSynonymMap(ClassCustomization classCustomization) { - customizeAst(classCustomization, clazz -> { - clazz.getMethodsByName("getFormat").forEach(MethodDeclaration::remove); - clazz.getMethodsByName("setFormat").forEach(MethodDeclaration::remove); - clazz.getMethodsByName("setName").forEach(MethodDeclaration::remove); - - clazz.addConstructor(com.github.javaparser.ast.Modifier.Keyword.PUBLIC) - .setJavadocComment(StaticJavaParser.parseJavadoc( - joinWithNewline("Constructor of {@link SynonymMap}.", "@param name The name of the synonym map."))) - .addParameter("String", "name") - .getBody() - .addStatement(StaticJavaParser.parseExplicitConstructorInvocationStmt("this(name,null);")); - - clazz.addConstructor(com.github.javaparser.ast.Modifier.Keyword.PUBLIC) - .addParameter("String", "name") - .addParameter("String", "synonyms") - .setBody(StaticJavaParser.parseBlock( - joinWithNewline("{", " this.format = \"solr\";", " this.name = name;", - " this.synonyms = synonyms;", "}"))) - .setJavadocComment(StaticJavaParser.parseJavadoc( - joinWithNewline("Constructor of {@link SynonymMap}.", "@param name The name of the synonym map.", - "@param synonyms A series of synonym rules in the specified synonym map format. The rules must be separated by newlines."))); - - clazz.addMethod("createFromFile", com.github.javaparser.ast.Modifier.Keyword.PUBLIC, - com.github.javaparser.ast.Modifier.Keyword.STATIC) - .setType("SynonymMap") - .addParameter("String", "name") - .addParameter("java.nio.file.Path", "filePath") - .setBody(StaticJavaParser.parseBlock(joinWithNewline("{", - " String synonyms = com.azure.search.documents.implementation.util.Utility.readSynonymsFromFile(filePath);", - " return new SynonymMap(name, synonyms);", "}"))) - .setJavadocComment(StaticJavaParser.parseJavadoc( - joinWithNewline("Creates a new instance of SynonymMap with synonyms read from the passed file.", "", - "@param name The name of the synonym map.", - "@param filePath The path to the file where the formatted synonyms are read.", - "@return A SynonymMap.", - "@throws java.io.UncheckedIOException If reading {@code filePath} fails."))); - }); - } - - private void customizeSearchResourceEncryptionKey(ClassCustomization keyCustomization, - ClassCustomization credentialCustomization) { - keyCustomization.removeMethod("getAccessCredentials"); - customizeAst(keyCustomization, clazz -> { - clazz.getMethodsByName("setAccessCredentials").get(0).remove(); - - clazz.addMethod("getApplicationId", Modifier.Keyword.PUBLIC) - .setType(String.class) - .setBody(StaticJavaParser.parseBlock("{\n" - + " return (this.accessCredentials == null) ? null : this.accessCredentials.getApplicationId();\n" - + " }")) - .setJavadocComment(StaticJavaParser.parseJavadoc( - "* Get the applicationId property: An AAD Application ID that was granted the required access permissions to the\n" - + " * Azure Key Vault that is to be used when encrypting your data at rest. The Application ID should not be confused\n" - + " * with the Object ID for your AAD Application.\n" + " * \n" - + " * @return the applicationId value.")); - - clazz.addMethod("setApplicationId", Modifier.Keyword.PUBLIC) - .setType(keyCustomization.getClassName()) - .addParameter(String.class, "applicationId") - .setBody(StaticJavaParser.parseBlock("{\n" + " if (this.accessCredentials == null) {\n" - + " this.accessCredentials = new AzureActiveDirectoryApplicationCredentials();\n" - + " }\n" + " this.accessCredentials.setApplicationId(applicationId);\n" - + " return this;\n" + " }")) - .setJavadocComment(StaticJavaParser.parseJavadoc( - "* Set the applicationId property: An AAD Application ID that was granted the required access permissions to the\n" - + " * Azure Key Vault that is to be used when encrypting your data at rest. The Application ID should not be confused\n" - + " * with the Object ID for your AAD Application.\n" + " * \n" - + " * @param applicationId the applicationId value to set.\n" - + " * @return the SearchResourceEncryptionKey object itself.")); - - clazz.addMethod("getApplicationSecret", Modifier.Keyword.PUBLIC) - .setType(String.class) - .setBody(StaticJavaParser.parseBlock("{\n" - + " return (this.accessCredentials == null) ? null : this.accessCredentials.getApplicationSecret();\n" - + " }")) - .setJavadocComment(StaticJavaParser.parseJavadoc( - "* Get the applicationSecret property: The authentication key of the specified AAD application.\n" - + " * \n" + " * @return the applicationSecret value.")); - - clazz.addMethod("setApplicationSecret", Modifier.Keyword.PUBLIC) - .setType(keyCustomization.getClassName()) - .addParameter(String.class, "applicationSecret") - .setBody(StaticJavaParser.parseBlock("{\n" + " if (this.accessCredentials == null) {\n" - + " this.accessCredentials = new AzureActiveDirectoryApplicationCredentials();\n" - + " }\n" + " this.accessCredentials.setApplicationSecret(applicationSecret);\n" - + " return this;\n" + " }")) - .setJavadocComment(StaticJavaParser.parseJavadoc( - "* Set the applicationSecret property: The authentication key of the specified AAD application.\n" - + " * \n" + " * @param applicationSecret the applicationSecret value to set.\n" - + " * @return the SearchResourceEncryptionKey object itself.")); - }); - } - - private void customizeSearchSuggester(ClassCustomization classCustomization) { - customizeAst(classCustomization, clazz -> { - clazz.getConstructors() - .get(0) - .setBody(StaticJavaParser.parseBlock( - joinWithNewline("{", " this.searchMode = \"analyzingInfixMatching\";", - " this.sourceFields = sourceFields;", " this.name = name;", "}"))); - - clazz.getMethodsByName("setSearchMode").forEach(MethodDeclaration::remove); - }); - } - - private void customizeCustomAnalyzer(ClassCustomization classCustomization) { - customizeAst(classCustomization, clazz -> { - addVarArgsOverload(clazz, "tokenFilters", "TokenFilterName"); - addVarArgsOverload(clazz, "charFilters", "CharFilterName"); - }); - } - - private void customizePatternAnalyzer(ClassCustomization classCustomization) { - customizeAst(classCustomization, clazz -> { - clazz.tryAddImportToParentCompilationUnit(Arrays.class); - - clazz.getMethodsByName("isLowerCaseTerms").get(0).setName("areLowerCaseTerms"); - addVarArgsOverload(clazz, "stopwords", "String"); - - clazz.getMethodsByName("getFlags") - .get(0) - .setType("List") - .setBody(StaticJavaParser.parseBlock( - joinWithNewline("{", " if (this.flags == null) {", " return null;", " } else {", - " String[] flagStrings = this.flags.toString().split(\"\\\\|\");", - " return Arrays.stream(flagStrings).map(RegexFlags::fromString).collect(Collectors.toList());", - " }", "}"))); - - clazz.tryAddImportToParentCompilationUnit(Collectors.class); - - clazz.getMethodsByName("setFlags") - .get(0) - .setParameters(new NodeList<>(new Parameter().setType("List").setName("flags"))) - .setBody(StaticJavaParser.parseBlock( - joinWithNewline("{", " if (flags == null) {", " this.flags = null;", " } else {", - " String flagString = flags.stream().map(RegexFlags::toString).collect(Collectors.joining(\"|\"));", - " this.flags = RegexFlags.fromString(flagString);", " }", "", " return this;", - "}"))); - - addVarArgsOverload(clazz, "flags", "RegexFlags").setBody(StaticJavaParser.parseBlock( - joinWithNewline("{", " if (flags == null) {", " this.flags = null;", " return this;", - " } else {", " return setFlags(Arrays.asList(flags));", " }", "}"))); - }); - } - - private void customizeLuceneStandardAnalyzer(ClassCustomization classCustomization) { - customizeAst(classCustomization, clazz -> addVarArgsOverload(clazz, "stopwords", "String")); - } - - private void customizeStopAnalyzer(ClassCustomization classCustomization) { - customizeAst(classCustomization, clazz -> addVarArgsOverload(clazz, "stopwords", "String")); - } - - private void customizeSearchIndexerSkillset(ClassCustomization classCustomization) { - customizeAst(classCustomization, clazz -> { - clazz.addConstructor(com.github.javaparser.ast.Modifier.Keyword.PUBLIC) - .addParameter("String", "name") - .addParameter("List", "skills") - .setBody( - new BlockStmt().addStatement(StaticJavaParser.parseExplicitConstructorInvocationStmt("this(name);")) - .addStatement(StaticJavaParser.parseStatement("this.skills = skills;"))) - .setJavadocComment(StaticJavaParser.parseJavadoc( - joinWithNewline("/**", " * Creates an instance of SearchIndexerSkillset class.", - " * @param name The name of the skillset.", " * @param skills The skills in the skillset.", - " */"))); - - addVarArgsOverload(clazz, "skills", "SearchIndexerSkill"); - }); - } - - private void customizeCjkBigramTokenFilter(ClassCustomization classCustomization) { - customizeAst(classCustomization, clazz -> { - clazz.getMethodsByName("isOutputUnigrams").get(0).setName("areOutputUnigrams"); - addVarArgsOverload(clazz, "ignoreScripts", "CjkBigramTokenFilterScripts"); - }); - } - - private void customizeKeepTokenFilter(ClassCustomization classCustomization) { - customizeAst(classCustomization, - clazz -> clazz.getMethodsByName("isLowerCaseKeepWords").get(0).setName("areLowerCaseKeepWords")); - } - - private void customizeSynonymTokenFilter(ClassCustomization classCustomization) { - customizeAst(classCustomization, clazz -> clazz.getMethodsByName("isExpand").get(0).setName("getExpand")); - } - - private void customizeShingleTokenFilter(ClassCustomization classCustomization) { - customizeAst(classCustomization, clazz -> { - clazz.getMethodsByName("isOutputUnigrams").get(0).setName("areOutputUnigrams"); - clazz.getMethodsByName("isOutputUnigramsIfNoShingles").get(0).setName("areOutputUnigramsIfNoShingles"); - }); - } - - private void customizeLimitTokenFilter(ClassCustomization classCustomization) { - customizeAst(classCustomization, - clazz -> clazz.getMethodsByName("isAllTokensConsumed").get(0).setName("areAllTokensConsumed")); - } - - private void customizePhoneticTokenFilter(ClassCustomization classCustomization) { - customizeAst(classCustomization, - clazz -> clazz.getMethodsByName("isOriginalTokensReplaced").get(0).setName("areOriginalTokensReplaced")); - } - - private void customizeStopwordsTokenFilter(ClassCustomization classCustomization) { - customizeAst(classCustomization, clazz -> { - clazz.getMethodsByName("isTrailingStopWordsRemoved").get(0).setName("areTrailingStopWordsRemoved"); - - addVarArgsOverload(clazz, "stopwords", "String"); - }); - } - - private void customizeNGramTokenizer(ClassCustomization classCustomization) { - customizeAst(classCustomization, clazz -> addVarArgsOverload(clazz, "tokenChars", "TokenCharacterKind")); - } - - private void customizeEdgeNGramTokenizer(ClassCustomization classCustomization) { - customizeAst(classCustomization, clazz -> addVarArgsOverload(clazz, "tokenChars", "TokenCharacterKind")); - } - - private void customizeWordDelimiterTokenFilter(ClassCustomization classCustomization) { - customizeAst(classCustomization, clazz -> { - clazz.getMethodsByName("isGenerateWordParts").get(0).setName("generateWordParts"); - clazz.getMethodsByName("isGenerateNumberParts").get(0).setName("generateNumberParts"); - clazz.getMethodsByName("isWordsCatenated").get(0).setName("areWordsCatenated"); - clazz.getMethodsByName("isNumbersCatenated").get(0).setName("areNumbersCatenated"); - clazz.getMethodsByName("isCatenateAll").get(0).setName("catenateAll"); - clazz.getMethodsByName("isSplitOnCaseChange").get(0).setName("splitOnCaseChange"); - clazz.getMethodsByName("isSplitOnNumerics").get(0).setName("splitOnNumerics"); - - addVarArgsOverload(clazz, "protectedWords", "String"); - }); - } - - private void customizeElisionTokenFilter(ClassCustomization classCustomization) { - customizeAst(classCustomization, clazz -> addVarArgsOverload(clazz, "articles", "String")); - } - - private void customizeMicrosoftLanguageStemmingTokenizer(ClassCustomization classCustomization) { - customizeAst(classCustomization, - clazz -> clazz.getMethodsByName("isSearchTokenizerUsed").get(0).setName("isSearchTokenizer")); - } - - private void customizePatternTokenizer(ClassCustomization classCustomization) { - customizeAst(classCustomization, clazz -> { - clazz.tryAddImportToParentCompilationUnit(Arrays.class); - - clazz.getMethodsByName("getFlags") - .get(0) - .setType("List") - .setBody(StaticJavaParser.parseBlock( - joinWithNewline("{", " if (this.flags == null) {", " return null;", " } else {", - " String[] flagStrings = this.flags.toString().split(\"\\\\|\");", - " return Arrays.stream(flagStrings).map(RegexFlags::fromString).collect(Collectors.toList());", - " }", "}"))); - - clazz.tryAddImportToParentCompilationUnit(Collectors.class); - - clazz.getMethodsByName("setFlags") - .get(0) - .setParameters(new NodeList<>(new Parameter().setType("List").setName("flags"))) - .setBody(StaticJavaParser.parseBlock( - joinWithNewline("{", " if (flags == null) {", " this.flags = null;", " } else {", - " String flagString = flags.stream().map(RegexFlags::toString).collect(Collectors.joining(\"|\"));", - " this.flags = RegexFlags.fromString(flagString);", " }", "", " return this;", - "}"))); - - addVarArgsOverload(clazz, "flags", "RegexFlags").setBody(StaticJavaParser.parseBlock( - joinWithNewline("{", " if (flags == null) {", " this.flags = null;", " return this;", - " } else {", " return setFlags(Arrays.asList(flags));", " }", "}"))); - }); - } - - private void customizeIndexingParameters(ClassCustomization classCustomization, Editor editor) { - customizeAst(classCustomization, clazz -> { - clazz.addPrivateField("Map", "configurationMap"); - clazz.tryAddImportToParentCompilationUnit(Map.class); - - clazz.getMethodsByName("getConfiguration").get(0).setName("getIndexingParametersConfiguration"); - clazz.getMethodsByName("setConfiguration") - .get(0) - .setName("setIndexingParametersConfiguration") - .setBody(StaticJavaParser.parseBlock(joinWithNewline("{", " this.configuration = configuration;", - " this.configurationMap = MappingUtils.indexingParametersConfigurationToMap(configuration);", - " return this;", "}"))); - - clazz.findAncestor(CompilationUnit.class) - .ifPresent(p -> p.addImport("com.azure.search.documents.implementation.util.MappingUtils")); - - clazz.addMethod("getConfiguration", com.github.javaparser.ast.Modifier.Keyword.PUBLIC) - .setType("Map") - .setBody(StaticJavaParser.parseBlock(joinWithNewline("{", " return this.configurationMap;", "}"))) - .setJavadocComment(StaticJavaParser.parseJavadoc(joinWithNewline( - "Get the configuration property: A dictionary of indexer-specific configuration properties. " - + "Each name is the name of a specific property. Each value must be of a primitive type.", "", - "@return the configuration value."))); - - clazz.addMethod("setConfiguration", com.github.javaparser.ast.Modifier.Keyword.PUBLIC) - .setType("IndexingParameters") - .addParameter("Map", "configuration") - .setBody(StaticJavaParser.parseBlock(joinWithNewline("{", " this.configurationMap = configuration;", - " this.configuration = MappingUtils.mapToIndexingParametersConfiguration(configuration);", - " return this;", "}"))) - .setJavadocComment(StaticJavaParser.parseJavadoc(joinWithNewline( - "Set the configuration property: A dictionary of indexer-specific configuration properties. " - + "Each name is the name of a specific property. Each value must be of a primitive type.", "", - "@param configuration the configuration value to set.", - "@return the IndexingParameters object itself."))); - }); - - String replacement = editor.getFileContent(classCustomization.getFileName()) - .replace("deserializedValue.configuration = configuration;", - "deserializedValue.setIndexingParametersConfiguration(configuration);"); - editor.replaceFile(classCustomization.getFileName(), replacement); - } - - private void customizeSearchIndexerDataSourceConnection(ClassCustomization classCustomization) { - customizeAst(classCustomization, clazz -> { - clazz.addConstructor(com.github.javaparser.ast.Modifier.Keyword.PUBLIC) - .addParameter("String", "name") - .addParameter("SearchIndexerDataSourceType", "type") - .addParameter("String", "connectionString") - .addParameter("SearchIndexerDataContainer", "container") - .setBody(StaticJavaParser.parseBlock( - joinWithNewline("{", " this.name = name;", " this.type = type;", - " this.credentials = (connectionString == null) ? null : new DataSourceCredentials().setConnectionString(connectionString);", - " this.container = container;", "}"))) - .setJavadocComment(StaticJavaParser.parseJavadoc( - joinWithNewline("Constructor of {@link SearchIndexerDataSourceConnection}.", "", - "@param name The name of the datasource.", "@param type The type of the datasource.", - "@param connectionString The connection string for the datasource.", - "@param container The data container for the datasource."))); - - clazz.getMethodsByName("getCredentials").forEach(MethodDeclaration::remove); - clazz.getMethodsByName("setCredentials").forEach(MethodDeclaration::remove); - - clazz.addMethod("getConnectionString", com.github.javaparser.ast.Modifier.Keyword.PUBLIC) - .setType("String") - .setBody(StaticJavaParser.parseBlock( - joinWithNewline("{", " return (credentials == null) ? null : credentials.getConnectionString();", - "}"))) - .setJavadocComment(StaticJavaParser.parseJavadoc( - joinWithNewline("Get the connectionString property: The connection string for the datasource.", "", - "@return the connectionString value."))); - - clazz.addMethod("setConnectionString", com.github.javaparser.ast.Modifier.Keyword.PUBLIC) - .setType("SearchIndexerDataSourceConnection") - .addParameter("String", "connectionString") - .setBody(StaticJavaParser.parseBlock( - joinWithNewline("{", " if (connectionString == null) {", " this.credentials = null;", - " } else if (credentials == null) {", - " this.credentials = new DataSourceCredentials().setConnectionString(connectionString);", - " } else {", " credentials.setConnectionString(connectionString);", " }", - " return this;", "}"))) - .setJavadocComment(StaticJavaParser.parseJavadoc( - joinWithNewline("Set the connectionString property: The connection string for the datasource.", "", - "@param connectionString the connectionString value to set.", - "@return the SearchIndexerDataSourceConnection object itself."))); - }); - } - - private static void customizeSemanticPrioritizedFields(ClassCustomization classCustomization) { - customizeAst(classCustomization, clazz -> { - clazz.tryAddImportToParentCompilationUnit(Arrays.class); - - addVarArgsOverload(clazz, "contentFields", "SemanticField"); - addVarArgsOverload(clazz, "keywordsFields", "SemanticField"); - }); - } - - private static void customizeVectorSearch(ClassCustomization classCustomization) { - customizeAst(classCustomization, clazz -> { - clazz.tryAddImportToParentCompilationUnit(Arrays.class); - - addVarArgsOverload(clazz, "profiles", "VectorSearchProfile"); - addVarArgsOverload(clazz, "algorithms", "VectorSearchAlgorithmConfiguration"); - addVarArgsOverload(clazz, "compressions", "VectorSearchCompression"); - addVarArgsOverload(clazz, "vectorizers", "VectorSearchVectorizer"); - }); - } - - private static void customizeAzureOpenAIModelName(ClassCustomization classCustomization) { - customizeAst(classCustomization, clazz -> { - clazz.getFieldByName("TEXT_EMBEDDING_ADA002").get().getVariable(0).setName("TEXT_EMBEDDING_ADA_002"); - clazz.getFieldByName("TEXT_EMBEDDING3LARGE").get().getVariable(0).setName("TEXT_EMBEDDING_3_LARGE"); - clazz.getFieldByName("TEXT_EMBEDDING3SMALL").get().getVariable(0).setName("TEXT_EMBEDDING_3_SMALL"); - }); - } - - private static void customizeSplitSkillEncoderModelName(ClassCustomization classCustomization) { - customizeAst(classCustomization, clazz -> { - clazz.getFieldByName("R50KBASE").get().getVariable(0).setName("R_50K_BASE"); - clazz.getFieldByName("P50KBASE").get().getVariable(0).setName("P_50K_BASE"); - clazz.getFieldByName("P50KEDIT").get().getVariable(0).setName("P_50K_EDIT"); - clazz.getFieldByName("CL100KBASE").get().getVariable(0).setName("CL_100K_BASE"); - }); - } - - private void customizeSearchError(ClassCustomization classCustomization) { - customizeAst(classCustomization, clazz -> { - MethodDeclaration fromJson = clazz.getMethodsByName("fromJson").get(0); - - clazz.addMethod("readSearchError", Modifier.Keyword.PRIVATE, Modifier.Keyword.STATIC) - .setType("SearchError") - .addParameter("JsonReader", "jsonReader") - .addThrownException(IOException.class) - .setBody(fromJson.getBody().get()); - - fromJson.setBody(StaticJavaParser.parseBlock( - joinWithNewline("{", "return jsonReader.readObject(reader -> {", - " // Buffer the next JSON object as SearchError can take two forms:", " //", - " // - A SearchError object", " // - A SearchError object wrapped in an \"error\" node.", - " JsonReader bufferedReader = reader.bufferObject();", - " bufferedReader.nextToken(); // Get to the START_OBJECT token.", - " while (bufferedReader.nextToken() != JsonToken.END_OBJECT) {", - " String fieldName = bufferedReader.getFieldName();", " bufferedReader.nextToken();", - "", " if (\"error\".equals(fieldName)) {", - " // If the SearchError was wrapped in the \"error\" node begin reading it now.", - " return readSearchError(bufferedReader);", " } else {", - " bufferedReader.skipChildren();", " }", " }", "", - " // Otherwise reset the JsonReader and read the whole JSON object.", - " return readSearchError(bufferedReader.reset());", "});", "}"))); - }); - } - - private static void bulkRemoveFromJsonMethods(ClassCustomization... classCustomizations) { - for (ClassCustomization classCustomization : classCustomizations) { - classCustomization.removeMethod("fromJson(JsonReader jsonReader)"); - } - } - - /* - * This helper function adds a varargs overload in addition to a List setter. - */ - private static MethodDeclaration addVarArgsOverload(ClassOrInterfaceDeclaration clazz, String parameterName, - String parameterType) { - clazz.tryAddImportToParentCompilationUnit(Arrays.class); - - String methodName = "set" + parameterName.substring(0, 1).toUpperCase(Locale.ROOT) + parameterName.substring(1); - - MethodDeclaration nonVarArgOverload = clazz.getMethodsByName(methodName).get(0); - - return clazz.addMethod(methodName, com.github.javaparser.ast.Modifier.Keyword.PUBLIC) - .setType(clazz.getNameAsString()) - .addParameter(new Parameter().setType(parameterType).setName(parameterName).setVarArgs(true)) - .setBody(StaticJavaParser.parseBlock(String.format(VARARG_METHOD_BLOCK_TEMPLATE, parameterName))) - .setJavadocComment(nonVarArgOverload.getJavadoc().get()); - } - - private static String joinWithNewline(String... lines) { - return String.join("\n", lines); - } -} diff --git a/sdk/search/azure-search-documents/tsp-location.yaml b/sdk/search/azure-search-documents/tsp-location.yaml new file mode 100644 index 000000000000..ef2208a33bea --- /dev/null +++ b/sdk/search/azure-search-documents/tsp-location.yaml @@ -0,0 +1,4 @@ +directory: specification/search/Azure.Search +commit: 291502c680831a58ea2408b1d5722e1f2603cc6b +repo: Azure/azure-rest-api-specs +additionalDirectories: